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

what happens if we do not override hashcode() and equals() in hashmap
hashcode() and equals() method in java example
difference between equals and hashcode() in javatpoint
what will be the problem if you don't override equals() method
hashcode() and equals() method in java by durga
equals() and hashcode contract
this class overrides equals() and should therefore also override hashcode
java do you need to override hashcode

Recently I read through this Developer Works Document.

The document is all about defining hashCode() and equals() effectively and correctly, however I am not able to figure out why we need to override these two methods.

How can I take the decision to implement these methods efficiently?

Joshua Bloch says on Effective 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.

Let's try to understand it with an example of what would happen if we override equals() without overriding hashCode() and attempt to use a Map.

Say we have a class like this and that two objects of MyClass are equal if their importantField is equal (with hashCode() and equals() generated by eclipse)

public class MyClass {

    private final String importantField;
    private final String anotherField;

    public MyClass(final String equalField, final String anotherField) {
        this.importantField = equalField;
        this.anotherField = anotherField;
    }

    public String getEqualField() {
        return importantField;
    }

    public String getAnotherField() {
        return anotherField;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((importantField == null) ? 0 : importantField.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final MyClass other = (MyClass) obj;
        if (importantField == null) {
            if (other.importantField != null)
                return false;
        } else if (!importantField.equals(other.importantField))
            return false;
        return true;
    }

}

Override only equals

If only equals is overriden, then when you call myMap.put(first,someValue) first will hash to some bucket and when you call myMap.put(second,someOtherValue) it will hash to some other bucket (as they have a different hashCode). So, although they are equal, as they don't hash to the same bucket, the map can't realize it and both of them stay in the map.


Although it is not necessary to override equals() if we override hashCode(), let's see what would happen in this particular case where we know that two objects of MyClass are equal if their importantField is equal but we do not override equals().

Override only hashCode

Imagine you have this

MyClass first = new MyClass("a","first");
MyClass second = new MyClass("a","second");

If you only override hashCode then when you call myMap.put(first,someValue) it takes first, calculates its hashCode and stores it in a given bucket. Then when you call myMap.put(second,someOtherValue) it should replace first with second as per the Map Documentation because they are equal (according to the business requirement).

But the problem is that equals was not redefined, so when the map hashes second and iterates through the bucket looking if there is an object k such that second.equals(k) is true it won't find any as second.equals(first) will be false.

Hope it was clear

Why to Override equals(Object) and hashCode() method , In this post, we will discuss why it is important to override equals and hashCode method in Java as suggested by Josh Bloch's Effective Java and Javadoc. This is because we have overridden both equals () and hashCode () method in the Employee class and both objects now points to the same bucket and also holds the same location within the bucket. Now let’s discuss the behavior of above program if equals () method is overridden without overriding hashCode () or vice versa.

Collections such as HashMap and HashSet use a hashcode value of an object to determine how it should be stored inside a collection, and the hashcode is used again in order to locate the object in its collection.

Hashing retrieval is a two-step process:

  1. Find the right bucket (using hashCode())
  2. Search the bucket for the right element (using equals() )

Here is a small example on why we should overrride equals() and hashcode().

Consider an Employee class which has two fields: age and name.

public class Employee {

    String name;
    int age;

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this)
            return true;
        if (!(obj instanceof Employee))
            return false;
        Employee employee = (Employee) obj;
        return employee.getAge() == this.getAge()
                && employee.getName() == this.getName();
    }

    // commented    
    /*  @Override
        public int hashCode() {
            int result=17;
            result=31*result+age;
            result=31*result+(name!=null ? name.hashCode():0);
            return result;
        }
     */
}

Now create a class, insert Employee object into a HashSet and test whether that object is present or not.

public class ClientTest {
    public static void main(String[] args) {
        Employee employee = new Employee("rajeev", 24);
        Employee employee1 = new Employee("rajeev", 25);
        Employee employee2 = new Employee("rajeev", 24);

        HashSet<Employee> employees = new HashSet<Employee>();
        employees.add(employee);
        System.out.println(employees.contains(employee2));
        System.out.println("employee.hashCode():  " + employee.hashCode()
        + "  employee2.hashCode():" + employee2.hashCode());
    }
}

It will print the following:

false
employee.hashCode():  321755204  employee2.hashCode():375890482

Now uncomment hashcode() method , execute the same and the output would be:

true
employee.hashCode():  -938387308  employee2.hashCode():-938387308

