hashCode()和equals()方法的概念是两个不相等的对象具有相同的散列码
1)如果两个对象是根据等于()相等,则调用每个这两个对象的哈希码方法应该产生相同的哈希码。
,另一个是
2)不要求是,如果两个对象根据等于()是不相等的,然后调用散列码方法对每个所述两个对象都必须产生不同的值。
我尝试并理解第一个,这是第一点的代码。
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()不同的两个不同对象怎么能有相同的散列码。
比较的可能散列码的数目可能'Long's或'String's的数目。 http://en.wikipedia.org/wiki/Pigeonhole_principle – SLaks 2013-05-06 14:19:29
可能的重复[在Java中==,equals和hashcode的示例](http://stackoverflow.com/questions/2731889/example-of-equals-and- hashcode-in-java) – cHao 2013-05-06 14:21:56