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.

Tech Talk... How hash map works in java

This is a very common question asked by interviewers for java.
Rather than explaining it here, I would like to compile some links that helped me immensely in understanding the internal working of hash map:

This one provides a very elaborate theoratical insite into how things work internally with hash map
http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html


This one explains the same, but rather centering the explanation around a practical example:
http://www.javacodegeeks.com/2014/03/how-hashmap-works-in-java.html

I liked both the approaches and benifitted from both these links...hoping the same will help the readers coming to this website as well.