Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation – it essentially peek() at the element that will be returned by the next call to next().
publicPeekingIterator(Iterator<T> iterator){ // initialize any member here. iter = iterator; next = iter.hasNext() ? iter.next() : null; }
// Returns the next element in the iteration without advancing the iterator. public T peek(){ return next; }
// hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. @Override public T next(){ int result = next; next = iter.hasNext() ? iter.next() : null; return result; }
@Override publicbooleanhasNext(){ return next != null || iter.hasNext(); } }