Java Keep Equality and Hashing Consistent
Hash-based collections rely on an equality contract. Objects that compare equal must return the same hash code, while different objects are allowed to share a hash code.
Understand the idea
The default Object equals normally represents identity. A value type may instead define equality from stable components. If you override equals, provide a compatible hashCode and satisfy reflexivity, symmetry, transitivity and consistency. Do not base a durable hash key on mutable state that changes after insertion. Hash collisions are expected possibilities, not proof that equals is broken.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
import java.util.Set;
import java.util.HashSet;
public class Main {
record BookingKey(String session, int groupNumber) {}
public static void main(String[] args) {
Set<BookingKey> keys = new HashSet<>();
keys.add(new BookingKey("Clay", 4));
keys.add(new BookingKey("Clay", 4));
System.out.println(keys.size());
System.out.println(keys.contains(new BookingKey("Clay", 4)));
}
}
Expected output
1
trueThe record supplies value-oriented equals and hashCode from both components. The set recognises the second value as equal to the first even though new created a different object. The string and int components are stable for this example, making the record an appropriate key representation.
Check the official Java documentation for detailed contracts and supported options.