sahu sahu - 7 months ago 74
Java Question

two unequal objects with same hashcode

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.

Answer

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.

Depending on the hashing function, 2 different objects can have the same hash code. However, 2 objects wich are the same must produce the same result when hashed (unless someone implemented a hashing function with random numbers in which case it's useless)

For example, if I am hashing integers and my hashing function is simply (n % 10) then the number 17 and the number 27 will produce the same result. This does not mean that those numbers are the same.