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); }
}
// in main:
Set<Point> set = new HashSet<>();
set.add(new Point(1, 2));
set.add(new Point(1, 2));
System.out.println(set.size());
  1. A. 2
  2. B. 1
  3. C. 0
  4. D. It depends on JVM hash randomization

Correct answer: B. 1

With a consistent hashCode() override matching equals(), both Point(1,2) instances hash to the same bucket and compare equal via equals(), so HashSet recognises the second add as a duplicate: size stays 1.

More OOP with C++ and Java questions

Exams that ask this topic