A developer needs to remove elements from an ArrayList<String> while iterating over it. Which approach is safest and avoids ConcurrentModificationException?
Trap 1: for (String s : list) { if (s.equals("x")) list.remove(s); break; }
Still throws ConcurrentModificationException.
Trap 2: for (int i = 0; i < list.size(); i++) { if…
Index shifts and may skip or miss elements.
Trap 3: for (String s : list) { if (s.equals("x")) list.remove(s); }
Throws ConcurrentModificationException.
- A
for (String s : list) { if (s.equals("x")) list.remove(s); break; }
Why wrong: Still throws ConcurrentModificationException.
- B
for (int i = 0; i < list.size(); i++) { if (list.get(i).equals("x")) list.remove(i); }
Why wrong: Index shifts and may skip or miss elements.
- C
Iterator<String> it = list.iterator(); while (it.hasNext()) { if (it.next().equals("x")) it.remove(); }
Correctly uses Iterator.remove().
- D
for (String s : list) { if (s.equals("x")) list.remove(s); }
Why wrong: Throws ConcurrentModificationException.