Immutability and Equality

An immutable object is one whose observable state cannot change after construction: no setters, every field assigned once, and nothing handed out that a caller could write through. Equality is the matching question – when two such objects count as the same value – and in any language with hash-based collections that is a contract with clauses you can violate, not an opinion. The two are one topic, because the contract holds only while the fields equals reads stay put.

💡 Value object = an object identified by what it holds, so two instances with equal fields are interchangeable: Money, a point, a cell style. Entity = an object identified by an id it keeps for life, so two with identical fields are still two different things.

Why this matters: several patterns quietly stand on this lesson. A Flyweight pool never scores a hit without correct equals and hashCode; a Memento holding a reference to live state is not a snapshot; Prototype is the question of which fields are safe to share; a Strategy or Specification wants to be stateless so one instance serves everyone. Interviewers test it head-on too, with the most reliable trick question in object-oriented design: an object put into a HashMap, mutated, and then not found in the map it is still sitting in.


Prerequisites

  • SOLID Principles – a value object is the smallest single responsibility there is, and composition fixes the subclass problem below
  • Collections and Complexity – a HashMap picks a bucket from the hash code, which is the whole bug in the next section
  • Money Handling – the Money below comes from there; this lesson covers its equality and immutability, not its arithmetic

The Problem: the mutable key that disappears from its own HashMap

Every system with a cache has a key class like this – see Multilevel Cache. Somebody did the right thing and overrode equals and hashCode so two equal keys hit one entry. Somebody else left the setter in:

// A cache key with proper equals and hashCode over its fields -- and a setter.
public class OrderKey {
    private final String customerId;
    private int warehouseId;

    public OrderKey(String cust, int wh) { customerId = cust; warehouseId = wh; }
    public void setWarehouseId(int warehouseId) { this.warehouseId = warehouseId; }

    @Override public boolean equals(Object o) {
        if (!(o instanceof OrderKey other)) return false;
        return warehouseId == other.warehouseId
            && customerId.equals(other.customerId);
    }

    @Override public int hashCode() {
        return Objects.hash(customerId, warehouseId);   // over a mutable field
    }
}

// And here is the afternoon you lose to it:
Map<OrderKey, Order> cache = new HashMap<>();
OrderKey key = new OrderKey("CUST-91", 7);
Order order = new Order(lineItems);   // Order keeps that list, does not copy
cache.put(key, order);
cache.get(key);               // the Order. Everything is fine.

key.setWarehouseId(8);        // one setter call, in unrelated code

cache.get(key);               // null
cache.remove(key);            // null -- cannot even evict it
cache.containsValue(order);   // true, and size() is still 1
cache.entrySet().forEach(System.out::println);   // prints the entry

// The second cost, no map involved: getItems() hands back that same live list.
order.getItems().clear();     // allowed, from any caller, at any time
order.getTotal();             // the old total: the invariant is now a lie

Three things are wrong, and the first is the mechanism you must be able to say out loud:

  1. The hash was computed at insertion and it chose the bucket. put calls hashCode() once, spreads it, and derives an index into the table array – that index is where the entry physically goes. Mutating warehouseId changes what hashCode() returns, so get derives a different index, searches a bucket the entry was never placed in, and reports nothing. The entry sits intact in the bucket the old hash picked, which is why containsValue is true, size() is 1, and iteration prints it: iteration walks the table instead of hashing. Nothing throws; the entry is just unreachable by key forever, remove included, so this leaks as well as misbehaves. HashSet is a HashMap underneath and fails identically.
  2. Order defended an invariant and then gave away the front-door key. total was summed from items in the constructor, so the two must agree – and getItems() returns the live list, so any caller can empty it and leave total describing items that no longer exist. It leaks inward too: the constructor stored the caller’s list, not a copy.
  3. The defect is equals and hashCode over mutable fields; the setter is only the trigger. That is why it survives review: it fires only when something mutates a key after insertion, usually far from both the key class and the map, and a test that builds a fresh key per lookup never sees it. Nor can you reproduce it from the report, which says “the cache misses sometimes”.

