ArrayList中的迭代器

本文详细介绍了Java中ArrayList的迭代器实现原理,包括其内部类Itr的源码分析,解释了如何通过cursor和lastRet变量追踪迭代过程,以及expectedModCount变量如何确保迭代器与ArrayList数据的一致性。

ArrayList需要遍历时,可以调用他的iterator()方法返回一个迭代器,然后用迭代器进行遍历。

ArrayList中的iterator

public Iterator<E> iterator() {

returnnew Itr();

}

iterator()方法放回了一个Itr类实例,这个Itr类是ArrayList的一个内部类,实现了Iterator接口。

Itr源码如下:

/**

* An optimized version of AbstractList.Itr

*/

privateclass Itr implements Iterator<E> {

intcursor; // index of next element to return

intlastRet = -1; // index of last element returned; -1 if no such

intexpectedModCount = modCount;

publicboolean hasNext() {

returncursor != size;

}

@SuppressWarnings(“unchecked”)

public E next() {

checkForComodification();

inti = cursor;

if (i >= size)

thrownew NoSuchElementException();

Object[] elementData = ArrayList.this.elementData;

if (i >= elementData.length)

thrownew ConcurrentModificationException();

cursor = i + 1;

return (E) elementData[lastRet = i];

}

publicvoid remove() {

if (lastRet < 0)

thrownew IllegalStateException();

checkForComodification();

try {

ArrayList.this.remove(lastRet);

cursor = lastRet;

lastRet = -1;

expectedModCount = modCount;

} catch (IndexOutOfBoundsException ex) {

thrownew ConcurrentModificationException();

}

}

finalvoid checkForComodification() {

if (modCount != expectedModCount)

thrownew ConcurrentModificationException();

}

}

Itr类的三个成员变量。

cursor类似游标,指向迭代器下一个值的位置。

lastRet是迭代器最后一次取出的元素的位置。

expectedModCount的值为Itr初始化时候ArrayListmodCount的值。

modCount用于记录ArrayList内发生结构性改变的次数,而Itr每次进行nextremove的时候都会去检查expectedModCount值是否还和现在的modCount值,从而保证了迭代器和ArrayList内数据的一致性。

源码下载:

链接: http://pan.baidu.com/s/1pJK9jon

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值