ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Shape {
    public boolean equals(Object o) {
        return o instanceof Shape;
    }
    public int hashCode() { return 1; }
}
public class Main {
    public static void main(String[] args) {
        java.util.Set<Shape> set = new java.util.HashSet<>();
        set.add(new Shape());
        set.add(new Shape());
        set.add(new Shape());
        System.out.println(set.size());
    }
}
  1. A. 3
  2. B. 1
  3. C. 0
  4. D. Compile-time error: hashCode() cannot return a constant

Correct answer: B. 1

Every Shape has the same hashCode (1), so all three land in the same HashSet bucket, and within that bucket equals() is used to detect duplicates. equals() says any Shape equals any other Shape (instanceof check only), so the second and third adds are recognised as duplicates, leaving the set with just one element.

More OOP with C++ and Java questions

Exams that ask this topic