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
🌐
PriorityQueue
nkamphoa.com › home › how to override the hashcode method properly in java
How to Override the hashCode Method Properly in Java
September 15, 2025 - Discover how the hashCode method in Java works, its contract with equals, and why proper overriding is crucial for collections.
🌐
Baeldung
baeldung.com › home › java › core java › overriding hashcode() and equals() for records
Overriding hashCode() And equals() For Records | Baeldung
January 16, 2024 - @Test public void givenTwoReco...rt.hashCode(), robertCopy.hashCode()); } Java does provide the ability to override the default implementations of the equals() and hashCode() methods....
Discussions

Why do I need to override the equals and hashCode methods in Java? - Stack Overflow
Any reason to use those numbers ... the hashcode? Can we use any random numbers? 2019-01-29T07:19:48.443Z+00:00 ... @JavaYouth , as mentioned by Rajeev, you can use any other values. However, it is suggested to use prime numbers as this will produce less collisions. 2021-12-29T08:30:09.373Z+00:00 ... You must override hashCode() ... More on stackoverflow.com
🌐 stackoverflow.com
Override hashCode
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 ... More on teamtreehouse.com
🌐 teamtreehouse.com
3
August 7, 2015
ELI5 why I NEED to override hashCode when overriding equals
Two objects that are considered "equal" must produce the same hash code. Right now if you create two Hippo objects that are equal according to your method, they will not have the same hash code. For example, you cannot currently make a Hash Table of Hippos, it will fail to find Hippos that are identical but instantiated separately since you did not override hashcode. More on reddit.com
🌐 r/learnjava
12
25
September 20, 2019
Can someone ELI5 the hashcode() method for me?
This is not material that any 5 year old would understand. HashCode is a 'helper' function that allows collections like HashMap to guess where they stored an object. Lets say you have a list of strings (apple, analog, bee and data) and you want to 'test' if the string "cider" is in that list. With a simple list you would have to, worst case, check all the items in the list. In this case 4. Hashmaps/sets use the 'trick' that objects can give a short number that is calculated from their contents. Lets say we simply use the alphabet position of the first character of the string. So apple and analog would be 1, bee would be 2, data would be 4. We would then create a bunch of lists based on those codes. We would stuff apple and analog into list 1, bee in list 2, data in list 4. If we were then to test "cider" which would have code 3 we would not have to check any list because we know there isn't even a list with code 3, let alone any strings in there. Same if we wanted to test "art": we know it also has hashcode 1 so we only need to test a list of 2 items instead of all 4 items. This is as simple as I can explain what a HashSet / Map does and why it needs a hashcode. In reality how it decides to create these internal lists and how a hashcode is made is a bit more complex but it essentially works like this. More on reddit.com
🌐 r/java
18
5
November 6, 2014
🌐
Coderanch
coderanch.com › t › 636710 › java › override-HashCode-class-String-variables
How to override HashCode when your class has only String variables (Java in General forum at Coderanch)
July 16, 2014 - If your code only needs to run on Java 7 or later and there's no requirement that you calculate the hash code yourself, though, using Objects.hash() as Campbell suggested is a better option. ... Brett Spell wrote: He specifically asked, "how can i override hashcode for the class" and his other comments seem to indicate that he understands that he also needs to override equals() and its relationship to the hash code.
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.

