Question Bank
/

Java OOP Fundamentals

Java OOP Fundamentals

Mid-tier Java drills on interfaces vs abstract classes, the equals / hashCode contract, generics type erasure, and Comparable / Comparator. Concrete code stems you can compile.

Question Bank
Medium
Java
4 questions
oop
java-interfaces
java-generics
interview-prep

999 views

29

Find the bug in Point.equals. Why does a HashSet<Point> end up containing both new Point(1, 2) instances?

Examples

Example 1:

Input: HashSet<Point> with two new Point(1, 2) instances
Output (buggy version, equals overridden but hashCode not): set.size() == 2
Output (fixed version with Objects.hash(x, y)): set.size() == 1
Explanation: The contract is a.equals(b) implies a.hashCode() == b.hashCode(). The default hashCode is identity-based, so two distinct instances land in different buckets and the HashSet stores both.
import java.util.HashSet;
import java.util.Objects;

class Point {
    final int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }
    @Override public boolean equals(Object o) {
        if (!(o instanceof Point)) return false;
        Point p = (Point) o;
        return p.x == x && p.y == y;
    }
    // TODO: override hashCode so a.equals(b) implies a.hashCode() == b.hashCode().
}

public class Main {
    public static void main(String[] args) {
        HashSet<Point> set = new HashSet<>();
        set.add(new Point(1, 2));
        set.add(new Point(1, 2));
        System.out.println(set.size());
    }
}