ArrayList里还有个迭代器的概念,用来遍历集合的,有Iterator、ListIterator两种,主要区别在于前者是单向移动遍历,ListIterator可以双向移动遍历。 Iterator的功能:
next()获取集合中的下一个元素;使用hasNext()检查是否还有元素可获取;使用remove()将迭代器新近返回的元素删除。实现迭代器需要继承Iterable接口,并实现其方法,要想实现集合的增强for循环也要继承该接口。ArrayList本身并没有直接继承这个接口,而是借由Collection接口间接地继承了该接口。 ArrayList内获取迭代器的方法:
public ListIterator<E> listIterator() { return new ListItr(0); } public Iterator<E> iterator() { return new Itr(); }ArrayList有自己的迭代器内部实现类,先看下Iterator:
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(); } } @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(); } }cursor是当前指向的下一个要返回元素,lastRet记录上一个已返回的元素,这里要注意在迭代器内进行删除时,删除掉的是最近一个已返回的元素,即lastRet指向的元素,因为删除后集合内被删除元素之后的元素会整体向前移位,此时必须把lastRet的指针指向的元素赋予给cursor,才能保证遍历不会出错。
接下来是ListIterator,它是Iterator的子类型,ListIterator可以双向移动指针,它还可以产生相对于迭代器在列表中指向的当前位置的前一个和后一个元素的索引,并可以用set()方法替换它最近访问的一个元素。 在previous()倒着遍历元素的方法中,cursor不再代表下一个要返回的元素,而是目前最近返回的元素,在previousIndex()返回下一个逆序元素索引时,也是将cursor - 1的索引返回。
private class ListItr extends Itr implements ListIterator<E> { ListItr(int index) { super(); cursor = index; } public boolean hasPrevious() { return cursor != 0; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } @SuppressWarnings("unchecked") public E previous() { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; return (E) elementData[lastRet = i]; } public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.set(lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void add(E e) { checkForComodification(); try { int i = cursor; ArrayList.this.add(i, e); cursor = i + 1; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } }迭代器内部还用到了modCount变量,在一个迭代器初始的时候会赋给成员变量expectedModCount,如果在迭代器遍历的过程中,一旦发现这个集合的modCount和迭代器中存储的expectedModCount不一样那就抛异常。为什么要这样呢,这里要提到个Fail-Fast机制:
ArrayList不是线程安全的,modCount就是修改次数的意思,对ArrayList内容的修改都将增加这个值,在迭代器初始化的时候会将这个值会赋给迭代器的 expectedModCount,在迭代过程中,判断 modCount 跟 expectedModCount 是否相等,如果不相等就表示已经有其他线程修改了 ArrayList。