gpt4 book ai didi

java - 为什么具有相同数据的两个不同的 HashSet 具有相同的 HashCode?

转载 作者:行者123 更新时间:2023-12-05 00:51:02 24 4
gpt4 key购买 nike

我最近在 leetcode 上遇到了一个问题,我用嵌套的哈希集解决了这个问题。这就是问题所在,如果您有兴趣:https://leetcode.com/problems/group-anagrams/ .

我的直觉是将每个单词的所有字母添加到一个哈希集中,然后将该哈希集放入另一个哈希集中。在每次迭代中,我会检查哈希集是否已经存在,如果存在,则添加到现有的哈希集中。

奇怪的是,这似乎有效。如果两个哈希集是不同的对象,为什么它们共享相同的哈希码?像 if(set1.hashCode() == set2.hashCode()) doStuff() 这样的代码是有效代码吗?

最佳答案

这是意料之中的。 HashSet扩展 AbstractSet . hashCode() AbstractSet 中的方法说:

Returns the hash code value for this set. The hash code of a set is defined to be the sum of the hash codes of the elements in the set, where the hash code of a null element is defined to be zero. This ensures that s1.equals(s2) implies that s1.hashCode()==s2.hashCode() for any two sets s1 and s2, as required by the general contract of Object.hashCode.

This implementation iterates over the set, calling the hashCode method on each element in the set, and adding up the results.

这是来自 AbstractSet 的代码:

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;
}

Why do 2 hashsets share the same hashcode if they are different objects?

使用 HashSet,hashCode 是使用集合的内容计算的。因为它只是数字加法,所以加法的顺序并不重要——只需将它们全部相加即可。因此,您有两个集合是有道理的,每个集合都包含等效的对象(因此应该具有匹配的 hashCode() 值),然后每个集合中的 hashCode 之和是相同的。

Would something like if(set1.hashCode() == set2.hashCode()) doStuff() be valid code?

当然。

编辑:比较两组是否相等的最佳方法是使用 equals()。在 AbstractSet 的情况下,调用 set1.equals(set2) 将导致在集合内的对象级别上单独调用 equals()(以及一些其他检查)。

关于java - 为什么具有相同数据的两个不同的 HashSet 具有相同的 HashCode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73046230/

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