下面是ArrayList的迭代器源码,我注意到这两行
Object[] elementData = ArrayList.this.elementData;
expectedModCount = modCount;
第一行用的是标准的内部类访问外部类成员变量的方法,为何第二行则是直接用变量名,没有加“ArrayList.this”?
为何modCount不需要加“ArrayList.this”?不加也能成?
private class Itr implements Iterator<E> {
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() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
因为
Itr
是ArrayList
的内部类,内部类想要访问外部类的非静态成员,最保险的写法是外部类.this.成员名
,这样写能够保证当内部类哪天出现了一个同名的成员时,不会被弄混。