👉 Short Answer:
It removes the last element returned by
next()from the underlying collection.
🧪 Example:
List<String> list = new ArrayList<>(List.of("A", "B", "C"));
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String val = it.next();
if (val.equals("B")) {
it.remove(); // removes "B" from the list
}
}
System.out.println(list); // Output: [A, C]
💬 What’s going on:
it.next()moves to"B".it.remove()then removes"B"from the actual list.
⚠️ Important Rules for iterator.remove()
❌ 1. You must call next() before remove()
Iterator<String> it = list.iterator();
it.remove(); // ❌ IllegalStateException — no prior call to next()
❌ 2. You can’t call remove() twice in a row without calling next() again
String val = it.next();
it.remove(); // ✅ OK
it.remove(); // ❌ IllegalStateException — must call next() again first
💡 Why use iterator.remove()?
Because it’s the only safe way to remove elements from a collection during iteration.
❌ This will fail:
for (String s : list) {
if (s.equals("B")) {
list.remove(s); // ❌ ConcurrentModificationException
}
}
✅ This is safe:
Iterator<String> it = list.iterator();
while (it.hasNext()) {
if (it.next().equals("B")) {
it.remove(); // ✅ Safe and correct
}
}