Java - 两个哈希集随着时间的推移是否会发生类似的变化?

标签 java hashset

我已经研究了不同的问题,但这些问题通常询问一致性或排序,而我对同时包含相同元素的两个 HashSet 的排序感兴趣。

我想创建一个包含整数的哈希集的哈希集。随着时间的推移,我会将大小为 3 的 HashSet 放入这个更大的 HashSet 中,并且我想查看新创建的 HashSet 是否已包含在更大的 HashSet 中。

现在我的问题是它是否总是会找到重复项,或者具有相同元素的两个 HashSet 的顺序是否会不同?

我很矛盾,因为它们使用相同的 hashcode() 函数,但这是否意味着它们将始终相同?

HashSet<HashSet<Integer>> test = new HashSet<>();
HashSet<Integer> one = new HashSet<>();
one.add(1);
one.add(2);
one.add(5);
test.add(one);
HashSet<Integer> two = new HashSet<>();
two.add(5);
two.add(1);
two.add(2);
//Some other stuff that runs over time
System.out.println(test.contains(two));

上面的代码试图说明我的意思,这总是返回 true 吗? (请记住,我可能会使用相同的元素初始化另一个 HashSet,然后再次尝试包含)

最佳答案

是的,以上总是返回 true。 Set 没有顺序,当您测试两个 Set 是否彼此相等时,您正在检查它们是否具有相同的元素。顺序没有任何意义。

详细来说,如果 test 包含具有相同 hashCode() 的元素,test.contains(two) 将返回 true > as two 等于 two(根据 equals 方法)。

具有相同元素的两个集合 s1s2 具有相同的 hashCode()s1.equals(s2) 返回 true。

这是 Set 接口(interface)的 equalshashCode 约定所要求的:

equals

Compares the specified object with this set for equality. Returns true if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set (or equivalently, every member of this set is contained in the specified set). This definition ensures that the equals method works properly across different implementations of the set interface.

hashCode

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.

如您所见,onetwo 甚至不必使用 Set 接口(interface)的相同实现来实现 test.contains(two) 返回 true。它们只需包含相同的元素即可。

关于Java - 两个哈希集随着时间的推移是否会发生类似的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49796743/

相关文章:

java - HashSet 正在添加重复的 ChannelSftp.LsEntry

java - 静态数据结构

java - Java的线性编程工具/库

java - 使用自己的 HashSet.add() 实现

c# - 从 IEnumerable 转换为 ISet

java - 如何编写哈希的删除方法来删除值?

Java对象的可重用性

java - 用 XML 写俄语

java - hibernate 中的异常(一对一)

c# - 添加到 Hashset<T> 时出现 IndexOutOfRangeException