gpt4 book ai didi

java - 具有相同哈希码的两个不相等的对象

转载 作者:太空狗 更新时间:2023-10-29 22:49:17 25 4
gpt4 key购买 nike

Hashcode() 和 equals() 的概念是

1) If two Objects are equal according to equal(), then calling the hashcode method on each of those two objects should produce same hashcode.

还有一个是

2) It is not required that if two objects are unequal according to the equal(), then calling the hashcode method on each of the two objects must produce distinct values.

我尝试并理解了第一个,这是第一点的代码。

public class Test {
public static void main(String[] args) {

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 11);
map.put(4, 11);
System.out.println(map.hashCode());
Map<Integer, Integer> map1 = new HashMap<Integer, Integer>();
map1.put(1, 11);
map1.put(4, 11);
System.out.println(map1.hashCode());
if (map.equals(map1)) {
System.out.println("equal ");
}
}
}

上面的程序为两个不同的对象提供了相同的哈希码。

谁能给我举个例子,根据 equals() 不相等的两个不同对象怎么会有相同的哈希码。

最佳答案

2) It is not required that if two objects are unequal according to the equal(), then calling the hashcode method on each of the two objects must produce distinct values.

根据哈希函数,2 个不同的对象可以具有相同的哈希码。然而,2 个相同的对象在散列时必须产生相同的结果(除非有人用随机数实现散列函数,在这种情况下它是无用的)

例如,如果我对整数进行哈希处理,而我的哈希函数只是(n % 10),那么数字17 和数字27 将产生相同的结果。这并不意味着这些数字相同。

关于java - 具有相同哈希码的两个不相等的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16400711/

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