Iterator (迭代器)
正是由于每一个容器都有取出元素的功能,这些功能定义都一样,所以对共性的取出功能进行了抽取,从而出现了Iterator接口。由于每一个容器的数据结构不一样,所以具体的实现方式也不同,每一个容器都在其内部对该接口以内部类的形式进行了实现。
【源码解析1】
public interface Iterator<E> {
//是否有下一个元素
boolean hasNext();
//下一个元素
E next();
//从迭代器指向的集合中删除迭代器返回的最后一个元素
default void remove() {
throw new UnsupportedOperationException("remove");
}
//遍历所有元素
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
}
Iterable
Iterable表示可迭代的,一般实现了这个接口的类表示是可以获取迭代器对象进行迭代的。
一个接口方法iterator():用来返回迭代器对象。
JDK 1.8 时,Iterable 接口中新增了 forEach 方法。
【源码解析2】
public interface Iterable<T> {
Iterator<T> iterator();
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
...
}
Collection
Collection 继承了 Iterable 接口,Collection 又是 Set、List、Queue 的父接口,所以 Set、List、Queue 的实现类可以重写此方法。
【源码解析3】
public interface Collection<E> extends Iterable<E> {
...
Iterator<E> iterator();
...
ArrayList 中有关迭代器的原理
对于我们日常使用的集合类如ArrayList,它的继承关系让它可以得到iterator()方法。
下面我们来分析一下。
前面了解到 Iterable 接口中有一个接口方法 iterator()。
①首先 Collection 接口重写了 Iterable 接口中的 iterator() 方法。
②然后 AbstractCollection 抽象类又重写了 Collection 接口中的 iterator() 方法。
③再是 AbstractList 抽象类重写了 AbstractCollection 抽象类中的 iterator() 方法。
④最后 ArrayList 中重写了 AbstractList 中的 iterator()方法,并返回一个内部类对象Itr。
我们可以画一个流程图来分析一下。
我们看一下 Itr 这个内部类的实现源码,可以看到是对迭代器接口 Iterator 的实现。
【源码解析4】
private class Itr implements Iterator<E> {
int cursor; // 下一个要返回元素的索引
int lastRet = -1; // 上一个已经返回元素的索引; -1 if no such
int expectedModCount = modCount; // modCount用于记录 ArrayList 对象被修改的次数
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
// 获取 ArrayList 对象的内部数组
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();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
总结:所以继承了Collection接口,并实现了iterator()方法的所有集合类,都可以使用迭代器进行元素的遍历。
LinkedList 中有关迭代器的原理
如果我们仔细研究 LinkedList 的源码就会发现,LinkedList 继承了它的父类 AbstractSequentialList 中的iterator()方法。
下面是 AbstractSequentialList 中iterator()方法的源代码:
public Iterator<E> iterator() {
return listIterator();
}
可以看到调用了 AbstractList 类中的 listIterator() 方法。
下面来看一下 AbstractList 类中 listIterator() 方法的源代码:
public ListIterator<E> listIterator() {
return listIterator(0);
}
可以看到调用了带有一个参数的 listIterator方法,而LinkedList 重写了该方法,返回一个 ListItr 对象。
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
ListItr 是 ListIterator 接口的实现类,下面是源代码,省略了很多部分,只列出简要方法。
private class ListItr implements ListIterator<E> {
...
public boolean hasNext() {
return nextIndex < size;
}
public E next() {
...
}
public boolean hasPrevious() {
return nextIndex > 0;
}
public E previous() {
checkForComodification();
...
}
...
}
新的迭代器接口 ListIterator,它继承了 Iterator 接口,并增加了一些新的迭代方式,比如在遍历List 时可以从任意下标开始遍历,而且支持双向遍历。注意ListIterator只支持List类型集合。
public interface ListIterator<E> extends Iterator<E> {
boolean hasNext();
E next();
boolean hasPrevious();
E previous();
}
增强for循环遍历
它的底层原理也是Iterator。
【代码示例1】
for (String str : list) {
System.out.print(str + ",");
}
【反编译】
反编译后我们可以看得出,底层的实现就是迭代器,而这个for-each的写法不过是Java的一个语法糖罢了。
Iterator var3 = list.iterator();
while(var3.hasNext()) {
String str = (String)var3.next();
System.out.print(str + ",");
}
问题
当使用集合中的remove方法删除元素时会出现 java.util.ConcurrentModificationException 异常信息。
fail-fast 是一种通用的系统设计思想,一旦检测到可能会发生错误,就立马抛出异常,程序将不再往下执行。
①在使用迭代器的remove()操作时,会将更新后的modCount给expectedModCount,两者会得到同步,但是在调用集合的remove()方法后,两个不会进行同步,进而导致在checkForComodification()校验时未通过,抛出java.util.ConcurrentModificationException异常。这种机制可以保证迭代器在遍历 ArrayList 时,不会遗漏或重复元素,同时也可以在多线程环境下检测到并发修改问题。
②所以,在单线程下使用迭代器是没有问题的,但是在多线程下同时操作集合就不允许了,可以通过fail-fast快速失败机制,快速判断是否存在同时操作问题。因此,集合在多线程下使用是不安全的。
这一部分还是不太明白,可以学习多线程并发之后再来看一下。
参考博客: