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;
    }

    @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;
    }
}

Imagine you have this

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

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

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

Answer from Lombo on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › equals-hashcode-methods-java
equals() and hashCode() methods in Java - GeeksforGeeks
July 23, 2025 - So if get the generated hashcode values are equal for both the Objects, after that we compare the both these Objects w.r.t their state for that we override equals(Object) method within the class.
🌐
Baeldung
baeldung.com › home › java › core java › java equals() and hashcode() contracts
Java equals() and hashCode() Contracts | Baeldung
January 8, 2024 - As a result, every Java class implicitly has these two methods.: ... Money income = new Money(55, "USD"); Money expenses = new Money(55, "USD"); boolean balanced = income.equals(expenses) We would expect income.equals(expenses) to return true, ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-equals-hashcode
Java equals() and hashCode() | DigitalOcean
August 3, 2022 - For multiple objects x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. Multiple invocations of x.equals(y) should return same result, unless any of the object properties is modified that is being used in the equals() method implementation. Object class equals() method implementation returns true only when both the references are pointing to same object. Java Object hashCode() is a native method and returns the integer hash code value of the object.
🌐
Codefinity
codefinity.com › blog › How-equals()-and-hashCode()-Work-in-Java-and-Why-Following-Their-Contract-Matters
How equals() and hashCode() Work in Java and Why Following Their Contract Matters
A: Yes, this is called a hash collision. Multiple objects can have the same hash code, but equals() is used as a second check to confirm actual equality. ... Learn the fundamentals of Java and its key features in this course.
🌐
Medium
justgiveacar.medium.com › how-to-use-equals-and-hashcode-in-java-e10b8fd1aba5
How to use equals() and hashCode() in Java | by Justgiveacar | Medium
July 6, 2021 - Bref, let’s make this method ... it: @Override public int hashCode() { return 50; } Class Main { public static void main(String[] args){ Humanity h = new Humanity("Linzhou"); int hashCode = h.hashCode(); System.out.println(hashCode); } } As we might ...
Top answer
1 of 16
726

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;
    }

    @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;
    }
}

Imagine you have this

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

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

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

2 of 16
379

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.

