Why do we have to override the equals() method in Java?
Solution 1:
From the article Override equals and hashCode in Java:
Default implementation of equals() class provided by java.lang.Object compares memory location and only return true if two reference variable are pointing to same memory location i.e. essentially they are same object.
Java recommends to override equals and hashCode method if equality is going to be defined by logical way or via some business logic: example:
many classes in Java standard library does override it e.g. String overrides equals, whose implementation of equals() method return true if content of two String objects are exactly same
Integer wrapper class overrides equals to perform numerical comparison etc.
Solution 2:
This should be enough to answer your question: http://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html
The
equals()
method compares two objects for equality and returnstrue
if they are equal. Theequals()
method provided in theObject
class uses the identity operator (==
) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. Theequals()
method provided byObject
tests whether the object references are equal—that is, if the objects compared are the exact same object.To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the
equals()
method.
(Partial quote - click through to read examples.)