简体   繁体   中英

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.

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 ie 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 eg 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.

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

.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

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.

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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM