【发布时间】:2013-04-30 07:47:14
【问题描述】:
Hashcode()和equals()的概念是
1) 如果两个对象根据 equal() 相等,则对这两个对象中的每一个调用 hashcode 方法应该会产生相同的 hashcode。
另一个是
2) 不要求如果两个对象根据equal()不相等,则对两个对象中的每一个调用hashcode方法都必须产生不同的值。
我尝试并理解了第一个,这是第一点的代码。
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() 不相等的两个不同对象如何具有相同的哈希码。
【问题讨论】:
-
将可能的哈希码数量与可能的
Longs 或Strings 的数量进行比较。 en.wikipedia.org/wiki/Pigeonhole_principle -
点(1)和(2)的来源是什么?
标签: java hashmap equals hashcode