Skip to content

favourite interview question- Hashcode and equals

March 27, 2013

Hi folks,

Today we are going to deal with interview strategy of hashcode() and equals() method.

By default, these methods are present in Object class of java.lang package.

Let’s discuss these methods one by one.

public boolean equals(Object o);

The equals() method takes an Object type argument and returns a boolen false or true.

This method checks if some object is passed to it as an argument is equal to the object on which the method is invoked or not.

Default implementation of the equals() method in the Object class says: Check whether two different object references, let r1 and r2,  refer to the same object or not. This method  returns true if and only if r1 and r2 refer to the same object. This is equivalent to something like:

if(r1==r2) or not.

The default implementation performs Shallow Comparison, because the Object class has no data members that defines its state.

The implementation classes that overrides this method performs Deep Comparison, by actually comparing the relevant data members.

Equals() method follows Equivalence Relation properties that you might have studied during your school days.

Equivalence Relation follows Reflexive, Symmetric and Transitive in nature.

Let’s see what does it mean, in Java context.

Assume two object references r1 and r2,

Reflexive:  r1.equals(r1) always returns True.

Symmetric: If r1.equals(r2) returns true/false, then

r2.equals(r1) also returns true/false.

means you can use this property interchangeably

Transitivity: If r1.equals(r2) returns true and r2.equals(r3) returns true, then

r1.equals(r3) also returns true.

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Note that it is generally necessary to override the hashCode method, if you are overriding equals() method, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hashCodes.

Relationship status of these methods on FACEBOOK.

If two objects are equal, then they must have the same hash code, however the opposite is NOT true

From → Uncategorized

Leave a Comment

Leave a comment