The three rules

1. Make it final, and make the fields final. No setters, and every field assigned exactly once in the constructor. The class itself final – or the constructor private behind static factories – so no subclass can bolt on a mutable field and inherit an immutable type’s reputation. Then the two directions people forget: copy mutable constructor arguments in, because the caller keeps their reference, and copy or wrap mutable values out, because a getter returning the live object has handed over write access.

💡 Defensive copy = copying a mutable object as it crosses your class boundary, in either direction, so no reference to your internals exists outside you. Learn more →

2. If you override equals, override hashCode – and make both read only fields that cannot change. equals carries five clauses that the JDK, your collections and your own code assume without checking: reflexive, symmetric (x.equals(y) exactly when y.equals(x)), transitive, consistent (repeated calls agree while nothing in the comparison changes), and false for null. hashCode carries one clause and one deliberate non-clause: equal objects must produce equal hash codes, and unequal objects may collide, which is legal and costs only a comparison. Consistency is the clause the mutable key broke, and final fields make it unbreakable rather than merely unbroken.

3. An immutable object needs no copy, no lock and no defensive anything. Nothing to clone before passing it somewhere, because the callee cannot damage it; nothing to synchronise, because no thread can observe a change that cannot happen; no copy on the way out, no “has someone modified this” check, no equality trio going stale. The first two rules are the price, this is the payoff, and it is why the shortest correct answer to a thread-safety question in an LLD round is often “that type is immutable.”


Real-World Example: Money in a Payment Wallet

import java.math.BigDecimal;
import java.util.*;

/** Final class, final fields, no setters, amount in minor units. */
public final class Money {
    private final long minorUnits;
    private final Currency currency;

    private Money(long minorUnits, Currency currency) {
        this.minorUnits = minorUnits;
        this.currency = Objects.requireNonNull(currency, "currency");
    }

    public static Money ofMinor(long m, Currency ccy) { return new Money(m, ccy); }

    // "Mutators" return a new instance and never touch this one.
    public Money plus(Money other) {
        requireSameCurrency(other);
        return new Money(Math.addExact(minorUnits, other.minorUnits), currency);
    }

    public Money minus(Money other) {
        requireSameCurrency(other);
        return new Money(Math.subtractExact(minorUnits, other.minorUnits), currency);
    }

    // Adding INR to USD is a bug, not a conversion. Fail at the boundary.
    private void requireSameCurrency(Money other) {
        if (!currency.equals(other.currency))
            throw new CurrencyMismatchException(currency, other.currency);
    }

    // The trio, over two fields that cannot change.
    @Override public boolean equals(Object o) {
        if (this == o) return true;                      // cheap, and reflexive
        if (!(o instanceof Money other)) return false;   // false for null, too
        return minorUnits == other.minorUnits
            && currency.equals(other.currency);
    }

    @Override public int hashCode() { return Objects.hash(minorUnits, currency); }

    @Override public String toString() {
        return currency.getCurrencyCode() + " "
             + BigDecimal.valueOf(minorUnits, currency.getDefaultFractionDigits());
    }
}

/** The same discipline, on a class owning a collection. */
public final class Order {
    private final String orderId;
    private final List<LineItem> items;   // final reference AND fixed contents
    private final Money total;

    public Order(String orderId, List<LineItem> items, Currency ccy) {
        this.orderId = Objects.requireNonNull(orderId);
        // Copy IN: the caller's list is now irrelevant to us, and copyOf also
        // rejects null elements and returns an unmodifiable list.
        this.items = List.copyOf(items);
        this.total = this.items.stream().map(LineItem::lineTotal)
                .reduce(Money.ofMinor(0, ccy), Money::plus);
    }

