Sub topic 2
The `hashCode` Contract
Assume you know basic Java classes, inheritance, and HashMap and HashSet. This chapter focuses on how these collections use hashCode together with equals.
The `hashCode` contract
hashCode() returns an int used as a compact representation of an object’s equality-related state.
The important rules are:
- If two objects are equal according to
equals, they must have the same hash code. - Unequal objects may have the same hash code. This is called a collision.
- A hash code should remain stable while an object is stored in a hash-based collection, unless the fields used by equality do not change.
The contract does not require unequal objects to have different hash codes. It requires equal objects to have equal hash codes.
Why `HashMap` and `HashSet` need both methods
A HashMap first computes the key’s hash code to choose a bucket. It then calls equals on candidates in that bucket. A HashSet follows the same process to decide whether a value is already present.
This two-step design is fast because most objects can be rejected without comparing them fully. If you override equals but inherit Object.hashCode, equal objects usually receive different identity-based hash codes. The collection searches the wrong bucket.
import java.util.HashSet;
import java.util.Set;
final class Tag {
private final String name;
Tag(String name) {
this.name = name;
}
@Override
public boolean equals(Object other) {
return other instanceof Tag
&& name.equals(((Tag) other).name);
}
@Override
public int hashCode() {
return name.hashCode();
}
}
public class Main {
public static void main(String[] args) {
Set<Tag> tags = new HashSet<>();
tags.add(new Tag("java"));
System.out.println(tags.contains(new Tag("java"))); // true
}
}Writing `hashCode` that matches `equals`
Use exactly the fields that equals compares. Objects.hash is convenient for ordinary object fields:
@Override
public int hashCode() {
return Objects.hash(name, x, y);
}For arrays, use Arrays.hashCode. For primitive fields, use suitable primitive hashing methods or include them with Objects.hash. Never omit an equality field or include a field that equality ignores.
What `toString` is for
toString() produces a text description for logs, debugging, and messages. The default implementation usually looks like Package.Class@1a2b3c, where the final part is hexadecimal and related to the hash code. It rarely describes the object’s values.
Override it with useful state:
@Override
public String toString() {
return "Point{x=" + x + ", y=" + y + "}";
}Exercise
Equal objects have different hash codes. What happens in a HashSet?
Show answer
The set may place them in different buckets, so it can store duplicates or fail to find an equal value.