ProgrammingVery hardProduct company OA
What is printed?
What is printed?
class Node {
int val;
Node(int v) { val = v; }
@Override
public int hashCode() { return 42; }
@Override
public boolean equals(Object o) {
return o instanceof Node && ((Node) o).val == val;
}
}
// in main:
Set<Node> set = new HashSet<>();
for (int i = 0; i < 1000; i++) set.add(new Node(i));
System.out.println(set.size());- A. 1000
- B. 1
- C. 0
- D. It never terminates
Correct answer: A. 1000
Every Node gets the same hashCode (42) — a deliberately bad but legal hash function — so all 1000 objects collide into one bucket. HashSet still works correctly (just slowly, degrading to a linear scan with equals()), and since each val 0..999 is distinct, equals() correctly treats all 1000 as unique: size 1000.
More OOP with C++ and Java questions
- What is printed? java // in main: String a = "Hello".toLowerCase(); String b = "hello"; System.out.println((a == b) + " " + a.equals(b));
- Which overridden equals() below is actually BROKEN with respect to the symmetry requirement of the equals contract? java class A { int x…
- What is printed? java class Version { int major, minor; Version(int ma, int mi) { major = ma; minor = mi; } @Override public boolean…
- What is printed? java public class Main { static int f() { int x = 10; try { return x; } finally { x = 20; } } public static void…
- What is printed? java public class Main { public static void main(String[] a) { try { System.out.print("A"); throw new RuntimeException()…
- Does this compile? java class MyException extends Exception {} class Demo { void risky() throws MyException { throw new MyException(); }…