Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 247
nakul Avatar asked Mar 02 '13 13:03

nakul


People also ask

Why do we need to override equals method in Java?

As a side note, when we override equals(), it is recommended to also override the hashCode() method. If we don't do so, equal objects may get different hash-values; and hash based collections, including HashMap, HashSet, and Hashtable do not work properly (see this for more details).

Why do I need to override the equals and hashCode methods in Java?

You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object. hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.

What will happen if you don't override equals () method in object class?

If you don't override equals, it will compare the internal address of the two references, which matches the logic behind hashCode.

What happens if we do not override equals?

As I have not overridden equals method, the default implementation will return false.


1 Answers

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.

like image 149
Grijesh Chauhan Avatar answered Sep 23 '22 10:09

Grijesh Chauhan