🌐
Blogger
javarevisited.blogspot.com › 2011 › 10 › override-hashcode-in-java-example.html
How to override hashcode in Java example - Tutorial
The importance of hashcode increases when we use the object in different collection classes which works on hashing principle e.g. hashtable and hashmap. A well-written hashcode method can improve performance drastically by distributing objects uniformly and avoiding a collision. In this article, we will see how to correctly override the hashcode() method in java with a simple example.
🌐
Baeldung
baeldung.com › home › java › core java › java equals() and hashcode() contracts
Java equals() and hashCode() Contracts | Baeldung
January 8, 2024 - If we want to use instances of the Team class as HashMap keys, we have to override the hashCode() method so that it adheres to the contract; equal objects return the same hashCode.
Find elsewhere
🌐
Hostman
hostman.com › tutorials › overriding the hashcode method in java
Java: Overriding the hashCode Method
December 29, 2025 - The first idea that might come to mind for overriding hashCode() in Java is to return a constant.
Price   $
Address   1999 Harrison St 1800 9079, 94612, Oakland
Top answer
1 of 3
3
Hello Jonathan, Could it be any integer? Yes, any positive or negative integer. This accounts for overflow. Does it have a meaning of what integer it is for its place in the hashMap and that's all or it affects the comparing\equals methods too? Quoted from the link I provided earlier: The general contract of hashCode is: 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. This integer need not remain consistent from one execution of an application to another execution of the same application. 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. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables. 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.) What is the meaning of the 31 I keep seeing in all the generated code \ when evaluating objects? Efficiency through the prevention of as many collisions as possible. A collision is when we attempt to place an object in a hash table and the bucket already has an object. Now we would have to use a different methodology to account for the collision and ultimately loose efficiency. For example, we might have a linked list in which all Objects that attempt to be placed in a bucket get inserted for storage. We now have to traverse the list in linear time instead of being able to accomplish hashing in constant time. There are other methods as well but for the sake of brevity within these forums, I will just provide some links from college at the end of this post. The number 31 is a Mersenne prime. A good explanation can be found at the following website: http://mathworld.wolfram.com/MersennePrime.html One of the important things that It states, "Mersenne primes were first studied because of the remarkable properties that every Mersenne prime corresponds to exactly one perfect number" Using a Mersenne prime of 31 allows our algorithm to produce many more distinct integers than not using 31. Thus, less collisions that give us a more efficient hash table. Although, there has been a lot of advancement in regards to even better hashing algorithms lately and you can find many that cover them online today. Of course, for the purposes of the courses here on TreeHouse, we have already went well beyond anything you will need here. The auto generated code is good for now. Please check out the following for further study: https://courses.cs.washington.edu/courses/cse373/13wi/lectures/02-01/11-hashcode-map.pdf https://courses.cs.washington.edu/courses/cse331/11wi/lectures/lect10-equality.pdf Definitely check out MIT open courseware on time complexity of algorithms for more about algorithms and efficiency. http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/ Regards, Chris
2 of 3
1
Jonathan, Now that is a great question. The answer stems from the fact that the equals method and the hashCode method share some important relationships. As you likely know, the Object class is the superclass to all other classes and it has the implementation of these methods in which includes a contract between them. You can look over the documentation to see these relationships at the following website: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html Basically, we need a way to keep Object identity when using Objects within collections like hashMaps and hashTables because we could cause problems by placing Objects where they were not intended to go. The relationships/rules typically require us to use these methods together to meet these requirements. For example, if you wanted to use a HashMap to store key value pairs consisting of a Vehicle Object and a Integer Object in order to keep how many of each vehicle in the lot is the same type of vehicle (i.e BMW, M6, Blue): ```java HashMap amountOfEachVehicleInLot = new HashMap(); ``` You could not just use the equals method. The issue that would arise is from the fact that since the Vehicle object is not overriding the hashCode() method, they would return a hashCode() based on their reference that is different. Therefore, if we place a Vehicle in the hashMap with make: BMW, model: M6, color: blue and then attempt to use the HashMap's get method to retrieve an amount via making a new vehicle with the same make, model, and color, we would just get NULL in return. Why? Realistically, they are not the same car. They are two different cars with the same make, model, and color. However, we want to be able to retrieve the amount of cars in the lot that have the same make, model, and color. While there may be different ways to accomplish this goal, this example shows how overriding both the equals method and the hashCode method will allow us to do so. We would simply override the hashCode method to return an int based on something like the length of the color String. ```java @Override public int hashCode() { return mColor.length(); } ``` I hope this helps. Regards, Chris
🌐
Reddit
reddit.com › r/learnjava › eli5 why i need to override hashcode when overriding equals
r/learnjava on Reddit: ELI5 why I NEED to override hashCode when overriding equals
September 20, 2019 -

I started studying OCP and my study guide tells me that when you override equals, you are expected to override hashCode. There is no additional information why this is expected and I'm kind of in the dark about the relation between these two methods.

The compiler does not force me to do it, I just found by testing. Here's the equal method I made on a Hippo object for example and it seems to work like a charm. Why am I still expected to override the hashCode method as well?

    public boolean equals(Object obj){
        if(!(obj instanceof Hippo)) return false;
        Hippo h = (Hippo)obj;
        return this.name.equals(h.name) && this.age == h.age;
    }
