用java源代码学数据结构<二>: Vector 详解(四)
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;
}
}
个人体会:
1.认清两个重要参数capacity(等价于size、length啥的),capacityIncrement。注意当capacityIncrement<=0时,容器扩大一倍(double),否则容器增加capacityIncrement个大小。(一般都是扩大一倍)
2.最重要的操作就是数组的复制,最基本函数System.arraycopy(elementData, index + 1, elementData, index, j)(这个函数在System类中只有定义,具体的实现在JVM中,大家可以自行查找资料)。不要管他的内部实现,面向对象嘛。然后注意一些参数变量的改变
3.迭代器类其实就是类似于一个代理,使用的都是vector的内部方法
4.vector类时线程安全的,主要靠synchronized (Vector.this) 这个对象锁或其他锁机制,以及检查修改次数modCount来实现。