    // Copy OUT is already done -- add() on this throws. An ArrayList field would
    // need Collections.unmodifiableList or a copy, and LineItem must be
    // immutable too: a list you cannot add to, holding editable objects, is not.
    public List<LineItem> items() { return items; }
}
from dataclasses import dataclass


@dataclass(frozen=True, slots=True)
class Money:
    """frozen=True blocks attribute assignment and, with the default eq=True,
    generates __eq__ and __hash__ -- the pair, never one. eq=True WITHOUT
    frozen=True sets __hash__ = None, so a mutable dataclass is unhashable and
    Python refuses outright to let you key a dict with it."""

    minor_units: int
    currency: str = "INR"

    def plus(self, other: "Money") -> "Money":
        if self.currency != other.currency:
            raise CurrencyMismatch(self.currency, other.currency)
        return Money(self.minor_units + other.minor_units, self.currency)


@dataclass(frozen=True, slots=True)
class Order:
    """frozen=True is SHALLOW: it stops `order.items = [...]` but not
    `order.items.append(...)`, so a list field here is a mutable field with a
    read-only name. And list is unhashable, so hash(order) raises TypeError --
    Python saying out loud what Java's Objects.hash quietly lied about."""

    order_id: str
    items: tuple["LineItem", ...]       # tuple, not list: immutable and hashable

    def __post_init__(self) -> None:
        # object.__setattr__ is the documented escape hatch inside __post_init__;
        # plain assignment on a frozen instance raises FrozenInstanceError.
        object.__setattr__(self, "items", tuple(self.items))
#include <cstdint>
#include <functional>
#include <string>
#include <vector>

// Value semantics: copyable, movable, equality-comparable, every member function
// const. Declaring the members themselves `const` says it more strongly but
// deletes copy-assignment, so the type can no longer live in a std::vector that
// reassigns elements. Either way `const` is compiler-enforced, while an
// "immutable" Java class is only a promise.
class Money {
public:
    Money(std::int64_t minorUnits, std::string currency)
        : minorUnits_(minorUnits), currency_(std::move(currency)) {}

    std::int64_t minorUnits() const noexcept { return minorUnits_; }
    const std::string& currency() const noexcept { return currency_; }

    // C++20: member-wise ==, generated, and guaranteed to stay in step when a
    // field is added later, which the Java tab's hand-written equals is not. A
    // defaulted operator<=> is deliberately absent: it would order members
    // lexicographically and cheerfully compare INR against USD.
    bool operator==(const Money&) const = default;

private:
    std::int64_t minorUnits_;
    std::string currency_;
};

// Specialising std::hash is what makes Money an unordered_map key -- the exact
// counterpart of overriding hashCode, and just as non-optional.
namespace std {
template <>
struct hash<Money> {
    size_t operator()(const Money& m) const noexcept {
        size_t h = hash<int64_t>{}(m.minorUnits());
        return h * 31 + hash<string>{}(m.currency());
    }
};
}   // namespace std

// A collection member needs no defensive copy here: held BY VALUE, taking the
// vector by value and moving it IS the copy Java needs List.copyOf for, and
// handing it back as a const reference will not compile against push_back.
class Order {
    std::string id_;
    std::vector<LineItem> items_;

public:
    Order(std::string id, std::vector<LineItem> items)
        : id_(std::move(id)), items_(std::move(items)) {}

    const std::vector<LineItem>& items() const noexcept { return items_; }
};

The five places this goes wrong in practice

equals and inheritance: the ColorPoint symmetry break

Give Point an equals that uses instanceof and compares x and y, then subclass it as ColorPoint whose equals also compares the colour. Now point.equals(colorPoint) is true while colorPoint.equals(point) is false: symmetry is broken, so list.contains(p) answers differently depending on which of the two the list holds. Patching that to “ignore colour against a plain Point” breaks transitivity instead – a red point equals the plain point, the plain point equals a blue point, and the two coloured points do not equal each other. Using getClass() != o.getClass() restores symmetry but costs substitutability, so an ORM’s lazy proxy subclass is never equal to the entity it proxies. There is no fully correct equals across a subclass that adds a field, so make value classes final and add the colour by composition – a Point and a Colour side by side, which is Inheritance vs Composition at its sharpest.

