Thursday 30 April 2015

Tech talk... hashcode and equals method overriding in java

I always used to messup the concept that which one must be overridden if the other one is overridden.

Should we override equals() if we are overriding hashcode():
we can, but even if we don't it will not have side effects

Should we override hashcode() if we intend to override equals():
yes we should, otherwise it might lead to side effects.

How?
hashcode() method generates a unique integer for each object. No matter what the fields value of the object, this integer is always the same for the object. And equals() uses hashcode by default to compare if two objects are equal or not.

Suppose now I override equals() to say two person objects are equal for me if their "name" are same.
But I don't override the hashcode(). I have all person objects stored in a HashMap against their address.

I say the following:

Person john = new person("john");
mymap.put(john, addrOfJohn);


Now, i want to retrieve the address of john. Since my equals() method is overridden,I assume if i create a object again with name "john" and use it to retrieve the address of john, that should work.

So i say:

mymap.get(new Person("john");

what do i get? null !!
why?
because storage of keys in hashmap is based on their hashcode and the above two Person objects that i created, had the same name but different hash value as i had not overridden the hashcode method.
so, while the address is stored against a key that hashes to a different bucket, after creating a new person, I might be looking at it in a different bucket. this leads to an undesirable effect.

That is why when equals() is overridden, hascode() should as well be overridden.

No comments:

Post a Comment