ProgrammingVery hardProduct-company placement · Java

What is printed?

What is printed?
List<String> l = new ArrayList<>(List.of("a", "b", "c"));
ListIterator<String> it = l.listIterator();
while (it.hasNext()) {
    String s = it.next();
    if (s.equals("b")) { it.set("B"); it.add("x"); }
}
System.out.print(l);
  1. A. [a, x, B, c]
  2. B. [a, B, x, c]
  3. C. [a, B, c, x]
  4. D. A ConcurrentModificationException is thrown

Correct answer: B. [a, B, x, c]

set replaces the element last returned by next (b → B); add inserts at the cursor position, i.e. right after it and before c. Changes made through the iterator itself are allowed.

More OOP with C++ and Java questions

Exams that ask this topic