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

注意:看源码找场景

相关推荐
罗曼蒂克在消亡3 分钟前
2.3MyBatis——插件机制
java·mybatis·源码学习
Fairy_sevenseven8 分钟前
【二十八】【QT开发应用】模拟WPS Tab
开发语言·qt·wps
_GR15 分钟前
每日OJ题_牛客_牛牛冲钻五_模拟_C++_Java
java·数据结构·c++·算法·动态规划
蜡笔小新星16 分钟前
Python Kivy库学习路线
开发语言·网络·经验分享·python·学习
凯子坚持 c16 分钟前
C语言复习概要(三)
c语言·开发语言
ROBIN__dyc27 分钟前
表达式
算法
无限大.28 分钟前
c语言200例 067
java·c语言·开发语言
余炜yw29 分钟前
【Java序列化器】Java 中常用序列化器的探索与实践
java·开发语言
攸攸太上30 分钟前
JMeter学习
java·后端·学习·jmeter·微服务
无限大.30 分钟前
c语言实例
c语言·数据结构·算法