Professional Documents
Culture Documents
Chapter 102: Iterator and Iterable: Section 102.1: Removing Elements Using An Iterator
Chapter 102: Iterator and Iterable: Section 102.1: Removing Elements Using An Iterator
The java.util.Iterator is the standard Java SE interface for object that implement the Iterator design pattern.
The java.lang.Iterable interface is for objects that can provide an iterator.
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:
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.
@Override
public Iterator<Character> iterator() {
return new Iterator<Character>() {
char letter = 'a';
@Override
public boolean hasNext() {
return letter <= 'z';
}
@Override
public Character next() {
return letter++;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Doesn't make sense to remove a letter");
}
};
}
}
To use:
The new Iterator should come with a state pointing to the first item, each call to next updates its state to point to
the next one. The hasNext() checks to see if the iterator is at the end. If the iterator were connected to a modifiable
collection then the iterator's optional remove() method might be implemented to remove the item currently
pointed to from the underlying collection.
// foreach-like loop
for (Integer i: iterable) {
This is much easier and clearer than having a isLastEntry variable or doing calculations with the loop index.