Understanding the Java hashCode Method
How the Java hashCode method works, why it must align with equals, and how to implement it correctly for hash-based collections.

Every Java object has a hashCode method. It returns an integer that hash-based collections use to decide which bucket an entry belongs to. The method is defined on Object, and its behavior is often misunderstood until a HashMap or HashSet returns unexpected results. When hashCode disagrees with equals, collections can store entries in the wrong bucket and fail to retrieve them.
The hashCode Contract
The contract for hashCode is specified in the Object class. Every implementation must satisfy three rules:
- Consistency during execution: If an object's state does not change, calling
hashCodemultiple times must return the same integer during the same execution of the application. - Equal objects must have equal hash codes: If
a.equals(b)istrue, thena.hashCode()must equalb.hashCode(). - Unequal objects may have equal hash codes: This is allowed, but collisions reduce performance. The contract does not require distinct hash codes for distinct objects.
These rules are not optional. Violating the second rule breaks hash-based collections. If two equal objects produce different hash codes, a HashMap can put them in different buckets, and get may not find the value you stored.
The Relationship Between equals and hashCode
The equals and hashCode methods are tightly coupled. Whenever you override equals, you must also override hashCode. Hash-based collections first compare hash codes to narrow the search, then use equals to confirm equality. If two objects are equal but have different hash codes, the collection never calls equals on them because they land in different buckets.
Consider a simple Person class with a name field. If you override equals to compare names but leave hashCode as the default identity-based implementation, two Person instances with the same name will not be treated as equal by a hash-based collection. The default hashCode implementation is usually based on the object's identity rather than its state, so the two instances will almost certainly have different hash codes.
Implementing hashCode Correctly
A common approach is to compute a hash code from the same fields that equals compares. The algorithm typically starts with a nonzero value, multiplies by a prime number, and accumulates the hash codes of the individual fields. The prime 31 is often used because it is odd and produces a reasonable distribution.
Here is a typical implementation for a class with a String field and an int field:
public class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Person)) return false;
Person other = (Person) obj;
return age == other.age && name.equals(other.name);
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
result = 31 * result + age;
return result;
}
}Because this implementation calls name.hashCode() directly, it assumes name is not null. If name can be null, use Objects.hashCode(name) or the Objects.hash shortcut below.
The initial value 17 and the multiplier 31 are conventional. The important part is that hashCode uses the same fields as equals. If you change the fields used in equals, change them in hashCode too.
Using Objects.hash for a Concise Implementation
Java 7 added the Objects utility class with a static hash method. It accepts a varargs array of fields and computes a combined hash code. The result is equivalent to a manual implementation, but with less boilerplate.
import java.util.Objects;
public class Person {
private final String name;
private final int age;
// constructor, equals...
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}Objects.hash boxes its arguments into an array and delegates to Arrays.hashCode(Object[]). That implementation treats null elements as zero, so it is null-safe. This is a good default choice for most classes. However, it creates an array for each call, which adds a small allocation overhead. For most applications this is negligible, but if you are creating millions of objects per second, a manual implementation might be slightly faster.
Common Mistakes That Break Collections
One of the most common mistakes is using a mutable field in the hash code calculation. If an object's hash code changes after it has been inserted into a HashMap, the object will be lost. The collection stores it in the bucket corresponding to the original hash code, but on lookup the new hash code points to a different bucket.
public class MutableKey {
private String value;
public void setValue(String value) {
this.value = value;
}
@Override
public int hashCode() {
return value.hashCode();
}
}If you mutate value after inserting this object into a HashSet, the set will be unable to find it. The solution is to make hash-code fields final or to ensure they are not modified after the object is placed in a collection.
Another mistake is forgetting to override hashCode when overriding equals. This is so common that many IDEs generate both methods together. The compiler does not enforce the relationship, so the error only surfaces at runtime.
A third mistake is using a hash code that is always the same constant. This satisfies the contract but makes every lookup a linear scan, destroying the performance benefit of hash-based collections. The hash function should distribute values reasonably across the integer range.
Performance Considerations for hashCode
Hash code computation happens on every put and get operation in a hash-based collection. If the method is expensive, it becomes a bottleneck. The cost depends on the fields involved. A String field's hashCode is cached after the first call, so repeated calls are cheap. If a field is an array and you use Arrays.hashCode to include its contents, computing that hash requires iterating over the array each time, which can be costly for large arrays.
If an object is immutable and its hash code is frequently needed, you can cache the hash code in a field. This is common for immutable value objects.
import java.util.Objects;
public class Point {
private final int x;
private final int y;
private int cachedHash;
private boolean hashComputed;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
if (!hashComputed) {
cachedHash = Objects.hash(x, y);
hashComputed = true;
}
return cachedHash;
}
}A boolean flag avoids the edge case where the computed hash code is 0. If you do this, remember that the fields included in the hash code must be stable after the object is created.
When Not to Override hashCode
If a class is never used in hash-based collections, the omission may not show up immediately. However, it is still good practice to override it whenever you override equals, because you cannot predict how the class will be used in the future. A library class that is part of a public API should always have a consistent equals and hashCode pair.
There is also a case where you should not override equals at all, and therefore you should not override hashCode either: when you want identity semantics. The default Object implementations are correct when two references should be equal only if they point to the same object, such as for mutable objects used as keys with explicit reference identity. For value objects like String, Integer, or custom DTOs, overriding both methods is almost always the right choice. Keep the fields used in hashCode consistent with those used in equals, and make sure those fields are stable after the object is created.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.