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

posted on   乐之者v  阅读(2499)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示