请查看我的代码:
HashSet<A> set = new HashSet<A>();
for (int i = 0; i < 10; i++)
set.add(new A());
System.out.println(set.contains(new A()));
A 类定义为:
class A {
public boolean equals(Object o) {
return true;
}
public int hashCode() {
return (int) (Math.random()%100);
}
}
如果hashset里面使用了hashmap……为什么输出是true? 因为不同的hashcode意味着它们的bucket位置不同。 那么检查 new A() 如何返回 true 。
此外,如果我从哈希码输出中返回 1 总是 true,这看起来没问题。
最佳答案
原因是你的哈希码函数:
(int) (Math.random()%100);
始终返回0
。因此所有 A
元素始终具有相同的哈希码。因此,所有 A 元素都将位于 HashSet 中的同一个存储桶中,因此您的 equals 将始终返回 true。一旦它在同一个桶中找到 A(在本例中总是如此),它将返回 true,表明 A 已被包含。
Math.random()
返回 0 到 1 之间的数字,以便对任何内容取模始终为0
。
您可能想使用 *
而不是 %
来获取 0 到 100 之间的随机数
(int) (Math.random() * 100);
做你想做的
关于java - 哈希集如何检查重复元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30283267/