ProgrammingHardTCS NQT · Infosys interview pattern
How many of the following statements about equals() and hashCode() in Java are correct? (i) If a.equals(b) is true, a.hashCode() must equal b.hashCode(). (ii) If a.hashCode() == b.hashCode(), then a.equals(b) must be true. (iii) Overriding equals() without overriding hashCode() can make a HashSet keep two “equal” objects. (iv) Object’s default equals() compares references.
- A. 1
- B. 2
- C. 3
- D. 4
Correct answer: C. 3
(i), (iii) and (iv) are correct. (ii) is false: different objects may collide on the same hash code. (iii) happens because HashSet first looks in the bucket chosen by hashCode, so equal objects with different hash codes land in different buckets.
More OOP with C++ and Java questions
- On a typical 64-bit compiler (8-byte pointers, 4-byte int, natural alignment), what does sizeof(P) print? cpp class P { int id; public…
- What is printed? java class P { static { System.out.print("1"); } { System.out.print("2"); } P() { System.out.print("3"); } } class C…
- What is printed? java class P { P() { show(); } void show() { } } class C extends P { final int a = 5; int b = 7; final String s = "s"…
- What is printed? java // static methods of the main class: static int f() { int x = 1; try { x = 2; throw new IllegalStateException(); }…
- What is printed? java Long l = 127L; Integer i = 127; System.out.print(l.equals(127) + " "); System.out.print(l.equals(127L) + " ")…
- What is printed? java // static methods of the main class: static void f(long x) { System.out.print("long "); } static void f(Integer x) {…