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 x * 31 + y; }
}
public class Main {
    public static void main(String[] args) {
        java.util.Set<Point> set = new java.util.HashSet<>();
        set.add(new Point(1, 2));
        set.add(new Point(1, 2));
        System.out.println(set.size());
    }
}
  1. A. 1
  2. B. 2
  3. C. Compile-time error: Point must implement Comparable to be used in a HashSet
  4. D. 0

Correct answer: A. 1

Both hashCode() and equals() are overridden consistently: equal objects (same x, y) produce the same hash bucket and compare equal, so HashSet correctly recognises the second Point(1, 2) as a duplicate and the set's size stays 1.

More OOP with C++ and Java questions

Exams that ask this topic