• ArrayList源码解析(JDK8)



    加油,不要过度焦虑♪(^∇^*)

    一、ArrayList继承体系

    ArrayList又称动态数组,底层是基于数组实现的List,与数组的区别在于,它具备动态扩展能力,从源码看一看ArrayList继承了哪些类?实现了哪些类?

    public class ArrayList<E> extends AbstractList<E>
            implements List<E>, RandomAccess, Cloneable, java.io.Serializable
    {
    
    • 1
    • 2
    • 3

    可以看出,ArrayList实现了List、RandomAccess、Cloneable、Serializable

    • 实现List,具备基本的遍历、删除、添加等操作
    • 实现RandomAccess,支持快速随机访问
    • 实现Cloneable,支持对象被克隆
    • 实现Serializable,支持被序列化

    继承体系图:

    在这里插入图片描述


    二、ArrayList属性

        private static final int DEFAULT_CAPACITY = 10;
        
        private static final Object[] EMPTY_ELEMENTDATA = {};
        
        private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
        
        transient Object[] elementData; 
        
        private int size;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • DEFAULT_CAPACITY:集合的默认容量,默认为10,通过new ArrayList()空参构造器创建实例时的默认容量是10。
    • EMPTY_ELEMENTDATA:空数组,通过new ArrayList(0)创建List集合实例时用的是这个空数组。
    • DEFAULTCAPACITY_EMPTY_ELEMENTDATA:默认容量空数组,这种是通过new ArrayList()无参构造方法创建集合时用的是这个空数组,与EMPTY_ELEMENTDATA的区别是在添加第一个元素时使用这个空数组的会初始化为DEFAULT_CAPACITY(10)个元素。
    • elementData:存储数据元素的数组,使用transient修饰,该字段不被序列化。
    • size:存储数据元素的个数,elementData数组的长度并不是存储数据元素的个数。

    三、构造方法

    1、ArrayList(int initialCapacity)

        /**
         * Constructs an empty list with the specified initial capacity.
         * 构造具有指定初始容量的空数组
         * @param  initialCapacity  the initial capacity of the list
         * 参数initialCapacity是初始容量
         * @throws IllegalArgumentException if the specified initial capacity
         *         is negative
         * 如果初始容量不合法,则抛出异常
         */
        public ArrayList(int initialCapacity) {
            if (initialCapacity > 0) {
                this.elementData = new Object[initialCapacity];
            } else if (initialCapacity == 0) {
            	//这就是EMPTY_ELEMENTDATA
                this.elementData = EMPTY_ELEMENTDATA;
            } else {
                throw new IllegalArgumentException("Illegal Capacity: "+
                                                   initialCapacity);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    2、ArrayList()

        /**
         * Constructs an empty list with an initial capacity of ten.
         */
        public ArrayList() {
        	//这就是DEFAULTCAPACITY_EMPTY_ELEMENTDATA
            this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    3、ArrayList(Collection c)

        /**
         * 构造一个含有具体元素集合的list,按照集合迭代的顺序返回
         * Constructs a list containing the elements of the specified
         * collection, in the order they are returned by the collection's
         * iterator.
         *	//参数c的元素放入list中
         * @param c the collection whose elements are to be placed into this list
         * //如果指定的集合为null,则抛出空指针异常
         * @throws NullPointerException if the specified collection is null
         */
        public ArrayList(Collection<? extends E> c) {
        	// 把c转化为数组
            elementData = c.toArray();
            if ((size = elementData.length) != 0) {
               // 如果elementData类型不是Object
                if (elementData.getClass() != Object[].class)
                	//则重新拷贝为Object类型
                    elementData = Arrays.copyOf(elementData, size, Object[].class);
            } else {
                // 用空数组代替
                this.elementData = EMPTY_ELEMENTDATA;
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    四、ArrayList 相关操作方法

    1、add(E e)

    添加元素到末尾,平均时间复杂度为 O ( 1 ) O(1) O(1)

        /**
        	//添加指定元素到list的末尾
         * Appends the specified element to the end of this list.
         *	//元素e被添加到list
         * @param e element to be appended to this list
         * @return true (as specified by {@link Collection#add})
         */
        public boolean add(E e) {
        	//检查是否需要扩容,minCapacity = (size + 1)
            ensureCapacityInternal(size + 1);  // Increments modCount!!
            //把元素插入到最后一位
            elementData[size++] = e;
            return true;
        }
        //检查是否需要扩容的方法
    	private void ensureCapacityInternal(int minCapacity) {
            ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
        }
        //计算最小容量的方法
        private static int calculateCapacity(Object[] elementData, int minCapacity) {
        // 如果list={}
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        	// 返回最大的一方,DEFAULT_CAPACITY的值为10
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }
    	//
        private void ensureExplicitCapacity(int minCapacity) {
        	//记录被修改的次数
            modCount++;
            // 当存储长度大于现有的长度时,需要扩容
            if (minCapacity - elementData.length > 0)
                grow(minCapacity);//扩容
        }
        /**
    	 *增加容量,确保它可以容纳至少最小容量参数指定的元素数
         * Increases the capacity to ensure that it can hold at least the
         * number of elements specified by the minimum capacity argument.
         * // minCapacity 是最小容量
         * @param minCapacity the desired minimum capacity
         */
        private void grow(int minCapacity) {
            // 先计算现有的长度
            int oldCapacity = elementData.length;
            // 扩容1.5倍
            int newCapacity = oldCapacity + (oldCapacity >> 1);
            // 如果新容量发现比需要的容量还小,则以需要的容量为准
            if (newCapacity - minCapacity < 0)
                newCapacity = minCapacity;
            //如果新容量已经超过最大容量了,则使用最大容量(Integer.MAX_VALUE - 8)
            if (newCapacity - MAX_ARRAY_SIZE > 0)
                newCapacity = hugeCapacity(minCapacity);
            // 以新容量拷贝出来一个新数组
            elementData = Arrays.copyOf(elementData, newCapacity);
        }
        //使用最大的容量
        private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64

    最后来分析一下执行流程:

    1. 检查是否需要扩容;
    2. 如果elementData等于DEFAULTCAPACITY_EMPTY_ELEMENTDATA(即为{})则初始化容量大小为DEFAULT_CAPACITY(10);
    3. 新容量是老容量的1.5倍(oldCapacity + (oldCapacity >> 1)),如果加了这么多容量发现比需要的容量还小,则以需要的容量为准;
    4. 创建新容量的数组并把老数组按顺序依次拷贝到新数组中;

    2、add(int index, E element)

    添加元素到指定位置,平均时间复杂度为 O ( n ) O(n) O(n)

     /**
         * 在list的指定位置插入指定元素,移动当前位于该位置的元素(如果有的话)和
    右边的任何后续元素(向它们的索引添加1)
         * Inserts the specified element at the specified position in this
         * list. Shifts the element currently at that position (if any) and
         * any subsequent elements to the right (adds one to their indices).
         * //index为插入指定元素的索引
         * @param index index at which the specified element is to be inserted
         * @param element element to be inserted
         * @throws IndexOutOfBoundsException {@inheritDoc}
         */
        public void add(int index, E element) {
        	//检查是否越界
            rangeCheckForAdd(index);
            //检查是否需要扩容
            ensureCapacityInternal(size + 1);  // Increments modCount!!
            //这个方法就是在index位置空出来,index后的元素向后移动
            System.arraycopy(elementData, index, elementData, index + 1,
                             size - index);
            //在index位置插入element
            elementData[index] = element;
            size++;
        }
        private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    来看看它的执行流程执行流程:

    1. 先检查索引是否越界;
    2. 然后检查是否需要扩容;
    3. 把插入索引位置后的元素都往后挪一位;
    4. 最后在插入索引位置放置插入的元素;
    5. 元素数量增1;

    3、addAll(Collection c)

    /**
         * 在list末尾增加collection集合的所有元素
         * Appends all of the elements in the specified collection to the end of
         * this list, in the order that they are returned by the
         * specified collection's Iterator.  The behavior of this operation is
         * undefined if the specified collection is modified while the operation
         * is in progress.  (This implies that the behavior of this call is
         * undefined if the specified collection is this list, and this
         * list is nonempty.)
         *
         * @param c collection containing elements to be added to this list
         * @return true if this list changed as a result of the call
         * @throws NullPointerException if the specified collection is null
         */
        public boolean addAll(Collection<? extends E> c) {
            Object[] a = c.toArray();
            int numNew = a.length;
            ensureCapacityInternal(size + numNew);  // Increments modCount
            System.arraycopy(a, 0, elementData, size, numNew);
            size += numNew;
            return numNew != 0;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    执行流程:

    1. 将c转换为数组;
    2. 检查minCapacity = (size + numNew)是否需要扩容;
    3. 把数组a中的元素拷贝到elementData的尾部;
    4. size +=numNew

    4、get(int index)

    获取指定索引位置的元素,时间复杂度为 O ( 1 ) O(1) O(1)

    /**
         * 返回list中指定位置的元素
         * Returns the element at the specified position in this list.
         *
         * @param  index index of the element to return
         * @return the element at the specified position in this list
         * @throws IndexOutOfBoundsException {@inheritDoc}
         */
        public E get(int index) {
        	//检查是否数组下标越界
            rangeCheck(index);
            return elementData(index);
        }
        private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    	//返回数组index的值
        @SuppressWarnings("unchecked")
        E elementData(int index) {
            return (E) elementData[index];
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    执行流程:检查数组下标是否越界,不越界则返回对应数组下标值。


    5、remove(int index)

    删除指定索引位置的元素,时间复杂度为 O ( n ) O(n) O(n)

        /**
         * Removes the element at the specified position in this list.
         * 将所有后续元素向左移动(从它们的索引中减去1)
         * Shifts any subsequent elements to the left (subtracts one from their indices).
         * @param index the index of the element to be removed
         * @return the element that was removed from the list
         * @throws IndexOutOfBoundsException {@inheritDoc}
         */
        public E remove(int index) {
        	//检查数组下标是否越界
            rangeCheck(index);
            //修改次数加1
            modCount++;
            //记录数组index下标的值,用oldValue记录下来
            E oldValue = elementData(index);
            //记录需要移动的次数
            int numMoved = size - index - 1;
            //如果要删除的元素不是list的最后一个元素
            if (numMoved > 0)
            	//则把剩余元素向前移动numMoved位
                System.arraycopy(elementData, index+1, elementData, index,
                                 numMoved);
            //将最后一个元素删除,有助于垃圾回收
            elementData[--size] = null; // clear to let GC do its work
            //返回删除的值
            return oldValue;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    来看看执行流程:

    1. 首先要检查索引是否越界;
    2. 然后获取指定索引位置的元素;
    3. 接着如果删除的不是最后一位,则其它元素往前移一位;
    4. 将最后一位置为null,方便垃圾回收;
    5. 最后返回删除的元素。

    需要注意的是:remove的操作并未修改数组的容量!!!


    6、remove(Object o)

    删除指定元素值的元素,时间复杂度为 O ( n ) O(n) O(n)

       /**
         * 从此列表中删除第一个出现的指定元素(如果存在)
         * Removes the first occurrence of the specified element from this list,
         * 如果不存在,则不发生改变
         * if it is present.  If the list does not contain the element, it is unchanged.  
         * 通俗来说,删除的是index最低的元素
         * More formally, removes the element with the lowest index
         * i such that
         * (o==null ? get(i)==null : o.equals(get(i)))
         * (if such an element exists).  Returns true if this list
         * contained the specified element (or equivalently, if this list
         * changed as a result of the call).
         *
         * @param o element to be removed from this list, if present
         * @return true if this list contained the specified element
         */
        public boolean remove(Object o) {
        	//如果要删除的是null值
            if (o == null) {
            	//遍历整个list
                for (int index = 0; index < size; index++)
                	//发现list存在null值
                    if (elementData[index] == null) {
                        fastRemove(index);
                        return true;
                    }
            } else {
                for (int index = 0; index < size; index++)
                    if (o.equals(elementData[index])) {
                        fastRemove(index);
                        return true;
                    }
            }
            //遍历的过程中都不存在o值,则返回false代表不存在
            return false;
        }
        /*
         * 跳过边界检查且不返回已删除值的私有删除方法
         * fastRemove(int index)相对于remove(int index)少了检查索引越界的操作,可见jdk将性能优化到极致
         * Private remove method that skips bounds checking and does not return the value removed.
         */
        private void fastRemove(int index) {
        	//修改次数加1
            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
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    执行流程:

    1. 找到第一个等于指定元素值的元素;
    2. 快速删除;

    到此结束,感谢阅读(*^▽^*)

  • 相关阅读:
    真实软件测试案例测试报告编写规划
    uni-app 原生ios插件开发以及自定义基座
    【秋招面经搬运】神策数据面经总结
    golang语言的gofly快速开发框架如何设置多样的主题说明
    【javaEE】网络原理(传输层Part3)
    上海亚商投顾:沪指冲高回落 中字头板块爆发领涨
    axios
    入门JavaWeb之 Session 篇
    新生儿早产:原因、科普和注意事项
    电脑文件自动备份到u盘,怎么实现?
  • 原文地址:https://blog.csdn.net/weixin_59654772/article/details/127618219