java的Iterator源码浅析
在java的集合中,List接口继承Collection接口,AbstractList类实现了List接口,在AbstractList中的内部类Itr实现了Iterator接口
ArrayList实现List接口并继承AbstractList类,结构图如下:(图片出自网络)
Iterator接口源码:
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()); } }
AbstractList的内部类Itr实现了Iterator接口,如下所示:
private class Itr implements Iterator<E> { /**元素的下标 * 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(); } }
ArrayList中的iterator()方法:
public Iterator<E> iterator() { return new Itr(); }
ArrayList中的内部类Itr源码功能类似于AbstractList的内部类Itr。
阅读了Iterator的源码,再回头看Iterator遍历List的过程,理解就会深刻很多。
List<String> list=new ArrayList<String>();
list.add("apple"); list.add("banana"); list.add("watermelon");
for (Iterator<String> iterator=list.iterator();iterator.hasNext();) {
System.out.println( iterator.next());
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了