A Java record is immutable only if its fields are

A record hands you final fields, accessors, equals and hashCode over every component, a toString, and a final class – the right default for a value object. The trap is exactly one thing: the generated constructor does not copy.

// WRONG: looks immutable, is not. The canonical constructor is a plain
// reference assignment, so the caller keeps a live handle on the list they
// passed in and can still append to it. And because the generated hashCode
// walks that list's contents, this record's hash code changes while it sits in
// a HashMap -- the bug from the top of the lesson, in a type that advertises
// immutability.
public record Order(String id, List<LineItem> items) { }

// RIGHT: a compact constructor runs before the fields are assigned, and the
// idiom is to reassign the parameter rather than write to the field.
public record Order(String id, List<LineItem> items) {
    public Order {
        items = List.copyOf(items);   // copies, rejects nulls, unmodifiable result
    }
}

A record also cannot leave a component out of equals. If one field is a cache or a derived total that must not participate, write the class by hand.

Immutability removes a lock, it does not add one

An immutable object is safe to share across threads with no synchronisation, because there is no write for a reader to race against: a lock you never add rather than a cost you pay. The guarantee underneath is worth stating. If every field is final and the constructor does not publish this, any thread that obtains a reference to the fully constructed object sees those fields correctly initialised, with no synchronisation on either side. Drop final and another thread can legally observe a reference to an object whose fields still hold their default values. The second clause matters as much: stashing this in a static map or a listener registry inside the constructor publishes the object early and forfeits the guarantee. Concurrency covers the objects that stay mutable.

The cost is allocation, and it is real

money = money.plus(delta) in a loop of a million iterations allocates a million Money objects. A generational collector handles short-lived garbage cheaply, but cheaply is not freely, and on a hot write path – running totals in a matching engine, a recalculation of a large sheet – it is measurable. Two escapes. A mutable accumulator confined to one scope: sum a plain long of minor units and build one Money at the end, safe precisely because the mutable thing never leaves the method, and the same trade as StringBuilder versus += on strings. Or a persistent data structure, sharing its unchanged interior between versions so the next “copy” costs O(log n) instead of O(n) – what Clojure’s vectors do, and what a rope does for an editor buffer. Where construction is many-step, a Builder mutates privately and freezes at build(). Immutability is not free, just usually worth it.

compareTo returning 0 must mean equals

TreeSet and TreeMap decide membership with compareTo; HashSet and HashMap decide it with equals and hashCode. When the two disagree, you own two collections that disagree about whether an element is present. The canonical case ships with the JDK: new BigDecimal("1.0").equals(new BigDecimal("1.00")) is false, because scale is part of BigDecimal equality, while compareTo on that pair returns 0 – so a HashSet holds both and a TreeSet holds one. Comparable’s contract calls consistency with equals “strongly recommended” rather than required, which is the polite way of saying the collections will not stop you – and it is one more reason a long of minor units beats BigDecimal as a money key.


Value objects vs entities

Which of the two you are modelling comes before every rule above, because it changes what equality means:

Kind Intent Equality Tell
Value object Describe a quantity or appearance – Money, Point, CellStyle All fields equal means equal, so two instances are interchangeable Swapping it for an equal copy changes nothing anyone could observe
Entity Track one real thing through time – Order, User, Account Equal when the id matches, whatever the other fields currently say Two instances with identical fields are still two different things

The overlap worth naming is that the same class can be either. A Seat is a value object in a seat-map renderer and an entity in a booking system, where 4C has a reservation history and two bookings for it are a conflict rather than a duplicate. So decide it per problem: would you ever need to tell two of them apart after confirming every field matches? If yes, it needs an id, and equals compares that id and nothing else.


