Iterator II
boolean hasNext();
T next();
Peek Iterator
support peek() operation and return next() value but doesn't move ptr.
ask for examples
{1, 2, 3, 4}
iterator.peek() 1 iterator.next() 1 iterator.peek() 2 iterator.peek() 2 iterator.next() 2 p = 3
Anaylsis
- when call peek() : return peekElement
- when call next(), return peekElement.
- update peekElement.
- peekElement = iter.next()
public class PeekIterator {
private Iterator<Integer> iter;
Integer peekElement;
Integer calledNext;
public PeekIterator(Iterator<Integer> iter) {
this.iter = iter;
this.peekElement = null;
}
public boolean hasNext() {
return peekElement != null || iter.hasNext();
}
public Integer next() {
if(hasNext()) {
Integer ret = null;
if (peekElement != null) {
ret = peekElement;
peekElement = null;
} else {
ret = iter.next();
peekElement = iter.next();
}
return ret;
}
throw NoSuchElementException();
}
public Integer peek() {
if(hasNext()) {
if(peekElement == null) {
peekElement = iter.next();
}
return peekElement;
}
throw NoSuchElementException();
}
}