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); }
}
public class Main {
public static void main(String[] args) {
Set<Point> set = new HashSet<>();
set.add(new Point(1, 2));
set.add(new Point(1, 2));
System.out.print(set.size());
}
}- A. It depends on JVM implementation
- B. Compilation error
- C. 1
- D. 2
Correct answer: C. 1
Now both equals() and hashCode() are consistently overridden based on x and y: the two Points have equal hash codes and compare equal, so HashSet correctly recognizes the second add as a duplicate — 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 = new String("hi").intern(); String b = "hi"…
- What is printed? java class Box { int value; Box(int v) { value = v; } } public class Main { public static void main(String[] args) { Box…
- Which statement about overriding equals() correctly describes the contract that must hold?
- What is printed? java class Animal { String name; Animal(String n) { name = n; } @Override public boolean equals(Object o) { if (!(o…
- What is printed? java public class Main { public static void main(String[] args) { Integer a = 127; int b = 127; System.out.print(a == b)…