When i see the implementation of equals()
method it does nothing but same as what ==
does. So my question is what was the need to have this as separate method when we have ==
operator which does the same work?
So the == Operator returns False because it compares the reference identity while the Equals() method returns True because it compares the contents of the objects.
equals() method. The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.
== should be used during reference comparison. == checks if both references points to same location or not. equals() method should be used for content comparison. equals() method evaluates the content to check the equality.
We can override the equals method in our class to check whether two objects have same data or not.
You can not overload the ==
operator, but you can override equals(Object)
if you want it to behave differently from the ==
operator, i.e. not compare references but actually compare the objects (e.g. using all or some of their fields).
Also, if you do override equals(Object)
, have a look at hashCode()
as well. These two methods need to be compatible (i.e. two objects which are equal according to equals(Object)
need to have the same hashCode()
), otherwise all kinds of strange errors will occur (e.g. when adding the objects to a set or map).
==
compares object references, and asks whether the two references are the same.
equals()
compares object contents, and asks whether the objects represent the same concept.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With