🌐
How to do in Java
howtodoinjava.com › home › java basics › java hashcode() and equals() methods
Java hashCode() and equals() Methods - HowToDoInJava
February 23, 2023 - The above example prints two objects in the second print statement. If both employee objects have been equal, in a Set which stores unique objects, there must be only one instance inside HashSet because both objects refer to the same employee. What is it we are missing?? We are missing the second important method hashCode(). As java docs say, if we override equals() then we must override hashCode().
🌐
EPAM Campus
campus.epam.com › en › blog › 339
Learning Java. equals() and hashCode() Methods | EPAM Campus article
This approach is used when we need ... for example, in such data structure as HashMap. In this case, the equals() method is not very suitable, since it takes time to check all fields of the object. The hash code of the object is more fitting for the purpose. In Java, the object’s hashcode can be obtained ...
Find elsewhere
🌐
Medium
medium.com › @iyusubov444 › interview-questions-java-equals-hashcode-methods-revisited-7b0cd80aa903
Interview Questions - Java equals & hashCode Methods Revisited | by Imran Yusubov | Medium
September 1, 2022 - Although we are not violating equals hashCode contract, we should avoid overriding hashCode in this way as there is a price to pay. If we read the working internals of a HashMap for example, we can say that we need an even distribution of the elements, to improve the search time. This implementation, will put all elements in the a single bucket, and the elements will be chained as a linked list. The cost of this is, we will now need O(n) time to find an element. However, in Java 8, there is a huge improvement and the elements are no longer chained as a linked list but as a binary search tree, after a certain threshold is reached.
🌐
DZone
dzone.com › data engineering › data › working with hashcode() and equals()
Working With hashcode() and equals()
January 2, 2018 - 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. In the following sections, we provide several examples ...
🌐
Medium
medium.com › @AlexanderObregon › how-javas-equals-and-hashcode-methods-work-together-da27332bb742
How Java’s equals() and hashCode() Work Together | Medium
February 22, 2025 - This happens because the collection relies on the original hashCode() to locate the object, and if that value changes, the object is no longer in the expected bucket. For example: import java.util.HashSet; class Employee { String name; Employee(String name) { this.name = name; } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Employee employee = (Employee) obj; return name.equals(employee.name); } } public class Main { public static void main(St
🌐
InfoWorld
infoworld.com › home › blogs › java challengers
Comparing Java objects with equals() and hashcode() | InfoWorld
May 16, 2024 - If equals() and hashcode() are not overridden when using hash collections, the collection will have duplicate elements. Debugging is one of the easiest ways to fully absorb programming concepts while also improving your code. In this video you can follow along while I debug and explain the Java equals() and hashcode() challenge.
🌐
CodeJava
codejava.net › java-core › collections › understanding-equals-and-hashcode-in-java
Understanding equals() and hashCode() in Java
If we violate these rules, the collections will behave unexpectedly such as the objects cannot be found, or wrong objects are returned instead of the correct ones.Now, let’s see how the hashCode() and equals() methods affect the behaviors of a Set by coming back to the student example.Until now, we have the Student class written like this: /** * Student.java * @author www.codejava.net */ public class Student { private String id; private String name; private String email; private int age; public Student(String id) { this.id = id; } public Student(String id, String name, String email, int age)
🌐
Reddit
reddit.com › r/java › origin of misconception for equals and hashcode implementation
r/java on Reddit: Origin of misconception for equals and hashcode implementation
February 11, 2022 -

So i do some coding interviews at my company and one question i ask nearly every Person who applies for a Java developer job is what are the equals and hashcode methods. I just want to see if the person understands what they do, how you could implement both, what contract is between them and where there are pitfalls, like on jpa entities.

It is not about how to generating those methods. I want to see if they thought about the concept.

One thing, many people say is that it is a good idea to use hashcode to implement equals. So that you should just compare the hashes.

I think it is clear that this is no good solution. But it is interesting that so many people say just that. And i think when i learned Java, i read this for myself. But i am not sure where.

Has anyone an idea where this misconception comes from? Maybe it was thought in a book or so?

🌐
Medium
medium.com › @reetesh043 › java-equals-and-hashcode-a69c37ce4d25
Java equals() and hashcode(). Introduction | by Reetesh Kumar | Medium
January 25, 2024 - In the above example, we can see hashCode of both the equals is different even though both objects are equal. Let’s override the hashCode() method for BankAccount class: import java.util.Objects; public class BankAccount { //Fields And Constructors // Getters and setters @Override public int hashCode() { int result; long temp; result = accountNumber.hashCode(); result = 31 * result + accountHolderName.hashCode(); temp = Double.doubleToLongBits(balance); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } public static void main(String [] args) { BankAccount account1 = new BankAccount("Savings", "Test", 2022); BankAccount account2 = new BankAccount("Savings", "Test", 2022); System.out.println(account1.equals(account2)); // true System.out.println(account1.hashCode()); // -813975577 System.out.println(account2.hashCode()); // -813975577 } }
🌐
TutorialsPoint
tutorialspoint.com › what-is-the-contract-between-equals-and-hashcode-methods-in-java
What is the contract between equals() and hashCode() methods in Java?\\n
The default implementation of this ... are equal if both of them reference the same object. It does not check the value or state of the objects. But we can override this method to provide our own implementation to compare the state or value of the objects. ... The hashCode() method should ...
🌐
Thorben Janssen
thorben-janssen.com › ultimate-guide-to-implementing-equals-and-hashcode-with-hibernate
Ultimate Guide to Implementing equals() and hashCode() with Hibernate
October 14, 2022 - The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. ... That is a challenge if you use generated primary keys because the identifying attribute of the object changes when it transitions from lifecycle state transient to managed. But more about that later… · The hashCode() contract is a little bit easier to implement: Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.
🌐
Medium
medium.com › @AlexanderObregon › javas-tostring-equals-and-hashcode-explained-27cfc9bb1497
Java’s toString(), equals(), and hashCode() Explained | Medium
July 9, 2024 - Example: import java.util.HashSet; ... person : people) { System.out.println(person); } } } In this example, we use a HashSet to store Person objects....
🌐
Accuweb
accuweb.cloud › home › java equals() and hashcode()
Java equals() and hashCode() - AccuWeb Cloud
November 15, 2023 - Let’s dive into their definitions, significance, and best practices for implementation. The equals() method compares the content or state of two objects for equality. It is often overridden in classes to provide a custom definition of object equality based on the specific attributes of the objects. By default, the equals() method compares object references, which checks if two object references point to the same memory location. Example ...
Top answer
1 of 7
164

The problem you will have is with collections where unicity of elements is calculated according to both .equals() and .hashCode(), for instance keys in a HashMap.

As its name implies, it relies on hash tables, and hash buckets are a function of the object's .hashCode().

If you have two objects which are .equals(), but have different hash codes, you lose!

The part of the contract here which is important is: objects which are .equals() MUST have the same .hashCode().

This is all documented in the javadoc for Object. And Joshua Bloch says you must do it in Effective Java. Enough said.

2 of 7
17

According to the doc, the default implementation of hashCode will return some integer that differ for every object

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation
technique is not required by the JavaTM programming language.)

However some time you want the hash code to be the same for different object that have the same meaning. For example

Student s1 = new Student("John", 18);
Student s2 = new Student("John", 18);
s1.hashCode() != s2.hashCode(); // With the default implementation of hashCode

This kind of problem will be occur if you use a hash data structure in the collection framework such as HashTable, HashSet. Especially with collection such as HashSet you will end up having duplicate element and violate the Set contract.