我的想法已经用完了......我正在比较两个对象,它们都有一个自定义类型的数组列表字段。
两个对象都包含数组列表中的一个元素。
当我查看 eclipse 调试器时,它看起来完全一样,直到最接近的细节,除了不同的 id(在调试器中它看起来像 : (id=111))
有趣的是,这个不同的 ID 出现在一个类型为 Integer(计数器)的字段上。这显然不应该发生,因为整数已经实现了等于和哈希码,对吧?
另一个ID不同的字段是字符串类型(过滤器)
具有这些字段的两个对象之间的 equals 方法返回 false...我想不出为什么...所有 equals 和 hashCode 方法都在每个自定义类型中实现..
这是来自 eclipse 调试器:
对象 1:
Object (id=159)
arrayList ArrayList<E> (id=175)
[0] Item (id=175)
counter Integer (id=179)
filter "abcd" (id=181)
count 4
hash -717152022
offset 2
value (id=189)
对象 2:
Object (id=259)
arrayList ArrayList<E> (id=267)
[0] Item (id=268)
counter Integer (id=268)
filter "abcd" (id=269)
count 4
hash -717152022
offset 2
value (id=270)
最佳答案
您可以简单地使用 equals() implementation ArrayList 的父类(super class):AbstractList。
当且仅当您已经覆盖类 Item
中的 equals()
方法。
例如:
@Override
public boolean equals(Item item){
if(this.counter.equals(item.counter)
&& this.filter.equals(item.filter)){
// && etc for all Item fields that make the equality
return true;
}
return false;
}
另请注意,您不能依赖 hashCode 来比较相等性,请参阅这篇文章:Is Java hashCode() method a reliable measure of object equality?
关于java - 比较对象,相同的内容,不同的 id(在 eclipse 调试器中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11306702/