public T next() {
if (hasNext()) {
lastMove = Move.NEXT;// 进行的是后移操作
isRemoveOrSetLegal = true;// 当next()调用了之后,才可以调用remove()或set()
return (T) elementData[nextIndex++];// 注意nextIndex的自增顺序
} else
throw new NoSuchElementException("Illegal call to next(),"
+ "迭代器位于表的最后端");
}
public boolean hasPrevious() {
return (nextIndex > 0) && (nextIndex <= size);
}
public T previous() {
if (hasPrevious()) {
lastMove = Move.PREVIOUS;// 进行的是前移操作
isRemoveOrSetLegal = true;
return (T) elementData[--nextIndex];// 注意nextIndex的自减顺序
} else
throw new NoSuchElementException("Illegal call to previous()"
+ "iterator is before beginning of list");
}
// 返回当前元素的索引
public int nextIndex() {
int result;
if (hasNext())
result = nextIndex + 1;
else
result = size;// 迭代超出顺序表的最后一个元素时返回顺序表中元素的个数
return result;
}
// 返回当前元素的前一个元素的索引
public int previousIndex() {
int result;
if (hasPrevious())
result = nextIndex - 1;
else
result = -1;// 迭代在顺序表的第一个元素时,返回-1
return result;
}
// 删除当前迭代的元素
public void remove() {
if (isRemoveOrSetLegal) {
isRemoveOrSetLegal = false;
if (lastMove.equals(Move.NEXT)) {
// next()被调用,但add() remove()没有被调用
SequenceListWithIterator.this.delete(nextIndex - 1);
nextIndex--;
} else if (lastMove.equals(Move.PREVIOUS)) {
SequenceListWithIterator.this.delete(nextIndex);
}
} else
throw new IllegalStateException(
"Illegal call to remove();"
+ "next() or previous() was not called, OR add() or remove() called since then");
}
// 更改当前迭代的元素
public void set(T e) {
if (isRemoveOrSetLegal) {
if (lastMove.equals(Move.NEXT))
// 使用内部类机制,内部类里面可以可以直接访问它外部类的底层数据
elementData[nextIndex - 1] = e;
else {
assert lastMove.equals(Move.PREVIOUS);
elementData[nextIndex] = e;
}
} else {
throw new IllegalStateException(
"Illegal call to set();"
+ "next() or previous() was not called, OR add() or remove() called since then");
}
}