Iterator and safe removal
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Removing items while you loop is where most list bugs live. An Iterator can remove the item it just gave you, safely. Calling list.remove(...) behind its back makes the next step fail with ConcurrentModificationException, and removeIf does the whole job in one line.
What you will learn
- Walk a list with an Iterator using hasNext, next and remove
- Explain why list.remove inside a loop throws ConcurrentModificationException
- Spot the skipped item when a forward index loop removes
- Remove items safely with Iterator.remove, removeIf or a backwards loop
Topics in this lesson
- What an Iterator is
- Removing inside a loop goes wrong
- The index loop skips items
- Safe ways to remove
- Removing objects: removeIf or an Iterator
Key points
- An
Iteratorwalks a list withhasNext(),next()andremove(); a for-each loop uses one behind the scenes. - Changing the list directly inside a loop throws
ConcurrentModificationException; a forward index loop that removes skips the next item. - Remove with
iterator.remove(),removeIf(...)or a backwards index loop. - Call
next()beforeremove(), and checkhasNext()beforenext().
Interview questions this lesson answers
- What is an Iterator?
- Why do you get
ConcurrentModificationExceptionwhen you remove from a list inside a for-each loop? - How do you remove items safely while looping?
- Does ConcurrentModificationException mean you have a threading problem?
- Follow-up: does removing inside a for-each loop always throw?
- What is the difference between
iterator.remove()andlist.remove(x)inside a loop? - What does
removeIfdo and what does it return?
Sign in to continue this lesson
Create an account to read every lesson, practise with the exercises and keep track of your progress.