手撕Iterator底层源码

手撕Iterator底层源码

public abstract class AbstractList<E>{
    
    //操作数 - 记录使用(添加、删除)集合的次数
    //为什么操作数只记录添加、删除集合的次数?
    //因为添加或删除会改变集合的长度,所以会被记录
    protected transient int modCount = 0;//4
}

public class ArrayList<E> extends AbstractList<E> implements List<E>{
    //存储数据的容器
    transient Object[] elementData;//["曹操","典韦","许褚","郭嘉"]
    //元素的个数/指针
    private int size;//4
    
    //e - 郭嘉
    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++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    
    public Iterator<E> iterator() {
        return new Itr();
    }
    
    //私有的成员内部类
    private class Itr implements Iterator<E> {
        int cursor;       // 游标 -- 4
        int lastRet = -1; // 当前元素的下标 - 3
        int expectedModCount = modCount;//内部操作数 - 4

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

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();//判断操作数不能与内部操作数就报错
            int i = cursor;//i = 3
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;//获取外部类的数据容器
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

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

        final void checkForComodification() {
            //操作数不等于内部操作数,就报错 -- ConcurrentModificationException
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
}

ArrayList<String> list = new ArrayList<>();
		
list.add("曹操");
list.add("典韦");
list.add("许褚");
list.add("郭嘉");

//为什么Iterator是个接口?
//Iterator的主要作用是遍历集合(ArrayList/LinkedList/Vector....)
//众多的集合的底层实现肯定是不一样的,将迭代器设计成接口,让每个集合自己去实现(内部类)
Iterator<String> it = list.iterator();
while(it.hasNext()){
    String element = it.next();
    System.out.println(element);
}

分析源码:一定要找场景

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雨霖先森

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值