ArrayList源码分析

ArrayList是我们最常用的集合类型之一,大家都知道他的底层实现是数组。最近刚好想研究一下jdk的源码,就从ArrayList开始看吧。
本来我想写的 但是我看完源码在查资料的时候发现 这个老哥写的很好,跟我的想法很像,下面贴出链接
https://blog.csdn.net/starexplode/article/details/80469079
他有些地方没写全 我这里补充一下
比如迭代器是如何实现安全的循环删除的

public Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * An optimized version of AbstractList.Itr
     */
    private class Itr implements Iterator<E> {
        int cursor; // 当前操作的数组索引
        int lastRet = -1; // 上次操作的数组索引
        int expectedModCount = modCount;
        //如果当前操作索引==数组size 说明没有next了
        public boolean hasNext() {
            return cursor != size;
        }
        
        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor; //第一次这里是0,i记录当前操作的索引
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1; //当前操作的值变为下一个,保证next获取的是下个索引的值。
            return (E) elementData[lastRet = i]; //将上一个操作的值变为i并取出当前操作的值
        }
        /**
        * arrayList的remove其实就是将索引后的所有值向前挪了一位,这时如果能记录到索引值和后一位的值就能安全的循环删除了
        */
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet); //由于next()之后才remove() lastRet就是当前next()获取的值 ,所以直接删除
                cursor = lastRet; // 将当前操作值 赋值成上次操作的值,这样就保证了下次next()操作的是remove前的索引
                lastRet = -1; //重新将lastRet赋值为-1 防止直接再次调用remove() 只能在next()后调用remove()
                expectedModCount = modCount; //由于remove会导致modCount++ 这里为了保证这两个值相等。
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
        /**
        * 这个方法可以在 next()到想要的结果之后对剩余的部分迭代 执行相同的操作,1.8新增,可以在特殊场景减少迭代次数。
        */
        @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() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

还有一个是ListItr 这个类是继承自ArrayList的Itr 并且实现了ListIterator接口的 而ListIterator又是继承自Iterator的所以他只要实现ListIterator的几个独有方法就可以了。

private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();//直接调用父类的构造
            cursor = index;
        }
        //如果当前索引不为0  就表示前面还有索引
        public boolean hasPrevious() {
            return cursor != 0;
        }
        //操作的下一个结果
        public int nextIndex() {
            return cursor;
        }
        //上一个索引 可能为负
        public int previousIndex() {
            return cursor - 1;
        }
        //实现思路和next 类似 这里不再赘述
        @SuppressWarnings("unchecked")
        public E previous() {
            checkForComodification();
            int i = cursor - 1; 
            if (i < 0)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i;
            return (E) elementData[lastRet = i];
        }
        给next()的值赋值,解决了迭代器中无法修改值得问题
        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
        //甚至可以add()
        public void add(E e) {
            checkForComodification();

            try {
                int i = cursor;
                ArrayList.this.add(i, e);
                cursor = i + 1;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

之后还有一个SubList 这里相当于是一个内部类 控制的是 一个this的子集 ,里面有list的基本操作。这里不再赘述 很简单。
最后是jdk1.8新加的Spliterator 继续放老哥的文档
https://blog.csdn.net/starexplode/article/details/80567758
写的很棒。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容