284. Peeking Iterator

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.