ArrayList源码分析

基于jdk1.8

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

继承自AbstractList,实现了List RandomAccess Cloneable Serializable这些接口

属性

serialVersionUID

private static final long serialVersionUID = 8683452581122892189L;

DEFAULT_CAPACITY

默认大小: 

private static final int DEFAULT_CAPACITY = 10;

构造器初始化使用的数组: 

private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
private static final Object[] EMPTY_ELEMENTDATA = {};

区别在于第一个元素添加时候不同

elementData

//一个数组elementData用来装载对象的
transient Object[] elementData; // non-private to simplify nested class access

elementData数组用来存储ArrayList中的元素,从这个可以看出,ArrayList是底层是借组于数组来实现的。

transient用来表示一个域不是该对象序行化的一部分,当一个对象被序行化的时候,transient修饰的变量的值是不包括在序行化的表示中的。但是ArrayList又是可序行化的类,elementData是ArrayList具体存放元素的成员,用transient来修饰elementData,岂不是反序列化后的ArrayList丢失了原先的元素?原理在于readObjct方法和writeObject方法。ArrayList在序列化的时候会调用writeObject,直接将size和element写入ObjectOutputStream;反序列化时调用readObject,从ObjectInputStream获取size和element,再恢复到elementData。 为什么不直接用elementData来序列化,而采用上诉的方式来实现序列化呢?原因在于elementData是一个缓存数组,它通常会预留一些容量,等容量不足时再扩充容量,那么有些空间可能就没有实际存储元素,采用上诉的方式来实现序列化时,就可以保证只序列化实际存储的那些元素,而不是整个数组,从而节省空间和时间。

size

属性用来记录ArrayList中存储的元素的个数。

private int size;

构造方法

指定容量作为参数的构造函数

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() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

源码上介绍的功能为:构造一个初始容量为 10 的空列表。即当我们不提供参数而new一个对象时,底层的数组就是直接用长度为10的空常量数组DEFAULTCAPACITY_EMPTY_ELEMENTDATA进行实例化。

此时DEFAULTCAPACITY_EMPTY_ELEMENTDATA的长度我们还不知道呀,从哪里可以看到是构造了一个初始容量为10的空列表呢?这里我们先不解释,在下面的add(E e)函数源码的介绍中会给出答案。

Collection作为参数的构造函数

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

从源码可以看到,将容器Collection转化为数组赋给数组elementData,还对Collection转化是否转化为了Object[]进行了检查判断。如果Collection为空,则就将空的常量数组对象EMPTY_ELEMENTDATA赋给了elementData;

方法

add(E e)

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

从源码可以看出,如果elementData==DEFAULTCAPACITY_EMPTY_ELEMENTDATA,则就用默认容量10来进行开辟空间。这里的源码就解释了DEFAULTCAPACITY_EMPTY_ELEMENTDATA数组和EMPTY_ELEMENTDATA数组的区别之所在。也给出了当我们用无参构造函数来实例化一个对象时,确实是构造的一个长度为10的数组对象。

private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

涉及到grow函数

/**
     * 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;
        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);
    }

从源码中可以看到,此函数的功能就是一个数组的扩张。一般情况下是扩展到原来数组长度的1.5倍。 
但是,由于扩张1.5倍可能和我们的需要不一致,即可能太小,也可能太大。因此,就有了源码中的两个if条件的处理。即如果扩张1.5倍太小,则就用我们需要的空间大小minCapacity来进行扩张。如果扩张1.5倍太大或者是我们所需的空间大小minCapacity太大,则进行Integer.MAX_VALUE来进行扩张。

以下是hugeCapacity的代码

private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

上面grow函数中最后一条语句elementData = Arrays.copyOf(elementData, newCapacity);的功能就是将原来的数组中的元素复制扩展到大小为newCapacity的新数组中,并返回这个新数组。Arrays.copyOf(elementData, newCapacity)的源码如下:

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

 看到了另外一个类System中的arraycopy这个函数,下面我们也看下源码具体是怎么实现拷贝的。文档上此函数的说明如下:

 public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

原想看下这个函数的源码的,发现这个函数时一个原生态(即native)的方法。

add(int index,E element)

今天到这,明天继续。

/**
     * 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!!
        //完成数组自身从index开始的所有元素拷贝到index+1开始且长度为size-index的位置上
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

设计到的方法是

/**
     * A version of rangeCheck used by add and addAll.
     */
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

这个方法可以看到就是做一个合法性数据校验

