Java HashSet equals and hashCode Explained
Learn how Java HashSet uses equals() and hashCode() for duplicate detection, how to implement the contract correctly, and common mistakes to avoid.

When you store objects in a Java HashSet, the set's behavior depends entirely on the equals() and hashCode() methods of those objects. If these methods are not implemented consistently, the set may allow duplicates, fail to find elements, or behave unpredictably. This article explains how equals() and hashCode() work together in a HashSet, what the contract requires, and how to implement both correctly for reliable set behavior.
How HashSet Uses equals and hashCode
A HashSet is backed by a hash table. When you add an element, the set calls hashCode() on the object to determine which bucket to place it in. Inside that bucket, it then uses equals() to check whether an equal element already exists. If an equal element is found, the add operation does not insert a duplicate. Similarly, contains() and remove() follow the same path: compute the hash, locate the bucket, then scan with equals.
This means both methods are essential. If hashCode() returns different values for two objects that are equal according to equals(), the set will place them in different buckets and never detect the equality. The set will then contain duplicates, violating the Set contract.
The Contract Between equals and hashCode
The Java platform defines a contract between these two methods, documented on Object.equals() and Object.hashCode(). The most important rule is: if two objects are equal according to equals(), they must have the same hashCode(). The reverse is not required: two objects with the same hash code do not have to be equal, but if they are not equal and share a hash code, they will collide in the same bucket, which affects performance.
Additionally, hashCode() must be consistent: calling it multiple times on the same object during a single execution must return the same value, as long as no fields used in equals() change. This is why you should never use mutable fields in hashCode() or equals() if those fields can change after the object is placed in a HashSet.
Implementing equals Correctly
A typical equals() implementation follows a pattern: check identity, check null, check type, then compare significant fields. Here is an example for a simple Person class:
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 o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && name.equals(person.name);
}
}Using getClass() instead of instanceof avoids asymmetry when subclasses add fields and override equals(). If a superclass implementation uses instanceof, a subclass instance could be considered equal to a superclass instance, while the subclass's equals() may not consider the superclass instance equal, breaking the symmetric requirement of equals().
name.equals(person.name) assumes name is non-null; use Objects.equals(name, person.name) if null values are allowed.
Implementing hashCode Correctly
The companion hashCode() method must produce the same value for equal objects. A common approach is to combine the hash codes of the fields used in equals(). The Objects.hash() utility makes this concise:
@Override
public int hashCode() {
return Objects.hash(name, age);
}If you prefer a manual implementation for performance, use a prime multiplier and combine each field's hash:
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + age;
return result;
}The prime number reduces collisions, but the exact value is not critical. What matters is that hashCode() is based on fields that are guaranteed to be the same for equal objects; in practice, those are the fields compared in equals(). The manual version also assumes name is non-null; use Objects.hashCode(name) if nulls are allowed.
Common Mistakes That Break HashSet Behavior
One frequent mistake is overriding equals() without overriding hashCode(). The HashSet will then compute a different bucket for each instance, even if the objects are equal, so duplicates slip through. Another mistake is using mutable fields in hashCode(). If an object's hash changes after it is inserted, the set will not be able to find it later because the bucket lookup uses the new hash. This is a subtle bug that can cause memory leaks if objects are never removed.
A third mistake is implementing equals() with fields that are not used in hashCode(), or vice versa. To satisfy the contract reliably, base hashCode() on the same fields that equals() compares. If you compare a subset of fields in equals() but hash on all fields, equal objects may produce different hash codes.
Performance Implications of hashCode Quality
The distribution of hash codes directly affects HashSet performance. If hashCode() returns a constant value for all objects, every element lands in the same bucket. The set then loses the hash-table advantage: operations can degrade significantly, in the worst case from O(1) to O(n), or O(log n) in JDK versions that treeify collision-heavy buckets. A good hashCode() spreads objects evenly across buckets and keeps operations near constant time.
There is no need to obsess over the hash function; a reasonable combination of fields is sufficient. The main goal is to avoid severe collisions. For example, using a single field with a limited range, like a boolean, will produce at most two distinct hash codes, which is poor for a large set. Combining multiple fields with a multiplier helps distribute values.
When to Override equals and hashCode
You only need to override these methods when you care about logical equality rather than reference identity. Value objects, such as a Money class or a Point, should override them. Entity objects that have a database identity may not need to override them if reference identity is the intended meaning; if you need two instances representing the same row to be equal, implement equals() and hashCode() consistently.
If you do override equals(), you must override hashCode() as well. The Java compiler will not warn you, but the runtime behavior will be incorrect. Use IDE generation tools or libraries like Lombok to avoid mistakes, but understand what they generate so you can spot problems.
Debugging HashSet Issues
When a HashSet behaves unexpectedly, start by checking the hashCode() and equals() implementations of the stored objects. Print the hash codes of the objects you are adding and comparing. If two equal objects produce different hash codes, the bug is in hashCode(). If they produce the same hash but the set still contains duplicates, the bug is in equals().
Another useful technique is to use a debugger and inspect the internal table of the HashSet. On common JDK implementations, HashSet is backed by a HashMap, so you can look at the buckets and see where elements are placed. This often reveals collisions or misplaced elements immediately.
Remember that changing equals() or hashCode() after objects are inserted into a HashSet will not retroactively fix the bucket placement. You must remove the affected objects from the old bucket (for example, by iterating over the set) and re-add them. This is why immutable objects are preferred as set elements: their hash code never changes, and the set remains consistent throughout the object's lifetime.
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.