Iterator代表接口 it表示接口类型的引用,即其子类对象名,al.iterator(),ArrayList中的方法被其对象调用,方法的功能是返回一个Iterator接口类型的子类
对象,并由其子类对象调用其中实现Iterator接口的方法(hasNext(),next(),remove()方法),即内部类Itr实现了外部类或接口并私有化,并通过对外的方法访问,保证了程序的封装和多态。下面是源代码,看一下
interface Iterator
{
public abstract boolean hasNext();
public abstract E next();
public abstract void remove();
public abstract void checkForComodification();
}
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
int cursor = 0;
int lastRet = -1;
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size();
}
public E next() {
checkForComodification();
try {
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
|