定义:迭代器模式提供一种方法顺序访问一个聚合对象的各个元素,而又不暴露其内部的表示。
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
public interface Iterable<T> {
Iterator<T> iterator();
}
下面是AbstractList对Iterable实现
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { // List接口实现了Collection<E>, Iterable<E>
protected AbstractList() {
}
... //其它代码省略
public Iterator<E> iterator() {
return new Itr(); // 这里返回一个迭代器
}
private class Itr implements Iterator<E> { // 内部类Itr实现迭代器
int cursor = 0;
int lastRet = -1;
int expectedModCount = modCount;
public boolean hasNext() { // 实现hasNext方法
return cursor != size();
}
public E next() { // 实现next方法
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public void remove() { // 实现remove方法
if (lastRet == -1)
throw new IllegalStateException();
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();
}
}
}
本文详细解析了Java集合框架中的迭代器实现原理,包括Iterable接口和Iterator接口的使用,以及如何通过AbstractList类实现迭代器接口。重点介绍了如何在不暴露内部结构的情况下遍历集合元素,并通过多态机制提高代码的复用性和灵活性。

被折叠的 条评论
为什么被折叠?