When to Make It Immutable vs When to Keep It Mutable

Make It Immutable When Keep It Mutable When
It is a map key or a set element It is an entity with a lifecycle – an Order walking through states
It is shared: across threads, through a Flyweight pool, or inside a Memento snapshot It is large and the write path is hot, and each change touches one field
It is a quantity or an appearance – money, coordinates, a date range Callers are meant to see changes through a reference they already hold
It is a Strategy or Specification, so one instance serves everyone Construction is many-step, and a Builder assembles before freezing
Its validity is an invariant across fields, checked once in the constructor It is a buffer or accumulator that never escapes one method

The characteristic failure mode is the class that is immutable everywhere except one field: final fields, no setters, a correct equality trio – and one getter returning the live List, or one Date stored by reference. The class reads as immutable, so the team shares it between threads and keys maps with it, and that one field carries every bug the others prevented. The audit is mechanical: for each field, ask whether its type is immutable. String, long, Instant, LocalDate, an enum and a record of immutables are; Date, ArrayList, HashMap, arrays and anything of yours with a setter are not. Arrays are the sharpest edge, since private final int[] grid is a final reference to a fully writable array.


Interview Questions

  1. “I put an object in a HashMap, changed a field, and now get returns null even though the map still contains the entry. What happened?” – put called hashCode() once and used it to pick a bucket index, and that index is where the entry physically lives; mutating a field hashCode reads changes the return value, so get derives a different index, searches a bucket the entry was never placed in, and finds nothing. Iteration still shows it, because iteration walks the table rather than hashing, and remove cannot reach it either, so it leaks. The fix is not “remove before mutating and re-insert” – it is an immutable key, because the mutation will happen in code that never heard of your map.

  2. “What breaks if you override equals but not hashCode?” – Two objects that are equals keep their distinct identity hash codes, land in different buckets and never meet, so a HashMap lookup with an equal-but-distinct key misses, a HashSet holds duplicates that report equals as true, distinct() stops deduplicating, and a Flyweight pool never hits. Note the asymmetry: return 42 is a legal hashCode, because equal objects do get equal hashes, and it costs only speed – one bucket, O(log n) once Java 8+ treeifies an over-full bin.

  3. “Is a Java record immutable?” – Shallowly yes: final fields, final class, and equals, hashCode and toString over all components. Deeply no, and the gap is one thing: the canonical constructor assigns the reference it was handed, so record Order(String id, List<LineItem> items) lets the caller keep appending to the list they passed in, and since the generated hashCode walks that list, the record’s hash changes under you. Fix it with a compact constructor doing items = List.copyOf(items).

  4. “How do you make a class with a collection field genuinely immutable?” – Three steps, and most candidates name one. Copy in with List.copyOf(items) so the caller’s reference stops being a handle on your state; return something unwritable out, knowing Collections.unmodifiableList is a view whose contents still change if someone holds the backing list while copyOf is a snapshot; and make the element type immutable, because an unmodifiable list of editable LineItems is not an immutable Order.

  5. “When is immutability the wrong choice?” – When identity is the point: an Order moving through states, a Wallet with a running balance and an Elevator all have a lifecycle, so equals compares the id and every other field is expected to change. And when allocation dominates, because a large object on a hot write path pays a full copy per single-field change – money = money.plus(x) a million times is a million objects. The honest answers there are a mutable accumulator confined to one scope, or a persistent structure sharing unchanged interior for O(log n) updates; reaching for either without the reason is over-engineering.


See It in Action

  • Splitwise – Money and a Split are value objects, a Group and a User are entities, and balances are keyed by a pair of user ids
  • Payment Wallet – immutable Transaction records in an append-only ledger, around a mutable Wallet entity
  • Spreadsheet Engine – CellRef as a map key, the mutable-key bug in its natural habitat, plus interned CellStyle values
  • Text Editor – immutable snapshots for undo, and the allocation cost that pushes a real editor towards a rope