gpt4 book ai didi

java - 为什么 Java 对 Set 和 ArrayList 实现不同的 hashcode 方法?

转载 作者:搜寻专家 更新时间:2023-11-01 02:03:02 24 4
gpt4 key购买 nike

 // this is the hashCode method of Set
public int hashCode() {
int h = 0;
Iterator<E> i = iterator();
while (i.hasNext()) {
E obj = i.next();
if (obj != null)
h += obj.hashCode();
}
return h;
}



//this is the hashCode method of List
public int hashCode() {
int hashCode = 1;
for (E e : this)
hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
return hashCode;
}

为什么 java 使用这两种不同的方法? Set和List的特性有什么关系吗?为什么它使用 31 而不是其他数字?谢谢!

最佳答案

集合是无序的,因此 {a, b, c} 必须与 {c, b, a} 具有相同的哈希码。加法是可交换的,因此添加元素的 hashCodes 可以得到该属性。

列表是有序的,因此虽然 [a, b, c] 可能 具有与 [c, b, a] 相同的哈希码,它不需要——如果不这样做会更好,因为尽可能多的不相等的对象应该尝试具有不相等的 hashCode。 ArrayList.hashCode 实现具有该属性。

请注意,Set 和 List 都定义了实现必须如何定义 equalshashCode(Set.hashCodeList.hashCode),因此这些各自的任何(兼容)实现集合看起来几乎一样。这为您提供了一个有用的属性,即包含相同元素的 Set 与任何其他 Set 相等(因此具有相同的 hashCode),而不管底层实现如何。

关于java - 为什么 Java 对 Set 和 ArrayList 实现不同的 hashcode 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41111868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com