Iterator底层源码分析

java 复制代码
/**
* Iterator用于遍历Collection下的集合,Collection下的每个集合底层实现不一样,意味着遍历逻辑也不一样,
* 所以Java的设计者将Iterator设计成了接口,让Collection下的每个集合实现Iterator
*/
public interface Iterator<E> {
    //判断是否有可迭代的元素
    boolean hasNext();

   	//返回下一个元素
    E next();

    //删除(默认方法) -- 报错
    default void remove() {
        throw new UnsupportedOperationException("remove");
    }
}
java 复制代码
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
	//外部操作数(记录集合添加、删除的次数)
	protected transient int modCount = 0;//6
}
java 复制代码
public class ArrayList<E> extends AbstractList<E> implements List<E>{
	
    //数据容器 - ["aaa","ccc","ddd","eee",null,null,null,null,null,null]
    transient Object[] elementData;
    //数据个数(指针)
    private int size;//4

    //e - "eee"
	public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // 判断是否扩容
        elementData[size++] = e;
        return true;
    }
    
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        ensureExplicitCapacity(minCapacity);
    }
    
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    
    //o - "bbb"
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            //线性查询(从头遍历到size的位置)
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    //删除元素(传入下标)
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }
    
    //index - 1
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;//计算移动次数
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }
    
    public Iterator<E> iterator() {
        return new Itr();
    }
    
    //Itr是成员内部类,因为Itr中使用到了外部类(ArrayList)的成员属性(modCount、size)
    private class Itr implements Iterator<E> {
        int cursor;       // 游标 - 4
        int lastRet = -1; // 当前元素的下标 - 3
        int expectedModCount = modCount;//内部操作数 - 6

        public boolean hasNext() {
            return cursor != size;//4 != 4
        }

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();//判断外部操作数和内部操作数是否相同
            int i = cursor;//i = 3
            if (i >= size)
                throw new NoSuchElementException();
            //elementData - ["aaa","ccc","ddd","eee",null,null,null,null,null,null]
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;//cursor - 4
            return (E) elementData[lastRet = i];
        }
        
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();//判断外部操作数和内部操作数是否相同

            try {
                //Itr依赖于ArrayList对象的remove()去删除元素
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                
                //重新将外部操作数赋值给内部操作数,保证内外部操作数一致不会出现脏数据
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

        
    }
}
java 复制代码
ArrayList<String> list = new ArrayList<>();
		
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add("ddd");
list.add("eee");

list.remove("bbb");

Iterator<String> it = list.iterator();
while(it.hasNext()){
    String element = it.next();
    System.out.println(element);
}

注意:看源码找场景

相关推荐
互联网全栈架构6 分钟前
遨游Spring AI:第一盘菜Hello World
java·人工智能·后端·spring
qq_429879676 分钟前
省略号和可变参数模板
开发语言·c++·算法
优秀的颜1 小时前
计算机基础知识(第五篇)
java·开发语言·分布式
BillKu1 小时前
Java严格模式withResolverStyle解析日期错误及解决方案
java
CodeWithMe1 小时前
【C/C++】std::vector成员函数清单
开发语言·c++
uyeonashi1 小时前
【QT控件】输入类控件详解
开发语言·c++·qt
飞川撸码1 小时前
【LeetCode 热题100】网格路径类 DP 系列题:不同路径 & 最小路径和(力扣62 / 64 )(Go语言版)
算法·leetcode·golang·动态规划
网安INF1 小时前
ElGamal加密算法:离散对数难题的安全基石
java·网络安全·密码学
Neil今天也要学习1 小时前
永磁同步电机参数辨识算法--IPMSM拓展卡尔曼滤波全参数辨识
单片机·嵌入式硬件·算法
yzx9910132 小时前
基于 Q-Learning 算法和 CNN 的强化学习实现方案
人工智能·算法·cnn