SteelReed

Search

Search posts, questions…

1. Java Core

Immutable objects, equals/hashCode and final: why a HashMap loses your object

Why a HashMap returns null for a key you just put and a HashSet keeps two identical copies: a hash table looks up by hash before it compares with equals. Immutable value objects and records, the equals/hashCode contract, what final locks, inlined static final constants, and how to review AI-written equals/hashCode.

17 Nov 20268 min readMid

–

1. The problem

A login session cache is a Map<UserKey, Session>, and UserKey holds userId and an email with a setter. When a user changes email, get returns null and the system creates a new session. A week later the map holds 380,000 orphaned sessions, the heap is full, and there's no exception anywhere.

2. Key idea

A hash table doesn't compare every element. It computes a hash to pick a bucket, then compares equals only inside that bucket. If hash and equals disagree, it looks in the wrong bucket.

Bug Symptom Root cause
Override equals, forget hashCode a set holds two "identical" copies two equal objects land in two buckets
Modify a key after put get returns null while size() is 1 the entry sits in the old hash's bucket
BigDecimal.equals 100.00 and 100.0 are two elements it compares scale too

2.1 Compare by value or by identity?

  • Value object (Money, Email, DateRange): same value means the same thing. Make it immutable, equals/hashCode over every field.
  • Entity (Account, Order): has an id, state changes over time. Don't compare on fields that change.
Choice Use when Don't use when
Immutable value object (record) money, email, map or cache keys objects with a lifecycle that change state
equals by id or business key entities that live in a Set the id only exists after saving and null isn't handled
Default equals (identity) services, connections objects crossing APIs, caches, tests

Immutability also gives you sharing across threads without locks.

3. In Java

JAVA
public record Money(BigDecimal amount, String currency) {
    public Money {                                       // compact constructor
        Objects.requireNonNull(currency);
        amount = amount.setScale(2, RoundingMode.UNNECESSARY);   // 100.0 and 100.00 become one
    }
    public Money plus(Money other) {                     // "changing" returns a new object
        return new Money(amount.add(other.amount), currency);
    }
}
 
public record Customer(String name, List<String> tags) {
    public Customer { tags = List.copyOf(tags); }        // records are only shallowly immutable
}
 
final List<String> xs = new ArrayList<>();
xs.add("a");                                             // fine: final only forbids reassignment

Other languages: Kotlin data class, C# record, Python @dataclass(frozen=True). Python sets __hash__ = None when you define __eq__ without __hash__.

static final constants get copied into other classes

public static final int MAX_RETRY = 3 is a compile-time constant: the compiler copies 3 straight into the bytecode of every class that uses it. If the library changes it to 5 and the service isn't rebuilt, the service still uses 3.

  • Check: javap -c -constants on the calling class shows the literal 3, no getstatic.
  • If a value can change between library versions, don't make it a public constant: use static int maxRetry() or config.
  • Only primitives and Strings initialized with constants are copied. A static final List isn't.

4. Working with AI

Hand to AI: converting value classes to record, generating equals/hashCode contract tests, finding every place your own objects are HashMap keys or HashSet elements.

Check yourself in AI-written code:

  • Every field in equals is also in hashCode, and vice versa.
  • Fields used by equals are final, with no setters.
  • BigDecimal scale is normalized; no compareTo in equals paired with a BigDecimal-based hashCode.
  • JPA entities don't carry Lombok @Data or @EqualsAndHashCode over every field.
  • Collections in records are List.copyOf-ed; toString doesn't print passwords or tokens.

5. Exercises

Exercise 1: Review the AI's Money

The AI says "compares by value, 100.0 equals 100.00". Find the bug, write a test that proves it, fix it.

JAVA
public final class Money {
    private final BigDecimal amount;
    private final String currency;
    // constructor assigns both fields
 
    @Override public boolean equals(Object o) {
        return o instanceof Money m && amount.compareTo(m.amount) == 0 && currency.equals(m.currency);
    }
    @Override public int hashCode() { return Objects.hash(amount, currency); }
}
Solution 1

equals uses compareTo, which ignores scale, but BigDecimal.hashCode includes scale. 100.0 and 100.00 are equal yet usually hash differently: the contract is broken.

JAVA
Set<Money> set = new HashSet<>();
set.add(new Money(new BigDecimal("100.0"), "VND"));
assertTrue(set.contains(new Money(new BigDecimal("100.00"), "VND")));   // usually false

Fix: normalize scale in the constructor (as in section 3) and use plain equals/hashCode, or switch to a record. Alternatively hash amount.stripTrailingZeros(), but normalizing once in the constructor reads better.

Exercise 2: Choose equals for an entity

Customer holds a Set<Order>; Order is a JPA entity whose status moves from NEW to PAID. The AI offers two options: (A) Lombok @Data; (B) equals by id (a null id only equals itself), hashCode returning a per-class constant. Pick one, explain, and say when to use a third option.

Solution 2

Pick B. With A, changing status changes the hash: the order inside the Set gets "lost" as in section 1, and @Data also touches lazy relations. B keeps the hash fixed for the whole lifecycle, including before saving. The cost: every order shares a bucket, so contains is O(n); fine because one customer's set is small.

The third option, better when available: an immutable business key created before saving (order number, UUID made in the constructor). Then equals/hashCode use that key.

Summary

  • HashMap returns null for a key you just put when the hash changed or disagrees with equals.
  • Objects equal by equals must share a hashCode.
  • Value objects are immutable; entities compare by id or business key.
  • record is only shallowly immutable: List.copyOf in the compact constructor.
  • final only forbids reassignment; static final constants get copied into the classes using them.

Further reading: Wrappers, BigDecimal and String.

Practice interview questions on this topic

All Java Core questions →

Loading comments…