Skip to content

equals & hashCode

The Course
•
15 min study

Two references can point to different objects that represent the same value. == compares object identity; equals can express value equality. Hash-based collections introduced tomorrow also need hashCode. Learn the pair together so values behave consistently when stored.

Work through the example

A parent class supplies behavior that another class inherits. Every class here inherits from Java's built-in Object, even without an explicit extends declaration. An Object variable can refer to a Key, a String, or another object; its declared type alone does not tell the compiler which one it holds. Day 3 explores inheritance in more detail. Its default equals uses identity. Our Key instead compares a normalized code. @Override asks the compiler to verify that the method really overrides a parent method. Its parameter must be Object, not Key.

instanceof asks whether a reference is a Key; it is false for null. Only after that check is the (Key) cast safe. A cast changes the compiler's view, not the object. Equal keys must produce equal hash codes; unequal keys may have the same hash code. Reusing the string's hash handles the same normalized value consistently.

Read equals in three steps: reject a non-Key (including null), give the checked reference the narrower Key type, then compare its code with this object's code. key.code is legal even though code is private: code inside Key can read the private fields of another Key instance. The method's parameter stays Object because that is the signature Java's existing equality contract uses.

Value equality should also agree in both directions: if a.equals(b), b.equals(a) should be true. If a equals b and b equals c, a must equal c. An object equals itself, never null, and repeated calls agree while the relevant fields stay unchanged. Compare labels in both directions and with a third matching label when checking your implementation.

A hash code is an integer used to narrow a collection's search for an equal value. Think of it as a shelf number, not a unique ID: different values may share a shelf, so the collection still checks equality. If equal objects report different shelves, lookup can miss them. Changing an equality field after insertion can cause the same problem; this is why the example keeps code final.

Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.

Predict, then run Java
public class Main {
    public static void main(String[] args) {
        Key first = new Key("A");
        Key second = new Key("A");
        System.out.println(first == second);
        System.out.println(first.equals(second));
        System.out.println(first.hashCode() == second.hashCode());
    }
}

final class Key {
    private final String code;

    Key(String code) {
        if (code == null) {
            throw new IllegalArgumentException("code required");
        }
        this.code = code.trim();
    }

    @Override
    public boolean equals(Object other) {
        if (!(other instanceof Key)) {
            return false;
        }
        Key key = (Key) other;
        return code.equals(key.code);
    }

    @Override
    public int hashCode() {
        return code.hashCode();
    }
}
Check your prediction
Text
false
true
true

Compare the behavior

A class name alone does not make values equal. This Token keeps Object's identity behavior. Notice that another reference to the same object is equal while a freshly constructed Token is not. Decide whether identity or value makes sense for your domain before overriding anything. For this week's project a task ID identifies a task; equal titles alone do not.

Trace the changed case Java
public class Main {
    public static void main(String[] args) {
        Token first = new Token();
        Token alias = first;
        System.out.println(first.equals(alias));
        System.out.println(first.equals(new Token()));
        System.out.println(first.equals(null));
    }
}

final class Token {
    // No equality override: each object has its own identity.
}
Check your prediction
Text
true
false
false

Exercise value equality in both directions

A value comparison should be symmetric: if first.equals(second) succeeds, second.equals(first) should succeed too. Include a third matching value to check consistency across several instances, and compare against null and an unrelated String. None of these comparisons should need the caller to cast first.

The normalization decision belongs in construction. If " A " and "A" describe the same key, store the same code in both objects before equality or hashing is requested. If case matters, do not lowercase just because two display labels look similar. Equality should describe a documented identity, not a convenient way to make one test pass.

Tomorrow a hash-based set will use both methods. A matching hash code is necessary for equal values but insufficient to prove equality, since collisions are allowed. Test equal values for equal hashes; never require every unequal value to have a different hash. Keep equality-relevant fields unchanged after storing a key.

Practice independently

Exercise

equals & hashCode: practice

Implement value equality for a Label with one final string field. Two labels with the same exact text are equal; different case stays different. Reject null in the constructor. Print checks for equal labels, different labels, comparison with null, and equal hash codes.

Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        System.out.println("Implement Label and compare values");
    }
}

final class Label {
    private final String text;

    Label(String text) {
        this.text = text;
    }
}
Hint 1: the idea

Use the same field for both equality and hashing. Compare string content with equals.

Hint 2: a first step

Check the other object type before casting, then compare the two text fields.

Show one solution

One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?

Java
public class Main {
    public static void main(String[] args) {
        Label a = new Label("Java");
        Label b = new Label("Java");
        System.out.println(a.equals(b));
        System.out.println(a.equals(new Label("java")));
        System.out.println(a.equals(null));
        System.out.println(a.hashCode() == b.hashCode());
    }
}

final class Label {
    private final String text;

    Label(String text) {
        if (text == null) {
            throw new IllegalArgumentException("text required");
        }
        this.text = text;
    }

    @Override
    public boolean equals(Object other) {
        if (!(other instanceof Label)) {
            return false;
        }
        Label label = (Label) other;
        return text.equals(label.text);
    }

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

Expected output:

Text
true
false
false
true

Change it and test again

Add a second equality-relevant field, such as a language code. Update both methods and test objects that differ in only that field. For a simple two-string hash, 31 * text.hashCode() + language.hashCode() is sufficient; hash values can collide. Never assert that every unequal object has a different hash.

Explain before moving on

Explain the three steps in equals and why equal values must have equal hash codes. Try changing its parameter to Key while keeping @Override: the compiler should reject the annotation because the parameter no longer matches Object's method. Restore it. Day 3 names this distinction “overloading versus overriding”; tomorrow you will use equality in a set.

Was this article helpful?

Your response is saved on this device.