ProgrammingHardProduct-company placement · Java
A class overrides equals correctly, but its hashCode() returns 42 for every object. What happens when many such objects are stored in a HashMap?
- A. get() may return the wrong value for some keys
- B. The HashMap throws an exception for duplicate hash codes
- C. Lookups still give correct results, but every key lands in the same bucket, so performance degrades
- D. Only the first object is stored; the rest replace it
Correct answer: C. Lookups still give correct results, but every key lands in the same bucket, so performance degrades
A constant hashCode obeys the contract (equal objects have equal hash codes), so correctness is preserved; equals still separates the keys. All entries collide, turning O(1) lookups into list or tree scans.
More OOP with C++ and Java questions
- What happens? java class P { int v; P(int v) { this.v = v; } } // in main: Set<P> s = new TreeSet<>(); s.add(new P(1)); s.add(new P(2))…
- Which constructors cause compile-time errors? java class F { final int x; F() { } // constructor 1 F(int v) { x = v; x = v + 1; } //…
- What is printed? java Map<String, Integer> m = new HashMap<>(); m.compute("a", (k, v) -> v == null ? 1 : v + 1); m.compute("a", (k, v) ->…
- What is printed? java Map<String, String> h = new HashMap<>(); h.put("k", null); System.out.print(h.size() + " "); Map<String, String> c =…
- What is printed? java List<Integer> e = Collections.emptyList(); System.out.print(e.size() + " "); e.add(1);
- What is printed? java System.out.print(String.valueOf((Object) null) + " "); System.out.print(String.valueOf(null));