Collection Iterator

来源:互联网 发布:html5 360全景源码 编辑:程序博客网 时间:2024/06/05 12:48
// Collection is an interfacepublic interface Collection<E> {    boolean add(E element);    Iterator<E> iterator();    ...  }public interface Iterator<E> {    E next();    boolean hasNext();    void remove();}


public class MergeIterator {Iterator<Integer> left;Iterator<Integer> right;int lastLeft;int lastRight;boolean leftNotUsed;public MergeIterator (Iterator<Integer> left, Iterator<Integer> right) {this.left = left;this.right = right;if (left.hasNext()) {lastLeft = left.next();leftNotUsed = true;} else if (right.hasNext()) {lastRight = right.next();leftNotUsed = false;} }public boolean hasNext() {return left.hasNext() | right.hasNext();}public int next() throws Exception {if (!left.hasNext() && !right.hasNext()) {throw new Exception(" ");}if (left.hasNext() && !right.hasNext()) {if (leftNotUsed) {leftNotUsed = false;return lastLeft;}return left.next();}if (!left.hasNext() && right.hasNext()) {if (leftNotUsed) {leftNotUsed = false;return lastLeft;}return right.next();}if (leftNotUsed) {lastRight = right.next();if (lastLeft < lastRight) {leftNotUsed = false;return lastLeft;} else {return lastRight;}} else {lastLeft = left.next();if (lastRight < lastLeft) {leftNotUsed = true;return lastRight;} else {leftNotUsed = false;return lastLeft;}}}}


0 0
原创粉丝点击