Tuesday, June 9, 2015

Java hashcode() and equals()

hashcode() and equals() occupies the first round of interviews in most firms. As the interview proceeds, so does the difficulty level.

Fun part is, if you understand the concept once, all the questions would seem easy.

To the uninitiated, hashcode() and equals() belong to java.lang.Object class. Since all classes extendsObject class, hence all classes inherit the default hashcode() and equals()


1. By default For not null Objects, equals() method return true if they occupy same place in memory, i.e if the Objects are same. else return false.

2. equals() perform for Object by default, what we call shallow comparison, i.e just that the object is same or not. Sometimes Object can be different but they might have the same data. In such a case, we need to do a deep copy, i.e. compare each member variable to come to a conclusion (by overriding equals)

3. However if equals() is overridden, so should be hashcode(). As two objects that are equal, must return the same hashcode (vice-versa not true). However more on this later.


1. By default, hashcode() varies from on Java implementation to another. Mostly it converts the memory address of the Object into and integer and that becomes the hashcode.

2. By default It is unique for two different Objects.

3. As two objects that are equal, must return the same hashcode. Two unequal objects need not have different hashcode. However it's better to have.

4. Hashcode need to consistent. i.e. no matter how many times we calculate hashcode of a give Object, we should get the same value.

We can override hashcode() and equals() implementation as per our requirement. They are used extensively to store values in HashMap and HashTables.

No comments:

Post a Comment