zoukankan      html  css  js  c++  java
  • ArrayList源码解析

    1.父类与接口

    public class ArrayList<E> extends AbstractList<E>
            implements List<E>, RandomAccess, Cloneable, java.io.Serializable

    ArrayList继承了AbstractList类,同时实现了List(list规范)、RandomAccess、Cloneable(克隆)、Serializable(序列号)接口

    2.类的属性

        /**
         * 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.
         */
        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.
         */
        transient Object[] elementData; // non-private to simplify nested class access
    
        /**
         * The size of the ArrayList (the number of elements it contains).
         *
         * @serial
         */
        private int size;

    ArrayList一共定义了五个属性,其中三个为final static,即这三个属性为ArrayList所有对象所共享,且不能被修改

    int DEFAULT_CAPACITY = 10;//ArrayList初始化容量
    Object[] EMPTY_ELEMENTDATA = {};//实例共享的空集合
    Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};//以默认大小初始化的共享的空集合。

    剩余的两个属性

    transient Object[] elementData;//实际存储对象的集合,使用了transient,使该属性不会被序列化。由此可见,ArrayList采用数组的形式存储元素
    private int size;//集合的实际元素数量

    3.类的构造函数

        public ArrayList() {
            this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
        }

    public ArrayList():无参构造器,元素为共享的空数组。

        public ArrayList(int initialCapacity) {
            if (initialCapacity > 0) {
                this.elementData = new Object[initialCapacity];
            } else if (initialCapacity == 0) {
                this.elementData = EMPTY_ELEMENTDATA;
            } else {
                throw new IllegalArgumentException("Illegal Capacity: "+
                                                   initialCapacity);
            }
        }

    public ArrayList(int initialCapacity):参数为int类型的构造函数。指定集合的初始容量,如果参数大于0,则建立与之对应的新的数组,如果参数等于0,则等于共享的空数组。由于此时仍未添加元素,因此size值未被操作,仍旧是0。

        public ArrayList(Collection<? extends E> c) {
            elementData = c.toArray();// ArrayList采用Arrays.copyof(elementData,size)
            if ((size = elementData.length) != 0) {
                // c.toArray might (incorrectly) not return Object[] (see 6260652)
                if (elementData.getClass() != Object[].class)
                    elementData = Arrays.copyOf(elementData, size, Object[].class);
            } else {
                // replace with empty array.
                this.elementData = EMPTY_ELEMENTDATA;
            }
        }

    public ArrayList(Collection<? extends E> c):参数为集合的构造函数。如果参数为空集合,则用共享的空数组作为集合的数组。否则,调用参数的toArray()方法,将参数中的元素赋值给elementData(在这个过程中,赋值给elementData的是一个新的数组,对参数中的元素进行操作,不会再影响该集合的元素,具体在toArray()方法中说明),同时判断参数的类类型是否为Objec[],如果不是,将其转换为Object[]数组,并将元素添加进去。

    4.ArrayList元素添加、删除和查询

    添加元素

        public boolean add(E e) {
            ensureCapacityInternal(size + 1);  // Increments modCount!!
            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);
        }
    
        private void grow(int minCapacity) {
            // overflow-conscious code
            int oldCapacity = elementData.length;
            int newCapacity = oldCapacity + (oldCapacity >> 1);
            if (newCapacity - minCapacity < 0)
                newCapacity = minCapacity;
            if (newCapacity - MAX_ARRAY_SIZE > 0)
                newCapacity = hugeCapacity(minCapacity);
            // minCapacity is usually close to size, so this is a win:
            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:调用boolean add(E e)方法添加元素。

    步骤2:判断用以存储元素的数组elementData是否等于DEFAULTCAPACITY_EMPTY_ELEMENTDATA(共享的空数组),如果是,说明该集合中elementData尚未初始化,此时size=0,elementData={},因此最小容量minCapacity应为默认的初始化容量。如果不等于,说明elementData已经被初始化,minCapacity应为当前元素数量加1,即size+1。

    步骤3:当minCapacityelementData的length大,说明该数组已经无法存储更多的元素,需要进行扩容,进入grow(int m)。否则,直接将新增的元素添加到elementData中,并return true。

    步骤4:当元素elementData需要扩容时候,每次都会扩容1.5倍。考虑到存在溢出问题,分为三种情况讨论:

      (1)newCapacity小于MAX_ARRAY_SIZE

        此时正常扩容1.5倍。

      (2)newCapacity大于MAX_ARRAY_SIZE,小于Integer.MAX_VALUE。

        此时进入hugeCapacity方法,如果minCapacity小于0,抛出异常OutOfMemoryError。如果大于MAX_ARRAY_SIZE,只能返回Integer.MAX_VALUE(讲道理,这里也已经超出了数组允许的最大值,应该也会抛出异常OutOfMemoryError)。如果minCapacity小于MAX_ARRAY_SIZE,则返回MAX_ARRAY_SIZE,下次扩容时,抛出异常OutOfMemoryError

      (3)newCapacity大于Integer.MAX_VALUE

        这种情况下,在初始化newCapacity时内存溢出,newCapacity变为负数,newCapacity=minCapacity。

    步骤5:最后将新元素添加在elementData[size+1]的位置,返回true。

    删除元素:

    根据索引删除元素

        public E remove(int index) {
            rangeCheck(index);
    
            modCount++;
            E oldValue = elementData(index);
    
            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
    
            return oldValue;
        }
    
        private void rangeCheck(int index) {
            if (index >= size)
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }

    使用Native方法System.arraycopy对index之后的数据进行重新复制,令原本最后位的数据=null,最后返回被移除的数据。

    根据原对象删除元素:

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

    步骤1:for循环遍历集合内元素数组,如果找到该对象,使用Native方法System.arraycopy对index之后的数据进行覆盖,然后令--size位的数据=null,并返回true。如果没有找到该对象,返回false。

    部分常用方法:

        public int size() {
            return size;
        }

    int size():返回当前集合中size的值。

        public boolean isEmpty() {
            return size == 0;
        }

    boolean isEmpty():判断当前集合元素是否为空,判断标准size是否等于0。

  • 相关阅读:
    [COI2007] Patrik 音乐会的等待 单调栈
    [NOI2012]随机数生成器 矩阵乘法
    流程控制主while,for,python画金字塔,画9*9乘法表
    VS第一天(一堆错误的错误示范)
    markdown插入表格语法
    格式化输出,基本运算符,流程控制主if
    jupyter notebook的插件安装及文本格式修改
    7个好用的社交分享按钮代码片段
    标签页tab.js 在栏目之间切换,局部变化
    详解 CSS 属性
  • 原文地址:https://www.cnblogs.com/yxth/p/10462783.html
Copyright © 2011-2022 走看看