package li.earth.urchin.twic.collections; import java.util.ListIterator; import java.util.NoSuchElementException; public class GeneralBigListIterator implements BigListIterator { private static final boolean FORWARD = true; private static final boolean BACKWARD = false; private final BigList list; private long index; // index of following element private boolean directionSet; private boolean direction; public GeneralBigListIterator(BigList list, long index) { if ((index < 0L) || (index > list.bigSize())) throw new IndexOutOfBoundsException(Long.toString(index)); this.list = list; this.index = index; } public boolean hasNext() { return index < list.bigSize(); } public boolean hasPrevious() { return index > 0; } public long nextBigIndex() { return index; } public int nextIndex() { return AbstractBigList.narrow(nextBigIndex()); } public long previousBigIndex() { return index - 1L; } public int previousIndex() { return AbstractBigList.narrow(previousBigIndex()); } public E next() { if (!hasNext()) throw new NoSuchElementException(); E obj = list.get(index); ++index; directionSet = true; direction = FORWARD; return obj; } public E previous() { if (!hasPrevious()) throw new NoSuchElementException(); E obj = list.get(index - 1L); --index; directionSet = true; direction = BACKWARD; return obj; } public void add(E obj) { list.add(index, obj); ++index; directionSet = false; } public void remove() { if (!directionSet) throw new IllegalStateException(); if (direction == FORWARD) --index; list.remove(index); directionSet = false; } public void set(E obj) { if (!directionSet) throw new IllegalStateException(); long index = this.index; if (direction == FORWARD) --index; list.set(index, obj); } }