If id is of type int (instead of Integer), id can't be null so you can use:

@Override
public int hashCode() {
    return id;
}

However, if you want to avoid the case that new Product(n) and Integer.valueOf(n) share the same hashCode, you can do:

@Override
public int hashCode() {
    int hash = getClass().hashCode();
    hash = 31 * hash + id;
    return hash;
}
Answer from Oboe on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › core java › overriding hashcode() and equals() for records
Overriding hashCode() And equals() For Records | Baeldung
January 16, 2024 - @Override public int hashCode() { return Objects.hash(name, yearOfRelease); } We can test the equality of two Movie records correctly now: @Test public void givenTwoRecords_whenCustomImplementation_thenCompareEquality() { Movie movie1 = new ...
🌐
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)); } } }
🌐
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.
🌐
JetBrains
jetbrains.com › guide › java › tips › generate-equals-hashcode
Generate Overrides for equals(), hashCode() and toString() - JetBrains Guide
February 17, 2023 - editing java · You can use ⌘N (macOS) / Alt+Insert (Windows/Linux) for the Generate menu and then select equals() and hashCode(). You can also use the same shortcut again and select toString() to override that method as well.
🌐
Hostman
hostman.com › tutorials › overriding the hashcode method in java
Java: Overriding the hashCode Method
December 29, 2025 - Learn how to override the hashCode method in Java. This guide covers the relationship with equals and best practices for implementation.
Price   $
Address   1999 Harrison St 1800 9079, 94612, Oakland
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.

🌐
Reddit
reddit.com › r/javahelp › @override hashcode method usage
r/javahelp on Reddit: @Override hashCode method usage
May 13, 2024 -

Hello guys,

Can anyone give me real-life example of hashCode useage. Where, when and why should we use the overridden hashCode method in a class?

Thank you!

Top answer
1 of 5
15
The main purpose of hashCode in Java is to provide an approximated answer to the question Are these two Java objects identical?. Why an approximation? More often than not two objects are not identical. If the approximation is good enough, we can avoid any more costly identity checks. Complicated identity checks? Whether to objects are identical is completly arbitrary from the JVMs point of view. It can't infer what identical means to you in each case you make an identity check. So there are some built-in assumptions what identity means for the JVM, with the option of providing your own rules. Out of the box you have identity checks via ==. That is, you take two objects, like two instances of String, and compare them with ==. This will, for beginners unexpectedly, check whether the two objects are represented by the same location in the JVM memory. For primitives like int or boolean == will compare the actual values as expected. As you already know, for Strings we more often than not care about the actual contents, not the location in memory. So to do a comparison on the content you can use the refined check via Object.equals. In the case of String, the Java authors already made sure that the equals implementation of String will check via the underlying bytes, i.e. the String content. Imagine you have a bunch of Strings which store the text of a large books. Instead of constantly comparing their contents whenever you want to know if they are identical, i.e. instead of directly calling Object.equals (which is overriden by String.equals), you can call Object.hashCode (also overriden by String.hashCode) instead. Since the content of String instance never changes, the hashCode can be only computed once from the content, and reused afterwards. Beyond the special meaning you assign to hashCode and equals for your needs, there are several data structures like Sets and Maps which also make use of the hashCode approximation to improve their performance in the average case this way.
2 of 5
6
If you override equals you should also override hashcode - 2 equal objects should result in the same hashcode. Pre record classes and pre Lombok every class holding data that might be stored in some kind of collection would override both.
Find elsewhere
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
🌐
Mkyong
mkyong.com › home › java › java – how to override equals and hashcode
Java - How to override equals and hashCode - Mkyong.com
March 24, 2016 - public class User { private String ... : Item 9 @Override public int hashCode() { int result = 17; result = 31 * result + name.hashCode(); result = 31 * result + age; result = 31 * result + passport.hashCode(); return result; } }...
🌐
Javainuse
javainuse.com › java › javaHash
Overriding hashcode method in Java - Hello World Example
package com.javainuse.domain; public class Employee { private String name; public Employee(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { return name.length()-1; } } Here ...
🌐
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.
🌐
Crunchify
crunchify.com › java j2ee tutorials › java collections – hashcode() and equals() – how to override equals() and hashcode() method in java?
Java Collections - hashCode() and equals() - How to Override equals() and hashcode() Method in Java? • Crunchify
December 31, 2021 - @Override public boolean equals(Object ... { return true; } else { return false; } } @Override public int hashCode() { int result = 0; result = (int) (value / 11); return result; } } Test1: One and Two are equal Test2: Three and ...
Top answer
1 of 11
1482

