Removing elements using an iterator

suggest change

The Iterator.remove() method is an optional method that removes the element returned by the previous call to Iterator.next(). For example, the following code populates a list of strings and then removes all of the empty strings.

List<String> names = new ArrayList<>();
names.add("name 1");
names.add("name 2");
names.add("");
names.add("name 3");
names.add("");
System.out.println("Old Size : " + names.size());
Iterator<String> it = names.iterator();
while (it.hasNext()) {
  String el = it.next();
  if (el.equals("")) {
    it.remove();
  }
}
System.out.println("New Size : " + names.size());

Output :

Old Size : 5
New Size : 3

Note that is the code above is the safe way to remove elements while iterating a typical collection. If instead, you attempt to do remove elements from a collection like this:

for (String el: names) {
    if (el.equals("")) {
        names.remove(el); // WRONG!
    }
}

a typical collection (such as ArrayList) which provides iterators with fail fast iterator semantics will throw a ConcurrentModificationException.

The remove() method can only called (once) following a next() call. If it is called before calling next() or if it is called twice following a next() call, then the remove() call will throw an IllegalStateException.

The remove operation is described as an optional operation; i.e. not all iterators will allow it. Examples where it is not supported include iterators for immutable collections, read-only views of collections, or fixed sized collections. If remove() is called when the iterator does not support removal, it will throw an UnsupportedOperationException.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents