ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Point {
    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 x == p.x && y == p.y;
    }
    @Override
    public int hashCode() { return Objects.hash(x, y); }
}
public class Main {
    public static void main(String[] args) {
        Set<Point> set = new HashSet<>();
        set.add(new Point(1, 2));
        set.add(new Point(1, 2));
        System.out.print(set.size());
    }
}
  1. A. It depends on JVM implementation
  2. B. Compilation error
  3. C. 1
  4. D. 2

Correct answer: C. 1

Now both equals() and hashCode() are consistently overridden based on x and y: the two Points have equal hash codes and compare equal, so HashSet correctly recognizes the second add as a duplicate — size stays 1.

More OOP with C++ and Java questions

Exams that ask this topic