Jan 13, 2009

hashcode and equals contract

The hashcode and equals contract is very important for the SCJP exam. The details of the two methods is provided in another post at the following link:

Hashcode and equals method

Here we will be discussing the contract between hashcode and equals method which can be stated as:

For the same object, the hashcode generated at one instant should be same as the hashcode generated at another instant of time.


First of all we need to understand that this contract comes into picture because of collections. Hashtable, HashMap use hashing to decide where to store/get objects corresponding to keys. The topic is so important that we understand it with an example.

Consider the following code:

hm.add(“a”,”test1”);
hm.add(“b”,”test2”);

Assume that hashcode for “a” is 20 and for “b” is 30. Hypothetically the above code will store the objects “test1” and “test2” on location 20 and 30. Now when retrieving the two objects, we use,

hm.get(”a”);
hm.get(”b”);

Here the hashcode of “a” and “b” will be calculated again which is 20 and 30 respectively and on reaching those locations, we get the desired objects.

But the problem arises when hashcode for keys is different at different time for the same object, for e.g.

TestKey testKey1 = new TestKey();

int hashcode() {
return Math.random()*1000;
}

hm.add(testKey1,”test1”);

The object corresponding to testKey1 will be stored at location 50 (as generated by the random method used in the overridden hashcode method). So far so good, now let us get the object:

hm.get(testKey1);

If this time hashcode is 100 (due to random in overridden hashcode), are we not getting into problem?

Now it’s the time to list the contract:

If equals() returns true then hashcode comparison should also return true.
If equals() returns false then hashcode comparison may return true or false.
If hashcode comparison returns true then equals() may or may not return true.
If hashcode comparison returns false then equals() must return false.


The above ensures that for the same object, the hashcode generated at one instant should be same as the hashcode generated at another instant of time. It however does not mean that different objects can’t have same hashcode. This means that all objects of a class can have same hashcode but that will make the hashing inefficient.


The key point is repeated here once again.
For the same object, the hashcode generated at one instant should be same as the hashcode generated at another instant of time

0 comments: