java iterator 源码_java的Iterator源码浅析

在java的集合中,List接口继承Collection接口,AbstractList类实现了List接口,在AbstractList中的内部类Itr实现了Iterator接口

ArrayList实现List接口并继承AbstractList类,结构图如下:(图片出自网络)

166019940_1_20190714080351316.jpg

Iterator接口源码:

166019940_2_20190714080351675.gif

public interface Iterator {

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());

}

}

166019940_2_20190714080351675.gif

AbstractList的内部类Itr实现了Iterator接口,如下所示:

166019940_2_20190714080351675.gif

private class Itr implements Iterator {

/**元素的下标

* Index of element to be returned by subsequent call to next.*/

int cursor = 0;

/**上一个元素的下标。如果元素已被删除就设置为-1

* Index of element returned by most recent call to next or

* previous. Reset to -1 if this element is deleted by a call

* to remove.*/

int lastRet = -1;

/**允许修改的次数,违规操作会抛异常* The modCount value that the iterator believes that the backing

* List should have. If this expectation is violated, the iterator

* has detected concurrent modification.*/

int expectedModCount = modCount;

/*检查是否还有下一个元素*/

public boolean hasNext() {

return cursor != size();

}

/*光标下移,并且返回当前的元素*/

public E next() {

checkForComodification();

try {

int i = cursor;

E next = get(i);

lastRet = i;

cursor = i + 1;

return next;

} catch (IndexOutOfBoundsException e) {

checkForComodification();

throw new NoSuchElementException();

}

}

/*移除元素*/

public void remove() {

if (lastRet < 0)

throw new IllegalStateException();

checkForComodification();

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();

}

}

166019940_2_20190714080351675.gif

ArrayList中的iterator()方法:

public Iterator iterator() {

return new Itr();

}

ArrayList中的内部类Itr源码功能类似于AbstractList的内部类Itr。

阅读了Iterator的源码,再回头看Iterator遍历List的过程,理解就会深刻很多。

List list=new ArrayList();

list.add("apple"); list.add("banana"); list.add("watermelon");

for (Iterator iterator=list.iterator();iterator.hasNext();) {

System.out.println( iterator.next());

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值