您可以使用 Arrays.deepEquals()。为了正确使用它,您需要覆盖 hashCode() 和 equals()。这是示例代码。
class Category {
Integer id;
int catId;
String catTitle;
public Category(Integer id, int catId, String catTitle) {
this.id = id;
this.catId = catId;
this.catTitle = catTitle;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + catId;
result = prime * result + ((catTitle == null) ? 0 : catTitle.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Category other = (Category) obj;
if (catId != other.catId)
return false;
if (catTitle == null) {
if (other.catTitle != null)
return false;
} else if (!catTitle.equals(other.catTitle))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
现在你可以使用 Arrays.deepEquals() 作为
List<Category> list1 = Arrays.asList(new Category(1, 1001, "first"), new Category(2, 1001, "second"),
new Category(3, 1001, "third"), new Category(4, 1001, "four"));
//same as content of list1
List<Category> list2 = Arrays.asList(new Category(1, 1001, "first"), new Category(2, 1001, "second"),
new Category(3, 1001, "third"), new Category(4, 1001, "four"));
//change in catTitle
List<Category> list3 = Arrays.asList(new Category(1, 100, "list3first"),new Category(2, 1001, "list3second"),new Category(3, 1001, "list3third"),new Category(4, 1001, "list3"));
//returns true only if you override hashCode() and equals() otherwise you will get false
System.out.println("list1==list2 : "+Arrays.deepEquals(list1.toArray(), list2.toArray()));
System.out.println("list1==list3 : "+Arrays.deepEquals(list1.toArray(), list3.toArray()));
output
--------
list1==list2 : true
list1==list3 : false