ArrayList源码解析(JDK1.8)及其相关对比

ArrayList源码解析(JDK1.8)

ArrayList是基于数组实现的动态扩容的动态数组

源码分析之前,我们来了解一下IDEA中一些查看层次结构关系图的相关快捷键(comand+7查看类的结构图、control+h查看类的层次结构图、option+command+u查看类的关系图),这几个快捷键有利于我们快速的查看类并了解其结构关系

先上类的关系图

ArrayList类的关系图

从类的关系图中可以看出ArrayList继承一个抽象类和实现了四个接口,然后分别简单介绍一下:

  • AbstractList:这里主要提供iterator迭代器的相关操作
  • List:提供数组的增删改查、迭代器遍历等操作
  • RandomAccess:标记接口,用来表明其支持快速(通常是固定时间)随机访问操作
  • Cloneable:按字段复制操作
  • 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.
     */
    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;
    
复制代码

transient Object[] elementData;//存放元素的数组

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) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        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)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
    
复制代码

可以看出有三个构造方法:

  • ArrayList(int initialCapacity):带有initialCapacity初始容量初始化数组大小的构造方法

  • ArrayList():无参构造方法,采用Default initial capacity. private static final int DEFAULT_CAPACITY = 10;此时的初始容量=10

  • ArrayList(Collection<? extends E> c): 集合c直接赋值给elementData元素的构造方法

增删改查

我们实际项目中,围绕ArrayList做的最多的就是增删改查相关操作,我们将细细的品一品官方的实现方式

拆入元素

单个元素拆入

