public class PeekingIterator<E>
extends java.lang.Object
implements java.util.Iterator<E>
The decorator supports the removal operation, but an IllegalStateException
will be thrown if remove()
is called directly after a call to
peek()
or element()
.
Modifier and Type | Field and Description |
---|---|
private boolean |
exhausted
Indicates that the decorated iterator is exhausted.
|
private java.util.Iterator<? extends E> |
iterator
The iterator being decorated.
|
private E |
slot
The current slot for lookahead.
|
private boolean |
slotFilled
Indicates if the lookahead slot is filled.
|
Constructor and Description |
---|
PeekingIterator(java.util.Iterator<? extends E> iterator)
Constructor.
|
Modifier and Type | Method and Description |
---|---|
E |
element()
Returns the next element in iteration without advancing the underlying iterator.
|
private void |
fill() |
boolean |
hasNext() |
E |
next() |
E |
peek()
Returns the next element in iteration without advancing the underlying iterator.
|
static <E> PeekingIterator<E> |
peekingIterator(java.util.Iterator<? extends E> iterator)
Decorates the specified iterator to support one-element lookahead.
|
void |
remove() |
private final java.util.Iterator<? extends E> iterator
private boolean exhausted
private boolean slotFilled
private E slot
public PeekingIterator(java.util.Iterator<? extends E> iterator)
iterator
- the iterator to decoratepublic static <E> PeekingIterator<E> peekingIterator(java.util.Iterator<? extends E> iterator)
If the iterator is already a PeekingIterator
it is returned directly.
E
- the element typeiterator
- the iterator to decoratejava.lang.NullPointerException
- if the iterator is nullprivate void fill()
public boolean hasNext()
hasNext
in interface java.util.Iterator<E>
public E peek()
Note: this method does not throw a NoSuchElementException
if the iterator
is already exhausted. If you want such a behavior, use element()
instead.
The rationale behind this is to follow the Queue
interface
which uses the same terminology.
public E element()
java.util.NoSuchElementException
- if the iterator is already exhausted according to hasNext()