Shallow vs Deep comparison of objects

Mary : “Which car you own?”

Lucy : “I have FIAT 500X”

Mary : “Hey…we have same car. I too have FIAT 500X”

 

You must have heard about comparing two objects in Java using == and equals() method. What is the difference ? Or what is the difference between deep and shallow comparison ?

The == returns true, if the variable reference points to the same object in memory. This is a “shallow comparison”.

 

Imagine Cat class has id and color as states.

Cat c = new Cat(2,”Black”);

Cat cc = new Cat(2,”Black”);

Now a comparison using == returns false. i.e (c==cc) returns false.

 

But consider this case :

Cat c = new Cat(2,”Black”);

Cat cc = c;

Now a comparison using == returns true. i.e (c==cc) returns true as both points to the same object in memory.

Let’s look at the equals() method.

The equals() – returns the results of running the equals() method of a user supplied class, which compares the attribute values. The equals() method provides “deep comparison” by checking if two objects are logically equal as opposed to the shallow comparison provided by the operator ==.

public class Cat {

private int id;

private String color;

 

public Cat(int id, String color) {

this.id = id;

this.color = color;

}

 

@Override

public boolean equals(Object obj) {

Cat cat = (Cat) obj;

if (this.id==cat.id && this.color == cat.color){

return true;

}else{

return false;

}

}

}

 

Cat c = new Cat(2,”Black”);

Cat cc = new Cat(2,”Black”);

Now a comparison using equals() returns true. i.e c.equals(cc) returns true.

Remember if equals() method does not exist in a user supplied class then the inherited Object class’s equals() method is run which evaluates if the references point to the same object in memory. The object.equals() works just like the “==” operator (i.e shallow comparison).

 

 

Saju Pappachen

 

About the author: Saju Pappachen is the Chief Consultant of jThread IT Training & Consultancy. He has more than 20 years of experience in Java technology.

He can be reached at saju@jthread.com

3 thoughts on “Shallow vs Deep comparison of objects

Leave a Reply

Your email address will not be published. Required fields are marked *