第二个方法上面已经介绍过了,判断一下,是否需要对现有的数组进行扩容。

下面是博主简单画个图表示一下后面system.arraycopy的过程

addAll(Collection<? extends E> c)

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

这个方法类似于上面的添加的方法,可以看到过程大致也是先判断是否需要扩容,完事进行数据的拷贝,更新对应的size,返回值是是否添加成功,是一个布尔值,也就是newNew是0的时候为false。

addAll(int index, Collection<? extends E> c)

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,因为是从某一个特定位置开始。然后获取传入集合的长度以及判断是否需要扩容。numMoved记录的是传入的指定位置和size大小的差值。如果大于0,那么说明是相当于先拷贝index后面长度为numNew的数据,完事将传入集合的数据赋值进入。如果是等于0,那么相当于直接拷贝整个传入集合到数组最后面。剩下的小于0,已经在校验的时候干掉了。最后更新size。返回布尔值是否添加成功。

get(int index)

public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }

该方法是返回指定位置的元素。

set(int index, E element)

public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

这里就是正常数组指定位置元素的更新,返回之前就的数据。涉及到其他一个方法rangeCheck()

 private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

可以看到该方法是做一个传入index数值的校验。如果不符合,直接抛出异常。

remove(int index)

移除ArrayList中的移除元素,包括两个函数的重载,一个是移除指定位置的元素,另一个是移除指定值的元素。

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

该方法是移除指定位置的元素。

过程类似于add,采用拷贝的方式,返回移出位置的数据。拷贝元素是将index之后的元素全部向前拷贝过去。里面记录了一个值是modCount++,是继承于AbstractList。

这个成员变量记录着集合的修改次数,也就每次add或者remove它的值都会加1。在使用迭代器遍历集合的时候同时修改集合元素。因为ArrayList被设计成非同步的,所以理所当然会抛异常。

remove(Object o)

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

大体上了来看首先判断传入的对象是否为null,处理过程的区别在于是如果是null采用的是“==”,对于不是null的对象采用的是equals方法,但都是从头开始找到第一个符合要求的元素,然后删除。最后如果没有找到对应的元素,那么返回false。

那么我们看看fastRemove方法。

 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
    }

首先更新modCount,完事执行拷贝动作。与remove(index)的区别在于没有进行对传入参数的合法性校验,以及没有返回移除的旧值,因为传入的object就是对应的旧值。

clear()

public void clear() {
        modCount++;

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

        size = 0;
    }

更新modCount,然后将elementData每一个位置的元素置为null,更新size。直接将数组中的所有元素设置为null即可,这样便于垃圾回收。

剩下的方法如

这些就不一一列举了。

clone方法

public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

可以看到调用的super的clone方法。

下面再来看一个方法

retainAll(Collection<?> c)

public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

    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
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }

从列表中移除未包含在指定collection中的所有元素。首先调用的是Objects的方法判断传入参数是否为空,如果为空,那么抛出空指针异常。然后调用私有方法batchRemove(),将相同元素放到集合前面,执行完将原来集合数据覆盖掉了就。整个retainAll就是将两个集合去交集,将相同的部分元素放入第一个集合当中。

为此博主画了一个简单前面的过程的示意图。

测试方法的demo如下:

package demo;

import java.util.ArrayList;
import java.util.List;

public class Demo {
	
	public static void main(String[] args) {

        List<String> list1 = new ArrayList<String>();
        List<String> list2 = new ArrayList<String>();
        List<String> list3 = new ArrayList<String>();
        for (int i = 0; i < 20; i++) {
            list1.add(i+"");
            if(i%2 == 0) {
                list2.add(i+"");
            }
            list3.add(i+"@");
        }
        System.out.println("list1=" +list1);
        System.out.println("list2=" +list2);
        System.out.println("list3=" +list3);
        // list1 与 list2 存在相同元素,list1集合只保留list2中存在的元素
        list1.retainAll(list2);
        System.out.println("list1=" +list1);
        if(list1.isEmpty()) {
            System.out.println("不包含");
        } else {
            System.out.println("包含");
        }
        System.out.println(list1);
        // list1 与 list3 不存在相同元素,list1集合变为空
        list1.retainAll(list3);
        System.out.println("list1=" +list1);
        if(list1.isEmpty()) {
            System.out.println("不包含");
        } else {
            System.out.println("包含");
        }
        System.out.println(list1);
    }
	
}

iterator方法

public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }


    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

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

具体ListItr和Itr代码就不粘贴了。

这基本就是整个ArrayList的源码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值