先看单个插入元素add(E e)


    /**
     * 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) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    
复制代码

从源码中可看出ensureCapacityInternal(size + 1);是确保数组内部容量足以满足本次插入操作;elementData[size++] =
e;是在尾部进行数组的赋值。然后看一下ensureCapacityInternal的具体实现

    private void ensureCapacityInternal(int minCapacity) {
        //判断元素是否是初始化时的DEFAULTCAPACITY_EMPTY_ELEMENTDATA空数组,如果是从DEFAULT_CAPACITY, minCapacity里面取最大值进行赋值给minCapacity
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        //判断一下是否够,不够就扩容
        ensureExplicitCapacity(minCapacity);
    }
复制代码

ensureExplicitCapacity是否需要扩容的方法

    private void ensureExplicitCapacity(int minCapacity) {
        //点击进去看到这个是夫类AbstractList定义用来记录数组修改次数的
        modCount++;

        // overflow-conscious code 根据即将加入的元素和已经加入的元素的数量-存放元素的数组大小判断是否还有剩余,大于0代表加入元素大于存放元素的大小则需要扩容
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
复制代码

grow扩容方法

    private void grow(int minCapacity) {
        // overflow-conscious code
       //旧容量大小 
        int oldCapacity = elementData.length;
        //新容量大小=旧容量大小 +旧容量大小的位运算=1.5*旧容量大小,这里用位元素是因为效率高
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //新容量大小-即将加入的元素和已经加入的元素的数量大小,则新容量大小取大的值,这里就是一个取最大值赋值
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        //下面的MAX_ARRAY_SIZE,private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;    
        //新容量大小大于数组的最大容量值,则会出现内存不足的情况,因此继续执行相关判断hugeCapacity,我们点进去看一下这里面的源码就是一个内存溢出的异常情况,还有一个设置为Integer.MAX_VALUE最大值的情况    
        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);
    }
复制代码

上面的分析就是简单的单个插入元素add(E e),我们接下来再来看一下add(int index, E element)根据下标位置进行插入元素

    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        //设置新的index的数据                 
        elementData[index] = element;
        size++;
    }
复制代码

我们要注意和上面最简单的拆入元素的区别,主要区别在于rangeCheckForAdd(index)、还有System.arraycopy(elementData, index, elementData, index + 1, size –
index)、elementData[index] = element;;我们先来讲一下System.arraycopy()

System.arraycopy方法

    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);
复制代码
  • 第一个参数是要被复制的数组
  • 第二个参数是被复制的数字开始复制的下标
  • 第三个参数是目标数组,也就是要把数据放进来的数组
  • 第四个参数是从目标数据第几个下标开始放入数据
  • 第五个参数表示从被复制的数组中拿几个数值放到目标数组中

从上面可以得知,是从index位置开始复制到index+1的位置,即index位置的所有数据右移,然后我们再来揭开rangeCheckForAdd(index)的神秘面纱

    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
复制代码

主要是判断index是否下标越界,其实还是很类似的

多个元素拆入

从下面的源代码可以看出,都是上面讲解过的方法,自行分析一下就行

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


    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount

        int numMoved = size - index;
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);

        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }

复制代码

总结一下拆入元素的逻辑就是:数组下标是否存在——>数组是否需要扩容——>数组插入,相关插入位置及其之后的位置右移 (不是index位置拆入的就不用考虑下标)

删除元素

根据下标删除元素

    public E remove(int index) {
        //点击进去看一下是判断index下标是否存在,不存在抛出异常
        rangeCheck(index);
        //修改数组的次数+1
        modCount++;
        //直接获取index下标的值
        E oldValue = elementData(index);
        //计算需要移动的元素数量
        int numMoved = size - index - 1;
        if (numMoved > 0)
            //index+1开始的数据都左移一位
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //数组最后一个位置设置为null,便于gc回收                     
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }
    
复制代码

根据对象删除元素


    public boolean remove(Object o) {
        //删除的值是否为null
        if (o == null) {
            //for查找到null数据的index,然后我们重点看一下fastRemove(index)
            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;
    }


复制代码

fastRemove快速删除方法,看下面的方法和remove(int index)里面的原理也是一样的

    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
    }
复制代码

根据对象删除元素其实就是根据对象找到index下标然后再去做删除,然后我们需要注意一下,如果数组里面有两个相同的元素A,我们调用remove(A),删除的是第一个A,因为是从0位置开始for循环查找index下标的

根据下标批量删除元素

    protected void removeRange(int fromIndex, int toIndex) {
        //修改数组次数+1
        modCount++;
        //需要移动的元素数量
        int numMoved = size - toIndex;
        //意思是从elementData的toIndex位置开始拿numMoved个元素复制到从fromIndex开始的位置,也就是把删除结束位置之后的元素全部左移到删除开始位置
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // clear to let GC do its work
        //计算一下删除以后新数组的大小
        int newSize = size - (toIndex-fromIndex);
        //新数组大小之后的位置的元素全部置为null,有助于gc回收
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }
复制代码

根据对象集合批量删除元素

    public boolean removeAll(Collection<?> c) {
        //判断一下删除的集合是否为空,为空抛出空指针异常
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }
复制代码

batchRemove真正的删除来了,批处理删除,注意一下这里传过来的complement=false


    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)
                //删除的元素集合里面不包含当前这个元素
                if (c.contains(elementData[r]) == complement)
                    //重新从头开始设置不包含的元素在这个数组里面的位置
                    elementData[w++] = elementData[r];
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            //删除走这里的分支
            if (w != size) {
                // clear to let GC do its work
                //将w及其之后的位置的元素置为null,回收gc
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                //修改数组次数+(size老数组大小-新数组大小)    
                modCount += size - w;
                //重新赋值新数组的大小
                size = w;
                modified = true;
            }
        }
        return modified;
    }

复制代码

我们结合一下拆入元素、删除元素,拆入元素:一个元素右移index及其之后的元素,删除元素:一个元素左移index之后的元素,对比分析有利于我们更好的理解

更新元素

    public E set(int index, E element) {
        //检验index是否合法
        rangeCheck(index);
        //拿到index位置的老数据
        E oldValue = elementData(index);
        //设置新数据
        elementData[index] = element;
        //返回老数据
        return oldValue;
    }
复制代码

查询元素

    public E get(int index) {
        //检验index是否合法
        rangeCheck(index);
        //直接取index元素数据返回
        return elementData(index);
    }
    
复制代码

我们通过整个增删改查方法的分析,可以看出ArrayList是一个增删复杂,改查方便

其他方法

像contains()、clear()这几个我们也来简单的看一下

    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
    
    //判断o元素是否存在,存在返回i,不存在返回-1,然后contains中根据>=0判断是否包含这个元素
    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
    
    //for循环,所有位置元素全部置为null
    public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }        
    
    
复制代码

线程安全问题

  • ArrayList是线程不安全的
  • Collections.synchronizedList()可实现ArrayList的线程安全
  • CopyOnWriteArrayList是线程安全的,里面通过ReentrantLock来实现的
  • Vector是通过synchronized来保证线程安全的,加锁和释放锁的时候开销大,在组合操作的时候是线程不安全的,扩容是一倍

我们要对比上面的这些相关的来便于我们理解和分析

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享