在看ArrayList的源码的时候,ArrayList中有一个实现了Iterator接口的内部类Itr,在内部类里,有两个elementData变量,一个是内部类的,昨天的是内部类的局部变量,右边的
是ArrayList的全局变量,由于ArrayList的全局变量elementData与内部类中的elementData重名,所以内部类引用外部类的同名变量时,需要在外部类的全局变量前加上
类名.this,即,ArrayList.this.elementData;
同理,内部类的局部方法名与外部类的方法名相同时,也需要在外部类的方法名前加上类名.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();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}