微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

两个列表在 equals() 函数下相等但具有不同的哈希码?

如何解决两个列表在 equals() 函数下相等但具有不同的哈希码?

我有两个在 equals() 方法下相等的 ArrayList,但它们具有不同的哈希码。这是怎么回事?

根据Java List API:“list1.equals(list2)意味着list1.hashCode()==list2.hashCode()对于任意两个列表,list1和list2,按照Object.hashCode的通用约定的要求()."

代码如下:

    List<nut> l1= new ArrayList<>(Arrays.asList(new nut((short) 4,(short) 2),new nut((short) 5,(short) 0),new nut((short) 1,(short) 3)));
    List<nut> l2= new ArrayList<>(Arrays.asList(new nut((short) 4,(short) 3)));
    System.out.println(l1.equals(l2));
    System.out.println(l1.hashCode());
    System.out.println(l2.hashCode());

输出: 真的 -2130368428 1856372392

解决方法

检查 equals()hashcode()AbstractList 的实现(ArrayList 正在扩展该类)

public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof List))
            return false;

        ListIterator<E> e1 = listIterator();
        ListIterator<?> e2 = ((List<?>) o).listIterator();
        while (e1.hasNext() && e2.hasNext()) {
            E o1 = e1.next();
            Object o2 = e2.next();
            if (!(o1==null ? o2==null : o1.equals(o2)))
                return false;
        }
        return !(e1.hasNext() || e2.hasNext());
}

public int hashCode() {
        int hashCode = 1;
        for (E e : this)
            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
        return hashCode;
}

它遍历列表中的对象并对它们调用 equals()/hashcode()。因此,处理此问题的责任在于您,因为您以泛型类型提供了 nut 类。

答案是:你在 hashcode() 课上搞砸了 equals()nut 之间的契约。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。