🌐
Medium
medium.com › qudini-engineering › java-object-identity-or-how-to-override-equals-hashcode-and-compareto-400fd4547fe0
Java object identity, or how to override equals, hashCode and compareTo | by Christophe Maillard | Medium
June 8, 2018 - Without hashCode being overridden by Item, the Object's hashCode method is called: 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 Java™ programming language.)
🌐
Quora
quora.com › Is-it-a-good-practice-to-override-equals-and-hashCode-in-Java
Is it a good practice to override equals and hashCode in Java? - Quora
Answer (1 of 4): Whenever you override equals, you must override hash code swell, s.t. o1.equals(o2) => o1.hashcode()==o2.hashcode() 2 objects with equal hash codes don't have to be equal however. It is good practice though to have as less equal objects as possible to have the same hash code.
🌐
GeeksforGeeks
geeksforgeeks.org › java › override-equalsobject-hashcode-method
Why to Override equals(Object) and hashCode() method ? - GeeksforGeeks
December 22, 2025 - Example: This program shows why overriding both equals() and hashCode() is necessary when using objects as HashMap keys. ... import java.util.*; class Geek { String name; int id; Geek(String name, int id) { this.name = name; this.id = id; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Geek geek = (Geek) obj; return name.equals(geek.name) && id == geek.id; } @Override public int hashCode() { return id; } } class GFG { public static void main(String[] args) { Geek g1 = new Geek("Ram", 1); Geek g2 = new Geek("Ram", 1); Map<Geek, String> map = new HashMap<>(); map.put(g1, "CSE"); map.put(g2, "IT"); for (Geek geek : map.keySet()) { System.out.println(map.get(geek)); } } }
🌐
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: Java collections like HashMap and HashSet rely on hashCode() for efficient lookup. If two objects are considered equal according to equals(), they must have the same hashCode(). Otherwise, collections may fail to find elements, leading to unexpected behavior. Q: What happens if I override equals() but not hashCode()?
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-equals-hashcode
Java equals() and hashCode() | DigitalOcean
August 3, 2022 - I have explained it in detail at How HashMap works in java? The implementation of equals() and hashCode() should follow these rules. If o1.equals(o2), then o1.hashCode() == o2.hashCode() should always be true. If o1.hashCode() == o2.hashCode is true, it doesn’t mean that o1.equals(o2) will be true. When we override equals() method, it’s almost necessary to override the hashCode() method too so that their contract is not violated by our implementation.
🌐
Coderanch
coderanch.com › t › 548121 › java › Overriding-hashCode-equals
Overriding hashCode() and equals() (Java in General forum at Coderanch)
August 4, 2011 - They are considered equal because the objects compared contain the same value. That depends on the implementation of class Book. With the following implementation they are not equal: You have to override equals (and therefore also hashCode) to specify what equality means.
🌐
Quora
quora.com › How-is-hashCode-in-Java-implemented-and-when-should-I-override-it
How is hashCode in Java implemented and when should I override it? - Quora
Answer (1 of 4): hashCode() method is nothing but it gives unique identity(Hash Code number) to the object. It defines the uniqueness of the object. Default implementation of hashCode() is given in such a way that it returns the Hash Code number for the object based on the address of the object...
🌐
Test-king
test-king.com › blog › common-pitfalls-and-best-practices-for-overriding-equals-and-hashcode-in-java
overriding equals and hashCode best practices
The default behavior of hashCode() ensures that each object has a different hash code unless two references point to the same object. While this default implementation works fine for many scenarios, it is not sufficient when you need to compare objects based on their content rather than their memory address, especially when objects are stored in collections like HashMap or HashSet. This is where overriding ...
🌐
Medium
medium.com › @abdullahkhames96 › understanding-the-importance-of-overriding-the-hashcode-method-in-java-a35f7cd4aa0d
Understanding the Importance of Overriding the hashCode() Method in Java | by Abdullah khames | Medium
February 28, 2025 - To write a good hashCode() method, follow these steps: Initialize a Result Variable: Declare an int variable named result and initialize it to the hash code of the first significant field in your object. Combine Remaining Fields: For each remaining significant field f in your object: Compute an int hash code c for the field. Combine c into result using the formula: result = 31 * result + c · 3. Return the Result: Finally, return the computed result. @Override public int hashCode() { int result = Short.hashCode(areaCode); result = 31 * result + Short.hashCode(prefix); result = 31 * result + Short.hashCode(lineNum); return result; }
🌐
Learninjava
learninjava.com › why-equals-and-hashcode-override
Why You Should Override Equals and HashCode in Java?
Color : BLACK HashCode : 2018699554 Color : RED HashCode : 366712642 Color : BLUE HashCode : 1829164700 Is RED angry bird present in the buckets ? : false · From the output, if we do not override the hashCode() method, the RED bird to find has a different hashCode than RED bird in the HashSet.