本文共 1187 字,大约阅读时间需要 3 分钟。
// Java Iterator interface reference:// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.htmlclass PeekingIterator implements Iterator{ private Integer cache; private boolean hasCache=false; Iterator originIterator; public PeekingIterator(Iterator iterator) { // initialize any member here. originIterator=iterator; } // Returns the next element in the iteration without advancing the iterator. public Integer peek() { if(hasCache) { return cache; } else { hasCache=true; cache=originIterator.next(); return cache; } } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. @Override public Integer next() { if(hasCache) { hasCache=false; return cache; } else { return originIterator.next(); } } @Override public boolean hasNext() { if(hasCache) { return true; } else { return originIterator.hasNext(); } }}
转载地址:http://ncuvb.baihongyu.com/