Sub topic 7
Writing hashCode that matches equals
This chapter assumes you can write a Java class with fields and a constructor, and that you know the earlier chapters' equals contract and how HashMap and HashSet use hash codes. Here you write hashCode methods that stay consistent with equals, choose the right helper for each field type, and avoid the mistakes that make hash lookups fail without any error.
The one rule that drives the design
The hashCode contract has a single requirement that is easy to break: if a.equals(b) is true, then a.hashCode() == b.hashCode() must be true. The reverse is not required. Two unequal objects may share a hash code, and this is called a collision.
It follows that the fields used in hashCode must be a subset of the fields used in equals.
- Using fewer fields in
hashCodeis legal. Hashing only some of the compared fields gives more collisions but never wrong answers. - Using a field in
hashCodethatequalsignores is a bug. Two objects can be equal while their hashes differ.
Here is the violation in code. equals compares only id, but hashCode also mixes in name.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class Employee {
private final int id;
private final String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee)) return false;
return id == ((Employee) o).id; // id only
}
@Override
public int hashCode() {
return Objects.hash(id, name); // BUG: name is not in equals
}
public static void main(String[] args) {
Employee a = new Employee(1, "Ann");
Employee b = new Employee(1, "Anna");
System.out.println(a.equals(b)); // true
System.out.println(a.hashCode() == b.hashCode()); // false
Set<Employee> staff = new HashSet<>();
staff.add(a);
System.out.println(staff.contains(b)); // usually false
}
}The fix is to hash id alone, or to decide that name is part of equality and add it to equals.
Using Objects.hash
For most classes, Objects.hash is enough. It takes any number of values and combines them.
@Override
public int hashCode() {
return Objects.hash(x, y);
}Internally, Objects.hash(values...) calls Arrays.hashCode(Object[]). That method starts with result = 1 and, for each element, computes result = 31 * result + (element == null ? 0 : element.hashCode()). For Point(1, 2) this gives 31 * (31 * 1 + 1) + 2, which is 994. The same arithmetic means Objects.hash(x, y) equals 961 + 31 * x + y for ints.
Objects.hash has three properties worth knowing:
- It handles
nullelements by treating them as 0, so nullable fields need no special code. - It is order-sensitive.
Objects.hash(1, 2)differs fromObjects.hash(2, 1), which is usually what you want. - It allocates a varargs array and boxes primitives on every call. In a class that is hashed millions of times, this cost is measurable.
Writing it by hand
When performance matters, or when you want to see exactly what happens, write the combination yourself. The standard recipe is:
- Start with a result such as the hash of the first significant field.
- For each remaining field, compute its hash code, then do
result = 31 * result + fieldHash. - Return the result.
The multiplier 31 is an odd prime. It spreads bits better than a power of two would, and the JIT compiler can turn 31 * x into (x << 5) - x.
The right hash for each field type is:
| Field type | Hash expression | Why |
|---|---|---|
| `boolean` | `Boolean.hashCode(f)` | Returns 1231 or 1237 |
| `byte`, `short`, `char`, `int` | `Integer.hashCode(f)` or the value itself | Widening to int is exact |
| `long` | `Long.hashCode(f)` | Folds both 32-bit halves into one int |
| `float` | `Float.hashCode(f)` | Uses the bit pattern, so it agrees with `Float.compare` |
| `double` | `Double.hashCode(f)` | Uses the bit pattern, so it agrees with `Double.compare` |
| Object reference, possibly null | `Objects.hashCode(f)` | Returns 0 for null |
| Array | `Arrays.hashCode(f)` | Hashes contents, not the array identity |
| Nested array | `Arrays.deepHashCode(f)` | Recurses into inner arrays |
A complete example with a nullable field, a long, and a double:
import java.util.Objects;
public final class Price {
private final String currency; // may be null
private final long cents;
private final double rate;
public Price(String currency, long cents, double rate) {
this.currency = currency;
this.cents = cents;
this.rate = rate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Price)) return false;
Price p = (Price) o;
return Objects.equals(currency, p.currency)
&& cents == p.cents
&& Double.compare(rate, p.rate) == 0;
}
@Override
public int hashCode() {
int result = Objects.hashCode(currency);
result = 31 * result + Long.hashCode(cents);
result = 31 * result + Double.hashCode(rate);
return result;
}
public static void main(String[] args) {
Price a = new Price(null, 1999L, 1.5);
Price b = new Price(null, 1999L, 1.5);
System.out.println(a.equals(b)); // true
System.out.println(a.hashCode() == b.hashCode()); // true
}
}Each field in hashCode has a matching comparison in equals, and the pairs agree: Objects.equals pairs with Objects.hashCode, and Double.compare pairs with Double.hashCode.
Pair comparisons with the matching hash
Pairing matters most for floating-point values. If you write rate == p.rate in equals and Double.hashCode(rate) in hashCode, the contract breaks in two cases:
0.0 == -0.0is true, but the two values have different bit patterns, so their hash codes differ. Equal objects would get different hashes.Double.NaN == Double.NaNis false, so an object with a NaN field would never equal itself unless you checkthis == ofirst.
Double.compare(a, b) == 0 treats 0.0 and -0.0 as different and treats NaN as equal to itself. That matches Double.hashCode, which is derived from Double.doubleToLongBits. The same reasoning applies to Float.compare and Float.hashCode.
Arrays and collections as fields
An array's own hashCode is identity-based, so values.hashCode() returns different results for two arrays with the same contents. Use Arrays.hashCode(values) and compare with Arrays.equals(values, other.values). If Objects.hash receives an array as one of its arguments, it calls that array's identity hashCode, so pass Arrays.hashCode(values) explicitly:
@Override
public int hashCode() {
return 31 * Objects.hash(label, score) + Arrays.hashCode(values);
}Lists, sets, and maps define hashCode from their contents, so Objects.hash works with them directly. Remember that this hash changes if the collection is modified, which is the mutable-key problem covered in a later chapter.
Caching the hash
If an object is immutable and its hash is expensive to compute, you can cache it, as String does. Use 0 as the "not computed yet" marker:
private int hash; // 0 means "not computed yet"
@Override
public int hashCode() {
int h = hash;
if (h == 0) {
h = Objects.hash(x, y);
hash = h;
}
return h;
}This is safe without synchronization only when all fields are final and the cached value is a plain int. If two threads compute the hash at once, both produce the same value. If the real hash happens to be 0, the code recomputes it each time, which is slow but still correct. Do not cache for mutable classes, because the cached value would go stale.
Weak but legal hash codes
The contract allows this:
@Override
public int hashCode() {
return 42;
}It is correct, since equal objects get equal hashes. It is also a performance disaster, because every entry lands in one bucket. A HashMap then degrades to a linked structure with linear lookups. Since Java 8, a crowded bucket converts to a balanced tree, which helps only if the keys implement Comparable, and even then lookups are logarithmic instead of constant.
A good hash code spreads unequal objects across many values. It does not need to be unique.
Limits of what a hash code means
- Not stable across runs.
Object.hashCodeand the hash of enums are typically derived from identity, so they differ from one JVM run to the next. Never store a hash code in a file or database, and never let program output depend onHashSetiteration order. - Only some formulas are specified. The Javadoc fixes the formulas for
String,List,Set,Map.Entry, and boxed types, but not forObjects.hashin your own classes in a future release. Treat your own hash values as internal. - Overflow is fine. The arithmetic wraps around in
int, and that is expected. - Keep it fast and side-effect free.
hashCodeis called on every insert and lookup. It should not do I/O, take locks, or throw.
Checklist
- List the fields
equalscompares. - Use the same fields, or a subset, in
hashCode. - Pick the hash helper that matches each field's comparison:
Objects.hashCode,Long.hashCode,Double.hashCode,Arrays.hashCode. - Combine with
Objects.hash(...), or with31 * result + hfor hot paths. - Change both methods together whenever a field is added to or removed from equality.
Exercise
A class Box has fields int w, int h, and String label. Its equals compares only w and h. A teammate wrote hashCode as Objects.hash(w, h, label). Is this legal? What happens with Set<Box>, and how do you fix it?
Show answer
It is not legal. Two boxes with the same w and h but different labels are equal under equals but usually get different hash codes, which breaks the contract. A HashSet may then store both as duplicates or fail to find an equal element with contains. Fix it by changing hashCode to Objects.hash(w, h), or by adding label to equals if the label is meant to be part of equality.
Exercise
In equals you compare a double field with ==, and in hashCode you use Double.hashCode(field). Name one input pair where this breaks the contract, and say what to change.
Show answer
0.0 and -0.0. They are ==, so equals returns true, but their bit patterns differ, so Double.hashCode returns different values. Change equals to use Double.compare(a, b) == 0, which distinguishes 0.0 from -0.0 and agrees with Double.hashCode.