ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
interface Repository<T> {
    void save(T item);
    T find(int id);
}
class UserRepository implements Repository<String> {
    Map<Integer, String> store = new HashMap<>();
    public void save(String item) { store.put(store.size(), item); }
    public String find(int id) { return store.get(id); }
}
// in main:
Repository<String> repo = new UserRepository();
repo.save("alice");
repo.save("bob");
System.out.println(repo.find(1));
  1. A. bob
  2. B. alice
  3. C. null
  4. D. Compilation error: Repository<String> cannot hold a UserRepository

Correct answer: A. bob

save("alice") stores at key 0 (store.size() was 0 at that point); save("bob") stores at key 1 (store.size() was then 1); find(1) retrieves the value at key 1, "bob".

More OOP with C++ and Java questions

Exams that ask this topic