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());
}
}- A. 1
- B. 2
- C. Compile-time error: Point must implement Comparable to be used in a HashSet
- 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
- What is printed? java public class Main { public static void main(String[] args) { String a = "hello"; String b = "hello"; String c = new…
- What is printed? java public class Main { public static void main(String[] args) { String a = "hello"; String c = new…
- What is printed? java import java.util.; public class Main { public static void main(String[] args) { List<Integer> nums =…
- What is printed? java public class Main { static void risky(int x) throws Exception { if (x < 0) throw new Exception("neg")…
- What is printed? java public class Main { static String f(int x) { try { if (x == 0) throw new ArithmeticException("div0"); return "ok" +…
- What is printed? java class LowBalanceException extends Exception { LowBalanceException(String m) { super(m); } } class Account { double…