Peeking Iterator

  • medium
  • tag: iterator, design pattern
  • similar: iterator题目

如同Guava, 加入一个peek()到iterator里面, 这样可以避免next总是指向下一个了.

思路

  • 和read4line类似, 只要每次next的时候都保存下一个, 然后输出cache的next.
  • 这里要熟悉一下iterator, 以及它的methods. 同时注意到,这就是OOP里面的iterator/decorator pattern. 参见书影博客

  • 同时参考一下Guava的peekingIterator的实现, link

idea

  • 看看怎么实现cache?
  • 代码如下
public class PeekingIterator implements Iterator<Integer> {
  private Integer next = null;
  private Iterator<Integer> iter;

  public PeekingIterator(Iterator<Integer> iterator) {
    iter = iterator;
    if (iter.hasNext()) {
      next = iter.next();
    }
  }

  public Integer peek() {
    return next;
  }

  @Override public boolean hasNext() {
    return next != null;
  }

  @Override public Integer next() {
    int res = next;
    if (iter.hasNext()) {
      next = iter.next();
    }
    else {
      next = null;
    }
    return res;
  }

  public static void main(String[] args) {
    Integer[] A = new Integer[]{3,2,5};
    //http://stackoverflow.com/questions/2607289/converting-array-to-list-in-java
    List<Integer> list = Arrays.asList(A);
    Iterator<Integer> itr = list.iterator();
    PeekingIterator pi = new PeekingIterator(itr);

    System.out.println(pi.peek());
    System.out.println(pi.next());
    System.out.println(pi.peek());
    System.out.println(pi.peek());
  }
}