[java] Why do we have to override the equals() method in Java?

I have some confusion about the reason that we override the .equals method.

For example:

Test test1 = new Test(3);
Test test2 = new Test(3);

//The if comparison does the same thing that the overridden `.equals()` method does.
if(test1.equals(test2)){
    System.out.println("test1 and test2 are true in .equals()");
}

// Override .equals method.
public boolean equals(Object object) {
    if(object instanceof Test && ((Test)object).getValue() == this.t) {
        return true;
    } else {
        return false;
    }
}

I do not understand why we have to override the .equals() method.

This question is related to java overriding equals

The answer is


To answer your question, firstly I would strongly recommend looking at the Documentation.

Without overriding the equals() method, it will act like "==". When you use the "==" operator on objects, it simply checks to see if those pointers refer to the same object. Not if their members contain the same value.

We override to keep our code clean, and abstract the comparison logic from the If statement, into the object. This is considered good practice and takes advantage of Java's heavily Object Oriented Approach.


By default .equals() uses == identity function to compare which obviously doesn't work as the instances test1 and test2 are not the same. == only works with primitive data types like int or string. So you need to override it to make it work by comparing all the member variables of the Test class


The default behavior for java.lang.Object is to compare references, but that's not appropriate for every kind of object. There are things called Value Objects (like BigDecimal or String), where objects with the same value are considered to be interchangeable, so the default behavior of equals is not desirable. Those kinds of objects have to implement equals and hashcode based on the value that the object takes on.


Let me give you an example that I find very helpful.

You can think of reference as the page number of a book. Suppose now you have two pages a and b like below.

BookPage a = getSecondPage();

BookPage b = getThirdPage();

In this case, a == b will give you false. But, why? The reason is that what == is doing is like comparing the page number. So, even if the content on these two pages is exactly the same, you will still get false.

But what do we do if you we want to compare the content?

The answer is to write your own equals method and specify what you really want to compare.


.equals() doesn't perform an intelligent comparison for most classes unless the class overrides it. If it's not defined for a (user) class, it behaves the same as ==.

Reference: http://www.leepoint.net/notes-java/data/expressions/22compareobjects.html http://www.leepoint.net/data/expressions/22compareobjects.html


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 returns true if they are equal. The equals() method provided in the Object 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. The equals() method provided by Object 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.)


Object.equals() method checks only reference of object not primitive data type or Object value (Wrapper class object of primitive data, simple primitive data type (byte, short, int, long etc.)). So that we must override equals() method when we compare object based on primitive data type.


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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to overriding

How to underline a UILabel in swift? How to 'update' or 'overwrite' a python list maven command line how to point to a specific settings.xml for a single command? How to override the properties of a CSS class using another CSS class What is the difference between dynamic and static polymorphism in Java? Overriding css style? Android Overriding onBackPressed() What is the 'override' keyword in C++ used for? Why do we have to override the equals() method in Java? Can overridden methods differ in return type?

Examples related to equals

this in equals method Why do we have to override the equals() method in Java? Compare two objects with .equals() and == operator Check if bash variable equals 0 Setting equal heights for div's with jQuery Java, how to compare Strings with String Arrays How can I express that two values are not equal to eachother? How to override equals method in Java How do you say not equal to in Ruby? Getting an element from a Set