// 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}
。加法是可交换的,因此添加元素的 hashCode 即可获得该属性。
列表是有序的,所以虽然[a, b, c]
may具有相同的哈希码[c, b, a]
,它不需要 - 如果不这样做会更好,因为尽可能多的不相等的对象应该尝试具有不相等的 hashCode。 ArrayList.hashCode 实现具有该属性。
请注意,Set 和 List 都定义了实现必须如何定义equals
and hashCode
(Set.hashCode https://docs.oracle.com/javase/8/docs/api/java/util/Set.html#hashCode--, List.hashCode https://docs.oracle.com/javase/8/docs/api/java/util/List.html#hashCode--),因此这些各自集合的任何(兼容)实现看起来几乎相同。这为您提供了一个有用的属性,即包含相同元素的 Set 与任何其他 Set 相等(因此具有相同的 hashCode),无论底层实现如何。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)