The original iterator class is brought next () and Hasnext (), but now with Peek () will be called Once Iterator.next (), and then the order of iterator chaos.
So once the peek is over we need to record this by the next () popup element, if you call next to return this temporary element, and then call peek return this element, and then call Hasnext to return whether peek or hasnext () itself
1 classPeekingiteratorImplementsIterator<integer> {2 PrivateIterator<integer>it;3 PrivateInteger Next;4 Private Booleanispeeked;5 6 PublicPeekingiterator (iterator<integer>iterator) {7 //Initialize any member here.8it =iterator;9ispeeked =false;Ten } One A //Returns the next element in the iteration without advancing the iterator. - PublicInteger Peek () { - if(ispeeked) { the returnNext; -}Else { -ispeeked =true; -Next =It.next (); + returnNext; - } + } A at //Hasnext () and next () should behave the same as in the Iterator interface. - //Override them if needed. - @Override - PublicInteger Next () { - Integer Res; - if(ispeeked) { inres =Next; -}Else { tores =It.next (); + } -ispeeked =false; the returnRes; * } $ Panax Notoginseng @Override - Public BooleanHasnext () { the returnIspeeked?true: It.hasnext (); + } A}
Bug Record:
Peek () itself is also to check whether it has been peek, or will continue to look back, will be missing elements
284. Peeking Iterator