Skip to main content
Module 10 · Lesson 2 of 222/22 in the course~16 min
Module lessons (2/2)

Contract equals/hashCode and Immutability

Lesson preview5 hands-on exercises readyCourse Java · Module 10 — Testing JUnit 5 and Contracts OOP

Correctly implement equals + hashCode for HashSet/HashMap, defensive copies List.copyOf, and immutable objects.

What you'll learn in this lesson

  • Implement equals(Object) and hashCode() respecting the symmetric and consistent contract via Objects.equals and Objects.hash.
  • Understand why mutable keys or an inconsistent hashCode silently break HashMap and HashSet.
  • Design immutable value classes with defensive copies (List.copyOf) and implement Comparable<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

  1. 11. The Contract equals and hashCode
  2. 22. Why HashSet and HashMap Break Without hashCode
  3. 33. Immutability and Defensive Copies
  4. 44. Comparable<T> Without Overflow Bugs
  5. 5Try it yourself
Pro Lesson · Module 10 — Testing JUnit 5 and Contracts OOP

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.