Now can you see why if two objects are considered equal, their hashcodes must also be equal? Otherwise, you'd never be able to find the object since the default hashcode method in class Object virtually always comes up with a unique number for each object, even if the equals() method is overridden in such a way that two or more objects are considered equal. It doesn't matter how equal the objects are if their hashcodes don't reflect that. So one more time: If two objects are equal, their hashcodes must be equal as well.

Why do we need to Override 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  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.

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.

   from Effective Java, by Joshua Bloch

By defining equals() and hashCode() consistently, you can improve the usability of your classes as keys in hash-based collections. As the API doc for hashCode explains: "This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable."

The best answer to your question about how to implement these methods efficiently is suggesting you to read Chapter 3 of Effective Java.

Why do I need to override the equals and hashCode methods in Java?, 2.2. Should we override only equals() method? To achieve correct application behavior, we need to override  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.

Java hashCode() and equals(), equals(Object obj): a method provided by java.lang. The default implementation is not enough to satisfy business needs, especially if As per the Java documentation, developers should override both methods in order to  What is the need to Override Hashcode() and equals() method. Although there are lots of material are available on internet and API document about the necessity of the overriding the hashcode() and equals() method in Java but lots of new developers still not able to understand the necessity of hashcode() method.

Working With hashcode() and equals(), Java recommends to override equals and hashCode method if equality is going to 5) Null comparison : comparing any object to null must be false and should not you don't need to use test prefix on test method, just use @Test annotations​. 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

Overriding equals() and hashCode() method in Java , Why Override equals, hashcode and toString method in Java. Couple of questions, which are often asked to me was why do we need to  java.util.Objects.hash() and java.util.Objects.equals() are part of Java 7 (released in 2011) so you don't need Guava for this. – herman Jul 23 '13 at 13:33 1 of course, but you should avoid that since Oracle is not providing public updates anymore for Java 6 (this has been the case since February 2013). – herman Jul 25 '13 at 9:48

Why Override equals, hashcode and toString method , equals() and hashCode() in Java are two fundamental method which equals() – How to Override equals() and hashcode() Method in Java? on others should very likely be omitted from equals and hashCode . I want to Optimize WordPress · Plugins we use · Get FREE Domain & Hosting · Learn SEO. hashCode  and  equals  are closely related : if you override  equals, you must override   hashCode. hashCode  must generate equal values for equal objects. equals  and  hashCode  must depend on the same set of significant fields.

Java Collections - hashCode() and equals(), Learn how these methods work together when comparing Java objects. Without equals Duration: 9:34 Posted: Aug 22, 2019 So, how do we check for equality of values inside the objects? All classes in Java inherit from the Object class, directly or indirectly (See point 1 of this ). The Object class has some basic methods like clone (), toString (), equals (),.. etc. We can override the equals method in our class to check whether two objects have same data or not.

Comments
  • There are two great articles at programming.guide explaining exactly this: When should I override equals? and Why you should always override hashCode when overriding equals. (Warning, the accepted answer is actually wrong.)
  • Case Override only equals: two same object will have different hashcode = same objects go in different bucket(duplication). Case Override only hashcode:two same object will have same hashcode = same object go in same bucket(duplication).
  • can you please elaborate a little more , in second case , why the second object must go in another bucket?
  • I don't like this answer because it suggests that you can't override hashCode() without overriding equals(), which is simply not true. You say your example code (the "override only hashCode" part) won't work because you define your two objects as equal, but - sorry - this definition is only in your head. In your first example you have two un-equal objects with the same hashCode, and that is perfectly legal. So the reason you need to override equals() is not because you have already overridden hashCode(), but because you want to move your "equals" definition from your head to the code.
  • if you think you need to override one, then you need to override both of them is wrong. You need to override hashCode if your class overrides equals but reverse is not true.
  • I think it's totally ok to override only hashCode() without overriding equals() as well. It's also whats written in Effective Java: books.google.fr/…
  • @PhantomReference, note that only overriding equals would violate the contract spelled out in the javadoc of Object: "If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result." Sure, not all parts of all contracts are exercised in all code, but still, formally speaking it's a violation and I'd consider it to be a bug waiting to happen.
  • Perfect example. Clearly demonstrated the difference!
  • nice explained @rajeev
  • @VikasVerma equals object will have equal hashcode doesn't mean unequal object will have unequal hashcode. What if objects are actually different, but their hashcode is same ?
  • explained very nicely :)
  • much better answer then the accepted answer! Thanks