CSE Roadmap

Core tier · about 2 hours · 7 parts

Part 4 of 7 · 2 min read

Identity versus equality

Same object, or just the same value?

In Java, == on two object references asks: are these the same object? The method equals asks: are these logically equal? For a Room made twice with the same data, == says false. Whether equals says true depends on how the class defines it.

EJ explains when to override equals. By default, each object equals only itself, and that is right when each instance is unique, such as a thread, or when nobody needs a logical test. Overriding is appropriate for a value class, a class that stands for a value such as a number or a string. A programmer who compares two values with equals wants to know whether they are logically the same, and overriding equals also makes the objects behave well as map keys and set elements.

An override must obey the general contract. Equality must be: - reflexive: an object equals itself; - symmetric: if x equals y, then y equals x; - transitive: if x equals y and y equals z, then x equals z; - consistent: repeated calls give the same answer while the data does not change; - and a non-null object never equals null.

EJ warns that breaking the contract makes programs behave erratically, because collections depend on it.

A second rule from EJ: always override hashCode when overriding equals. Hash-based collections such as HashMap find an object by its hash code first, so two equal objects must give the same hash code.

final class Money {
    private final long cents;

    Money(long cents) { this.cents = cents; }

    @Override
    public boolean equals(Object o) {
        if (o == this) return true;
        if (!(o instanceof Money)) return false;
        return ((Money) o).cents == cents;
    }

    @Override
    public int hashCode() { return Long.hashCode(cents); }
}

Checked by running it: new Money(500).equals(new Money(500)) is true, new Money(500) == new Money(500) is false, and a HashSet holding one Money(500) reports that it contains another Money(500). Without the hashCode override, that last check would usually fail.

A record writes equals, hashCode and toString for you, from its fields. It is the shortest way to make a value class, and Level 0 used it for TimeSlot.

Logical equality

Logical equality means two objects stand for the same value, even if they are different objects in memory.

Example: two Money objects of 500 cents are logically equal and are still two objects.

Check yourself: 1. What does == compare on object references? 2. Why must hashCode change together with equals? 3. Which Java feature writes equals for you?