【问题标题】:Comparing objects, same content, different id (in eclipse debugger)比较对象,相同的内容,不同的 id(在 eclipse 调试器中)
【发布时间】:2012-07-03 07:57:15
【问题描述】:

我的想法不多了...我正在比较两个对象,它们都有一个自定义类型的数组列表字段。

两个对象都包含数组列表中的一个元素。

当我查看 Eclipse 调试器时,它看起来完全一样,直到最接近的细节,除了不同的 id(在调试器中看起来像:(id=111))

有趣的是,这个不同的 ID 位于一个整数类型(计数器)的字段上。这显然不应该发生,因为整数已经实现了等于和哈希码,对吧?

另一个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)   

【问题讨论】:

标签: java compare equals hashcode


【解决方案1】:

您可以简单地使用 ArrayList 超类的equals() implementation: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?

【讨论】:

    【解决方案2】:

    您如何比较您的 ArrayList?请发布一些代码。

    public static void main(String[] args) {
        List<String> list1 = new ArrayList<String>();
        List<String> list2 = new ArrayList<String>();
    
        list1.add("abcd");
        list2.add("abcd");
    
        if (list1.equals(list2)) {
            System.out.println("hello");
        }
    }
    

    打印你好。

    那你是做什么的?

    【讨论】:

    • 数组列表内置了equals和hashcode,我用equals方法比较两个对象
    • 我做 if(objectA.equals(objectB)) System.out.println("hello");
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2016-09-15
    相关资源
    最近更新 更多