Java Iterator remove() Method
Example
Remove the first item of a list with an iterator:
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
Iterator<String> it = cars.iterator();
it.next();
it.remove();
System.out.println(cars);
}
}
Definition and Usage
The remove() method removes the last item that next() returned. The item is removed from the collection that the iterator loops through.
It is the safe way to remove items while you loop through a collection. Call next() before each call to remove(), or the method throws an IllegalStateException.
Tip: The Java Iterator Tutorial shows how to remove items inside a loop.
Syntax
public void remove()
Parameter Values
None.
Technical Details
| Returns: | No return value. |
|---|---|
| Throws: | IllegalStateException - if next() has not been called yet, or if remove() was already called after the last call to next(). |
Related Pages
❮ Iterator Methods