Implementing hashCode
Write correct hash functions.
Goals of a Good hashCode
A good hashCode() should:
- Return the same value for equal objects (the contract).
- Spread unequal objects across many different values.
- Be cheap to compute.
A poor hashCode that returns a constant still satisfies the contract but turns the map into a slow linked list.
public class Main {
public static void main(String[] args) {
// Legal but terrible: every object collides
System.out.println("constant hashCode is legal but kills performance");
}
}Objects.hash for the Common Case
The simplest correct approach is Objects.hash(field1, field2, ...).
It handles nulls and combines fields with a standard algorithm. Use the same fields you compare in equals.
import java.util.Objects;
public class Main {
static class User {
final String name; final int age;
User(String name, int age) { this.name = name; this.age = age; }
@Override public int hashCode() { return Objects.hash(name, age); }
}
public static void main(String[] args) {
User a = new User("Ada", 36);
User b = new User("Ada", 36);
System.out.println(a.hashCode() == b.hashCode());
}
}All lessons in this course
- How HashMap Works
- The equals/hashCode Contract
- Implementing hashCode
- Treeification and Performance