在AbstractList中还有一个内部类Itr,Itr implements Iterator,Itr是一个List遍历的工具类,当然list.iterator()方法也是返回Itr对象,在Itr中有一个校验位属性expectedModCount,对于一个Itr对象,其初始时expectedModCount=modCount。
【注】在AbstractList中,有一个属性modCount,这个属性是跟踪List中数据被修改的次数,任何对List的add/remove操作,都将导致modCount++。
Iterator是List一个视图,其最终还是操作List的存储结构。在使用iterator遍历时,remove()操作,会导致modCount++,因为有expectedModCount=modCount,即在 iterator中remove数据,会带来expectedModCount与modCount值的同步。
在Iterator遍历时,next(),remove()方法会校验expectedModCount与modCount值是否一致,如果不一致,就意味着这List数据在iterator外部被修改,此时iterator遍历将会造成 ConcurrentModificationException。
AbstractLlist不仅支持普通的Iterator,还支持ListIterator(ArrayList,LinkedList均支持),ListIterator增加了遍历时双向游标能力(previous,next),增加了add方法。add方法和remove方法一样也做了expectedModCount和modCount一致性校验。
转载自:小议Iterator