Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why equals() method when we have == operator? [duplicate]

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?

like image 507
GuruKulki Avatar asked May 05 '10 11:05

GuruKulki


People also ask

Why does Equals () method give different results when compared to the == operator?

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.

What is the difference between Equals () method and == operator?

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.

Does Equals () method and == do the same thing in Java?

== 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.

What is the reason for overriding Equals () method?

We can override the equals method in our class to check whether two objects have same data or not.


2 Answers

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).

like image 170
Thomas Lötzer Avatar answered Oct 09 '22 11:10

Thomas Lötzer


== 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.

like image 26
Sean Owen Avatar answered Oct 09 '22 09:10

Sean Owen