Friday 22 January 2016

equals() and hashcode() methods

Both methods are from object class. Let us understand one by one
equals() : It compares the content of two objects. If two objects are meaningfully equivalent then it returns true else false. The default implementation of equals() method in object class is same as '==' operator. Declaration of equals() in Object class is as follows :
public boolean equals(Object anObject).

hashcode(): This method gives 32 bit int value, we may say that it is a object Id. The default implementation of hashcode() in object class is, it return the memory address.
Suppose we say, String str="Hello"; then str.hashcode() will return some int number like 69609650, it may vary according to platform. If you wish to use hashcode() other than String class, then you have to override it.

Contract between equals() and hashcode() :
1. If 2 objects are equal using equals() method, then their hashcode must be same.
2. It does not mean that unequal objects must have different hashcode.
3. It does not mean that objects with same hashcode must be equal

Interviewer might confuse you here, but be firm and just remember the contract between these two methods.Soon we will we how and when to override these two methods.

No comments:

Post a Comment