Hashcode() and equals() concept is
1) If two Objects are equal according to equal(), then calling the hashcode method on each of those two objects should produce same hashcode.
and other one is
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.
I tried and understood first one and this is the code for first point.
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 ");
}
}
}
the above program gives same hashcode for two different objects.
Can someone explain me with an example,how can two different objects which are unequal according to the equals() have same hashcode.