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());
}
}- A. 3
- B. 1
- C. 0
- 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
- What is printed? java class Base { static int shared = 0; int id; Base() { id = ++shared; } } class Sub extends Base { } public class Main…
- What is printed? java class Base { Base(String tag) { System.out.print("Base:" + tag + " "); } } class Sub extends Base { Sub() {…
- What is printed? cpp struct Shape { virtual double area() const = 0; bool operator<(const Shape &o) const { return area() < o.area(); } }…
- What is printed? java class Matrix { int[][] data; Matrix(int n) { data = new int[n][n]; } @Override public boolean equals(Object o) { if…
- What is printed? java class Vehicle { void honk() { System.out.print("Beep "); } } class Car extends Vehicle { @Override void honk() {…
- What is printed? java List<String> strings = new ArrayList<>(); List<Integer> ints = new ArrayList<>()…