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
Very Informative sir👍
Very useful information sir 👍
Classic model.
Classic model.
Explained very well with a good example.
Explained well with a good example.
Very informative & nice presentation.
Good job Sir. Great way of explanation.
Very useful information
really a great information in a simple way 👌👌👌
Informative and easy to understand
Unique style of teaching. Great work sir, you are gifted 👍
Very useful
Thank you sir. 🤗
Easy to understand… Thank you sir….
Well explained sir
well, explained sir…
thank you sir
Well explained
Excellent, Very helpful
thank you Sir
Well explained sir ..Thank you
Detailly Explained sir,Nice one.Thank you
Great way of explanation and easy to understand.Thankyou sir.
Thank you so much sir.well explained…
Nice explanation Sir. Thanks
Very informative and clearly explained, sir. Thank you.
Very very informative..thank you sir.