Hashcode()和equals()的概念是
1)如果两个对象根据equal()相等,则在这两个对象中的每一个上调用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 ");
}
}
}
Run Code Online (Sandbox Code Playgroud)
上面的程序为两个不同的对象提供相同的哈希码.
有人可以用一个例子来解释我,根据equals()不同的两个不同对象如何具有相同的哈希码.