Video in progress
What are the ways to safely remove elements while iterating over a list?
Iterator.remove(), Collection.removeIf(...), or a plain for loop with a reverse index. In new code the cleanest option is removeIf, which shifts elements in a single pass in ArrayList.
📖 Answer
All three approaches work correctly:
// 1. removeIf: short and fast
orders.removeIf(o -> o.status() == Status.CANCELLED);
// 2. Iterator: when you need complex logic before removing
Iterator<Order> it = orders.iterator();
while (it.hasNext()) {
Order o = it.next();
if (o.isExpired()) {
audit.log(o);
it.remove();
}
}
// 3. Reverse index: shifting doesn't affect the indexes still to be visited
for (int i = orders.size() - 1; i >= 0; i--) {
if (orders.get(i).total() == 0) orders.remove(i);
}
If you call remove(i) in a forward for (int i = 0; ...) loop, no exception is thrown, but the element right after the removed one is skipped without being checked. This kind of bug stays silent, and that is exactly what makes it the most dangerous.
On performance: in an ArrayList, it.remove() inside a loop shifts the tail every time, which is O(n²) in the worst case. removeIf is O(n).
Sign up to mark studied questions and save your progress.