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

注意:看源码找场景

相关推荐
Q_Q19632884751 分钟前
python的电影院座位管理可视化数据分析系统
开发语言·spring boot·python·django·flask·node.js·php
该用户已不存在4 分钟前
OpenJDK、Temurin、GraalVM...到底该装哪个?
java·后端
杜子不疼.28 分钟前
《Python学习之第三方库:开启无限可能》
开发语言·python·学习
西工程小巴29 分钟前
实践笔记-VSCode与IDE同步问题解决指南;程序总是进入中断服务程序。
c语言·算法·嵌入式
TT哇35 分钟前
@[TOC](计算机是如何⼯作的) JavaEE==网站开发
java·redis·java-ee
Tina学编程41 分钟前
48Days-Day19 | ISBN号,kotori和迷宫,矩阵最长递增路径
java·算法
Moonbit1 小时前
MoonBit Perals Vol.06: MoonBit 与 LLVM 共舞 (上):编译前端实现
后端·算法·编程语言
青川入梦1 小时前
MyBatis极速通关上篇:Spring Boot环境搭建+用户管理实战
java·开发语言·mybatis
执子手 吹散苍茫茫烟波1 小时前
leetcode415. 字符串相加
java·leetcode·字符串
CC__xy1 小时前
04 类型别名type + 检测数据类型(typeof+instanceof) + 空安全+剩余和展开(运算符 ...)简单类型和复杂类型 + 模块化
开发语言·javascript·harmonyos·鸿蒙