ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
class Key {
final String name;
Key(String n) { name = n; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return name.equals(((Key) o).name);
}
@Override
public int hashCode() { return name.hashCode(); }
}
public class Main {
public static void main(String[] args) {
Map<Key, Integer> map = new HashMap<>();
map.put(new Key("x"), 1);
map.put(new Key("x"), 2);
System.out.print(map.size() + " " + map.get(new Key("x")));
}
}- A. 1 1
- B. 1 2
- C. 2 1
- D. 2 2
Correct answer: B. 1 2
Both Key("x") instances are equal and have the same hashCode, so the second put() replaces the value for the existing key rather than adding a new entry: size stays 1, and the stored value becomes 2 (the later put wins). A fresh Key("x") lookup also matches via equals/hashCode, returning 2.
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"…
- What is printed? java class Base { Base() { System.out.print("Base "); } protected Base(int x) { System.out.print("Base(int) "); } } class…
- What is printed? java class Vehicle { void start() { System.out.print("Vehicle-start "); } } class ElectricCar extends Vehicle { @Override…
- What is printed? cpp struct Base { Base() { cout << "Base "; } }; struct Mixin1 { Mixin1() { cout << "Mixin1 "; } }; struct Mixin2 {…
- What is printed? java class Base { public String describe() { return "Base"; } } interface Describable { String describe(); } class Sub…
- What is printed? java class Resource { String name; Resource(String n) { name = n; System.out.print("open:" + n + " "); } void use() {…