The theory (for the language lawyers and the mathematically inclined):

equals() (javadoc) must define an equivalence relation (it must be reflexive, symmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null) must always return false.

hashCode() (javadoc) must also be consistent (if the object is not modified in terms of equals(), it must keep returning the same value).

The relation between the two methods is:

Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().

In practice:

If you override one, then you should override the other.

Use the same set of fields that you use to compute equals() to compute hashCode().

Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. An example:

public class Person {
    private String name;
    private int age;
    // ...

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
            // if deriving: appendSuper(super.hashCode()).
            append(name).
            append(age).
            toHashCode();
    }

    @Override
    public boolean equals(Object obj) {
       if (!(obj instanceof Person))
            return false;
        if (obj == this)
            return true;

        Person rhs = (Person) obj;
        return new EqualsBuilder().
            // if deriving: appendSuper(super.equals(obj)).
            append(name, rhs.name).
            append(age, rhs.age).
            isEquals();
    }
}

Also remember:

When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, or WeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits.

2 of 11
303

There are some issues worth noticing if you're dealing with classes that are persisted using an Object-Relationship Mapper (ORM) like Hibernate, if you didn't think this was unreasonably complicated already!

Lazy loaded objects are subclasses

If your objects are persisted using an ORM, in many cases you will be dealing with dynamic proxies to avoid loading object too early from the data store. These proxies are implemented as subclasses of your own class. This means thatthis.getClass() == o.getClass() will return false. For example:

Person saved = new Person("John Doe");
Long key = dao.save(saved);
dao.flush();
Person retrieved = dao.retrieve(key);
saved.getClass().equals(retrieved.getClass()); // Will return false if Person is loaded lazy

If you're dealing with an ORM, using o instanceof Person is the only thing that will behave correctly.

Lazy loaded objects have null-fields

ORMs usually use the getters to force loading of lazy loaded objects. This means that person.name will be null if person is lazy loaded, even if person.getName() forces loading and returns "John Doe". In my experience, this crops up more often in hashCode() and equals().

If you're dealing with an ORM, make sure to always use getters, and never field references in hashCode() and equals().

Saving an object will change its state

Persistent objects often use a id field to hold the key of the object. This field will be automatically updated when an object is first saved. Don't use an id field in hashCode(). But you can use it in equals().

A pattern I often use is

if (this.getId() == null) {
    return this == other;
}
else {
    return this.getId().equals(other.getId());
}

But: you cannot include getId() in hashCode(). If you do, when an object is persisted, its hashCode changes. If the object is in a HashSet, you'll "never" find it again.

In my Person example, I probably would use getName() for hashCode and getId() plus getName() (just for paranoia) for equals(). It's okay if there are some risk of "collisions" for hashCode(), but never okay for equals().

hashCode() should use the non-changing subset of properties from equals()

🌐
Medium
medium.com › codelog › overriding-hashcode-method-effective-java-notes-723c1fedf51c
Overriding hashCode method — Effective Java Notes | by Lou | Code Log | Medium
August 3, 2017 - Overriding hashCode method — Effective Java Notes When overriding the equalmethod, always override the hashCode()method, or the HashSet, HashMap... methods would fail. If two objects equal, then …
🌐
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()?
🌐
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 - @Override public int hashCode() { int result = Short.hashCode(areaCode); result = 31 * result + Short.hashCode(prefix); result = 31 * result + Short.hashCode(lineNum); return result; }
🌐
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().
🌐
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)
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.
🌐
InApp
inapp.com › home › if we override equals(), then we may or may not override hashcode(). (java override equals | java override hashcode)
If we override equals(), then we may or may not override hashcode(). (Java override equals | Java override hashcode) - InApp
May 24, 2023 - What is wrong with the 1st example? The two instances of HashCodeSample are logically equal according to the class’s equals method. Because the hashCode() method is not overridden, these two instances’ identities are not in common with the default hashCode implementation.