用java源代码学数据结构<二>: Vector 详解(四)

2014-11-24 08:49:24 · 作者: · 浏览: 2
n new ListItr(index);//ListItr类在后面 } public synchronized ListIterator listIterator() { return new ListItr(0); } public synchronized Iterator iterator() { return new Itr();//在后面 } //将迭代器类定义到Vector类的里面,这样迭代器就可以访问vector类的内部变量 private class Itr implements Iterator { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such //用于检查线程是否同步,如果线程不同步,它们两个的值不一样 int expectedModCount = modCount; public boolean hasNext() { // Racy but within spec, since modifications are checked // within or after synchronization in next/previous return cursor != elementCount; } public E next() { synchronized (Vector.this) { //检查线程安全 checkForComodification(); int i = cursor; if (i >= elementCount) throw new NoSuchElementException(); //cursor保存下次要访问的位置 cursor = i + 1; //将最后依次访问的地址赋给lastRet(用于恢复) return elementData(lastRet = i); } } public void remove() { if (lastRet == -1) throw new IllegalStateException(); synchronized (Vector.this) { checkForComodification(); //实质是调用vector自己的remove方法 Vector.this.remove(lastRet); expectedModCount = modCount; } cursor = lastRet; lastRet = -1; } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } //ListItr和Itr很像,基本上都是调用vector的方法 final class ListItr extends Itr implements ListIterator
{ ListItr(int index) { super(); cursor = index; } public boolean hasPrevious() { return cursor != 0;//第二个元素之后的元素都有previous } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } public E previous() { synchronized (Vector.this) { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); cursor = i; return elementData(lastRet = i); } } public void set(E e) { if (lastRet == -1) throw new IllegalStateException(); synchronized (Vector.this) { checkForComodification(); Vector.this.set(lastRet, e); } } public void add(E e) { int i = cursor; synchronized (Vector.this) { checkForComodification(); Vector.this.add(i, e); expectedModCount = modCount; } cursor = i + 1; lastRet = -1; } }