Question Bank

Java OOP Fundamentals

Difficulty: Medium

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
/

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.