ProgrammingModerateProduct-company placement · Java

What is printed?

What is printed?
Map<String, Integer> m = new TreeMap<>(Map.of("a", 1, "b", 2));
for (Map.Entry<String, Integer> e : m.entrySet()) e.setValue(e.getValue() * 10);
System.out.print(m);
  1. A. {a=1, b=2}
  2. B. {a=10, b=20}
  3. C. A ConcurrentModificationException is thrown
  4. D. An UnsupportedOperationException is thrown

Correct answer: B. {a=10, b=20}

Map.Entry.setValue on an entry obtained from a mutable map's entrySet writes through to the map, and it is not a structural modification, so iteration continues normally.

More OOP with C++ and Java questions

Exams that ask this topic