00:00

Problem Statement

Input/Output Examples

Visual Explanation

That is why the two methods must always be overridden together, and why hashCode() must use the same fields as equals().

Approaches

Both approaches give identical behaviour. The first writes the methods by hand; the second lets a record generate them.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Both methods do a constant amount of work for a fixed number of fields. With a good hash function, HashSet lookups take O(1) time on average.

Interview Tips and Recommended Approach

  • Override both or neither. Overriding only equals() breaks every hash-based collection.
  • Use the same fields in both methods. A field used in equals() but not in hashCode() is fine; the reverse is a bug.
  • Avoid mutable fields in the hash. Changing a field after inserting the object makes it unreachable in the set.
  • Write the signature equals(Object o). equals(Point p) is an overload, not an override, and is never called by collections.

Recommended Approach: Manual equals() and Objects.hash()

Why: it shows exactly what the contract requires. In new code, a record gives you the same correct methods for free.