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
List<String> items = Arrays.asList("A", "B", "C");
for (String item : items) {
if (item.equals("B")) items.remove(item);
}
System.out.println(items);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.
More Collections questions
- Given a List<String> catalog, which method call on an Iterator<String> allows safe removal of an item during iteration?
- If you need to ensure that elements are processed in the exact order they are added but also need occasional access to…
- Given an e-commerce application that requires frequent updates and lookups of product prices, which collection would…
- Which operation is most efficient for an ArrayList?
- What will happen if you try to access an index in an ArrayList that is out of bounds?
- You need to store product IDs and ensure no duplicates, with the ability to retrieve them in sorted order. Which…