Module lessons (2/2)
Contract equals/hashCode and Immutability
Correctly implement equals + hashCode for HashSet/HashMap, defensive copies List.copyOf, and immutable objects.
What you'll learn in this lesson
- Implement
equals(Object)andhashCode()respecting the symmetric and consistent contract viaObjects.equalsandObjects.hash. - Understand why mutable keys or an inconsistent
hashCodesilently breakHashMapandHashSet. - Design immutable value classes with defensive copies (
List.copyOf) and implementComparable<T>without overflow bugs.
Overview
If you use a record in Java 17+, the compiler already generates equals, hashCode and shallow immutability for you. However, when you work with a traditional class (or extend existing code), violating the contract between equals and hashCode generates bugs that are very difficult to detect.
The golden rule of java.lang.Object states: if a.equals(b) is true, then a.hashCode() == b.hashCode() MUST be true. Implement it safely with pattern matching instanceof and java.util.Objects:
Sections covered in this lesson
- 11. The Contract
equalsandhashCode - 22. Why
HashSetandHashMapBreak WithouthashCode - 33. Immutability and Defensive Copies
- 44.
Comparable<T>Without Overflow Bugs - 5Try it yourself
Unlock "Contract equals/hashCode and Immutability" and the full Course Java curriculum
Correctly implement `equals` + `hashCode` for `HashSet`/`HashMap`, defensive copies `List.copyOf`, and immutable objects.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Java plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.