This question already has an answer here:
- How do I compare strings in Java? 23 answers
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?
You can not overload the
==
operator, but you can overrideequals(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 athashCode()
as well. These two methods need to be compatible (i.e. two objects which are equal according toequals(Object)
need to have the samehashCode()
), 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.That's done so to make this possible:
If you check the source of
String#equals()
, you'll see that it has overridden theObject#equals()
appropriately to compare each other's internal character array (the actual value). Many other classes have this method overridden as well."string" == "string" will return false "string".equals("string") will return true
With o1 == o2 you compare that the object 1 is the same object than o2 (by reference)
With o1.equals(o2), depending on the object the equals method is overriden and not implemented with something like "return o1 == o2"
For exemple you create 2 Set instances These 2 set objects are 2 different objects, you can add different elements in any of those. set1 == set2 will always return false but set1.equals(set2) will eventually return true if the set2 contains exactly the same elements that set1... and because equals method is overriden in the Set class...
Equals implementation for Set is:
== operator is used to compare references.
equals() method is defined over object definition.
would return false indicating that the the two dogs have two different collar object (items).they do not share the same collar.
return true if the Collar is defined as [Collar are same if color of Collar are same] the two dogs have same colored collar.
In java equals operator(==) operates on data of two variables if the operands are of primitive data types. But if the operands are objects java compares them using references because it has no way to figure out to compare on which field or fields of the object.
So there is only one way to compare based on user defined fields and that is defined in the object by overriding equals() methods, since equals operator(==) cannot be overrided in java as java does not supports operator overriding.
As an example if you want to compare Employee on the basis of name you need to define it's logic by overriding equals method in Employee class as below: