美文网首页
ArrayList源码分析

ArrayList源码分析

作者: c5fc16271aee | 来源:发表于2018-07-31 14:33 被阅读0次

    【补充说明:】

    【modCount】
     在父类AbstractList中定义了一个int型的属性:modCount,记录了ArrayList结构性变化的次数。
     protected transient int modCount = 0; *  在ArrayList的所有涉及结构变化的方法中都增加modCount的值,包括:add()、remove()、addAll()、removeRange()及clear()方法。这些方法每调用一次,modCount的值就加1。
     注:add()及addAll()方法的modCount的值是在其中调用的ensureCapacity()方法中增加的。
     
     【调用add()方法时,调用的函数:】
    程序调用add,实际上还会进行一系列调用,可能会调用到grow,grow可能会调用hugeCapacity。
     add ——>ensureCapacityInternal  ——>ensureExplicitCapacity - - ->grow - - ->hugeCapacity
     添加 确保内部容量(是否扩容)            确保明确的容量  扩容函数         指定新容量
        实例看图
     
        【总结】:
            增:仅是将这个元素添加到末尾。操作快速
            删:由于需要移动插入位置后的元素,并且涉及到数组的复制。操作较慢
            改:直接对指定位置元素进行修改,不涉及元素的挪动和数组赋值。操作快速
            查:直接返回指定下标的数组元素。操作快速
        
            ArrayList有其特殊的应用场景,与LinkedList相对应。其优点是随机读取,
         缺点是插入元素时需要移动大量元素,效率不太高。[查找修改快而插入删除慢的特点]
    
    ArrayList实例01(数组).png ArrayList实例02(数组).png

    【ArrayList的一些属性:】

    public class ArrayList<E> extends AbstractList<E>
            implements List<E>, RandomAccess, Cloneable, java.io.Serializable
    {
        /**
         * 版本号
         */
        private static final long serialVersionUID = 8683452581122892189L;
    
        /**
         * Default initial capacity.
         * 默认初始容量
         */
        private static final int DEFAULT_CAPACITY = 10;
    
        /**
         * Shared empty array instance used for empty instances.
         * 用于空实例的共享空数组实例 (空对象数组)
         */
        private static final Object[] EMPTY_ELEMENTDATA = {};
     /**
         * Shared empty array instance used for default sized empty instances(实例). We
         * distinguish(区分) this from EMPTY_ELEMENTDATA to know how much to inflate(膨胀) when
         * first element(元素) is added.
         * 用于默认大小的空实例的共享空数组实例。我们将此与EMPTY_ELEMENTDATA区分开来,以了解何时
         *  膨胀多少第一个元素被添加(默认长度的空对象数组)
         *  DEFAULTCAPACITY_EMPTY_ELEMENTDATA
              默认长度       空      元素数据
         */
        private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    
        /**
         * The array buffer into which the elements of the ArrayList are stored(存储).
         * The capacity(容量) of the ArrayList is the length of this array buffer. Any
         * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
         * will be expanded to DEFAULT_CAPACITY when the first element is added.
         *
         * ArrayList的元素存储在其中的数组缓冲区。ArrayList的容量是此数组缓冲区的长度。
         *      任何使用elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA为空的ArrayList
         *      将在添加第一个元素时扩展到DEFAULT_CAPACITY。(元素数组)
         */
        transient Object[] elementData; // non-private to simplify nested class access
    
        /**
         * The size of the ArrayList (the number of elements it contains).
         * 实际元素大小,默认为0
         * @serial
         */
        private int size;
    

    【构造函数:】

     /**
         * Constructs an empty list with the specified(指定) initial capacity.
         *  构造具有指定初始容量的空列表
         *
         * @param  initialCapacity  the initial capacity of the list
         * @throws IllegalArgumentException if the specified initial capacity
         *         is negative
         */
        public ArrayList(int initialCapacity) {
            //初始容量大于0
            if (initialCapacity > 0) {
                //初始化元素数组
                this.elementData = new Object[initialCapacity];
                //初始容量为0
            } else if (initialCapacity == 0) {
                //元素数组 = (空数组实例/空对象数组)
                this.elementData = EMPTY_ELEMENTDATA;
            } else {
                //初始容量小于0,抛出异常
                throw new IllegalArgumentException("Illegal Capacity: "+
                                                   initialCapacity);
            }
        }
    
        /**
         * Constructs an empty list with an initial capacity(容量) of ten.
         * 构造一个初始容量为10的空列表
         */
        public ArrayList() {
            //无参构造函数,设置元素数组为空,长度为10
            this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
        }
    
        /**
         * Constructs a list containing the elements of the specified
         * collection, in the order they are returned by the collection's
         * iterator.
         *  构造一个包含指定集合元素的列表,其顺序由集合的迭代器返回。
         * @param c the collection whose elements are to be placed into this list
         * @throws NullPointerException if the specified collection is null
         * 集合参数构造函数
         */
        public ArrayList(Collection<? extends E> c) {
            //转换为数组
            elementData = c.toArray();
            //参数为非空集合
            if ((size = elementData.length) != 0) {
                // c.toArray might (incorrectly) not return Object[] (see 6260652)
                //是否成功转换为Object类型数组
                if (elementData.getClass() != Object[].class)
                    //不为Object数组,进行复制
                    elementData = Arrays.copyOf(elementData, size, Object[].class);
            } else {
                // replace(替换) with empty array. 替换为空数组
                this.elementData = EMPTY_ELEMENTDATA;
            }
        }
    
    

    【扩容相关下函数:】

    //按照函数名意为:确保内部容量 函数 / 扩容函数
        private void ensureCapacityInternal(int minCapacity) {
            //判断元素数组是否为空数组 (DEFAULTCAPACITY_EMPTY_ELEMENTDATA 默认长度的空对象数组))
            if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
                //取较大值(默认初始容量,传入的最小容量)
                minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
            }
            //调用【确保明确的容量】 函数;数组已经初始化过就执行这一步
            ensureExplicitCapacity(minCapacity);
        }
        
        //按照函数名意为:确保明确的容量 函数
        private void ensureExplicitCapacity(int minCapacity) {
            //结构性 修改时+1
            modCount++;
    
            // overflow-conscious code
            //当传入的最小容量 减去 元素数组的长度 大于0时,需要进行扩容
            if (minCapacity - elementData.length > 0)
                //调用 【grow函数】对数组进行扩容
                grow(minCapacity);
        }
    
        /**
         * The maximum size of array to allocate.
         * Some VMs reserve some header words in an array.
         * Attempts to allocate larger arrays may result in
         * OutOfMemoryError: Requested array size exceeds VM limit
         *  最大数组容量(集合最大容量)
         */
        private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    
        /**
         * Increases the capacity to ensure that it can hold at least the
         * number of elements specified by the minimum capacity argument.
         * 增加容量以确保它至少可以容纳由参数指定的元素数。
         *
         * @param minCapacity the desired minimum capacity
         * 扩容函数
         */
        private void grow(int minCapacity) {
            // overflow-conscious code
            //获取数组的旧容量
            int oldCapacity = elementData.length;
            //新容量为旧容量的1.5倍
            int newCapacity = oldCapacity + (oldCapacity >> 1);
            if (newCapacity - minCapacity < 0)
                //当新容量 减去 传入的最小容量 小于0时,将传入的最小容量赋值给 新容量
                newCapacity = minCapacity;
            if (newCapacity - MAX_ARRAY_SIZE > 0)
                //如果 新容量 减去 最大数组容量 大于0,
                newCapacity = hugeCapacity(minCapacity);    //指定新容量
            // minCapacity is usually close to size, so this is a win:
            //Arrays.copyOf功能是实现数组的复制,返回复制后的数组。参数是被复制的数组和复制的长度:
            //拷贝扩容
            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;
        }
    

    【增删改查函数:】

    /**
         * 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);
        }
    
        /**
         * Replaces(替换) the element(元素) at the specified position in this list with
         * the specified(指定) element.
         *  用指定的元素替换此列表中指定位置的元素
         * @param index index of the element to replace
         * @param element element to be stored at the specified position
         * @return the element previously at the specified position
         * @throws IndexOutOfBoundsException {@inheritDoc}
         * 【设定指定下标索引的元素值】
         */
        public E set(int index, E element) {
            //校验 索引是否合法(index 不能 大于 size)
            rangeCheck(index);
            //旧值
            E oldValue = elementData(index);
            //赋新值
            elementData[index] = element;
            //返回旧值
            return oldValue;
        }
    
        /**
         * Appends the specified element to the end of this list.
         *  将指定的元素追加到此列表的末尾。
         * @param e element to be appended to this list
         * @return <tt>true</tt> (as specified by {@link Collection#add})
         * 添加元素 
         */
        public boolean add(E e) {
            //调用【确保内部容量】函数:参数为(实际元素大小+1)
            //添加之前先检查是否需要扩容,此时数组长度最小为size+1
            ensureCapacityInternal(size + 1);  // Increments modCount!!
            //将元素添加到数组末尾
            elementData[size++] = e;
            return true;
        }
    
        /**
         * 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).
         *
         * @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!!
            //挪动插入位置后面的元素
            System.arraycopy(elementData, index, elementData, index + 1,
                             size - index);
            //在要插入的位置赋上新值
            elementData[index] = element;
            size++;
        }
    
        /**
         * Removes the element at the specified position in this list.
         * 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);
    
            modCount++;
            //得到旧值
            E oldValue = elementData(index);
            //需要移动的元素的个数
            int numMoved = size - index - 1;
            if (numMoved > 0)
                /**
                 * Object src :源数组
                 * int srcPos :在源数组中的起始位置
                 * Object dest:目标数组
                 * int destPos:在目标数组中的起始位置
                 * int length :要复制的数组元素的数量
                 */
                //void java.lang.System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
                System.arraycopy(elementData, index+1, elementData, index,numMoved);
            //赋值为空,有利于进行GC                   
            elementData[--size] = null; // clear to let GC do its work
            //返回旧值
            return oldValue;
        }
    
        /**
         * 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.  More formally, removes the element with the lowest index
         * <tt>i</tt> such that
         * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
         * (if such an element exists).  Returns <tt>true</tt> 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 <tt>true</tt> if this list contained the specified element
         */
        public boolean remove(Object o) {
            if (o == null) {
                for (int index = 0; index < size; index++)
                    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;
                    }
            }
            return false;
        }
    
        /*
         * Private remove method that skips bounds checking and does not
         * return the value removed.
         */
        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
        }
    
        /**
         * Removes all of the elements from this list.  The list will
         * be empty after this call returns.
         */
        public void clear() {
            modCount++;
    
            // clear to let GC do its work
            for (int i = 0; i < size; i++)
                elementData[i] = null;
    
            size = 0;
        }
    
        /**
         * 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 <tt>true</tt> 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;
        }
    

    相关文章

      网友评论

          本文标题:ArrayList源码分析

          本文链接:https://www.haomeiwen.com/subject/hmchvftx.html