Coding problem · Easy · Language Idioms

equals() and hashCode() Done Right

Easy Language practicals Most askedSeen at Amazon, Oracle, Microsoft, Bloomberg

Implement a final class Point (not a record) with two int fields x and y:

  • equals — two points are equal when both coordinates match; must handle null and other types;
  • hashCode — consistent with equals;
  • toString — "Point(1, 2)".

The tests rely on HashSet de-duplication and HashMap lookups with different but equal instances — the classic interview probe of the equals/hashCode contract.

Hints

Hint 1

Objects.hash(x, y) is a correct (if slightly slow) hashCode.

Hint 2

Use getClass() != o.getClass() or instanceof with a final class.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(1) · Space O(1)

Hash-based collections first use hashCode to pick a bucket, then equals inside it. If equal objects had different hash codes, HashSet would store duplicates and HashMap.get would miss. The contract: equal objects must have equal hash codes (unequal objects may collide). Using final fields keeps the hash stable — mutating a key after inserting it into a HashMap makes it unreachable.

In modern Java, a record Point(int x, int y) generates all three methods — say so, then show you understand what it generates.

Reference solution

final class Point {
    private final int x;
    private final int y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Point other)) return false;
        return x == other.x && y == other.y;
    }

    @Override
    public int hashCode() {
        return 31 * x + y;
    }

    @Override
    public String toString() {
        return "Point(" + x + ", " + y + ")";
    }
}

Common mistakes

  • Overriding equals(Point p) (an overload!) instead of equals(Object o).
  • Overriding equals without hashCode.
  • Mutable fields in a key object.

Follow-up questions

  • Why should equals be symmetric with subclasses? (Liskov / getClass vs instanceof)
  • Implement Comparable<Point> consistently with equals.