Skip to content
Sharp

Collections · interview question

What does the following code snippet print? List<String> items = Arrays.asList("A", "B", "C"); for (String item : items) { if (item.equals("B")) items.remove(item); } System.out.println(items);?

Multiple choiceMediumchapter-4-curatedpremiumcollectionsiteration-and-traversal
java
List<String> items = Arrays.asList("A", "B", "C");
for (String item : items) {
  if (item.equals("B")) items.remove(item);
}
System.out.println(items);
Choose one answer
Answer and explanation

Correct answer

D. ConcurrentModificationException

Why

This code throws a ConcurrentModificationException because the list is modified while being iterated using an enhanced for loop.

Test yourself on Collections

A free test with instant, explained results. No account needed.

Start free test
All Collections questions →