Java集合(一)-ArrayList源码解析

ArrayList是什么?

ArrayList是Java集合中的一份子,它的内部结构实为数组并封装了一些方法和特性方便使用者,为什么不用数组呢?因为ArrayList更加方便:如果你再不确定元素个数的情况下创建一个数组,那么在数组容量不够的情况下需要手动扩容(也就是重新初始化一个数组),但是在ArrayList中会在内部自动扩容。ArrayList的特性还很多,都是为了使用方便,在下面的讲解中你们可以边看边细细思考。

我们通过源码的方式来讲解ArrayList以便于让你更加深入地学习。

构造器

ArrayList提供三个构造器,分别提供于无参初始化、指定容量初始化、指定提供元素的集合参数初始化:

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

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定义了三个数组来根据不同的情况创建数组,我们可以看到数组类型是 Object 类型。
第一个构造器需要传入一个 int 型的变量来规定初始化数组的大小,在构造函数里会对你传入的值进行检测,若果大于0的话就用 elementData 来初始化,注意,这是一个反序列化变量;如果你传入的大小是0的话用初始化好的容量为0的EMPTY_ELEMENTDA

第二个构造器是默认无参的构造器,它会创建一个长度为0的 Object 数组存储元素,也就是 DEFAULTCAPCITY_EMPTY_ELEMENT数组。

第三个构造器是传入一个一个集合对象来初始化 ArrayList 的,它会将传入元素的元素全部复制给 ArrayList ,我们可以看到,如果传入集合不为空的话会调用 Arrays.copyOf() 方法将元素复制到 ArrayList() 方法中,那么这个 Arrays.copyOf() 方法是干什么的呢?看看源码:

    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() 方法,这是一个本地方法,是用C/C++写的,就不做赘述了。

属性 DEFAULT_CAPACITY 和 size:

    /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

这两个属性容易混淆,size值是指容器中时间有多少个元素;

DEFAULT_CAPACITY 表达的是 ArrayList 中存储元素的 Object 数组的默认长度,但它不代表你的容器容量,也不是说你的容器在初始化的时候容量都是10。在上面的构造器中我们能看到如果在传入容量大小的构造其中传入0的话它和默认无参的构造器使用的数组不是一个数组,为什么呢?

在源码开头 ArrayList 定义了三个数组来根据不同的情况存储元素:

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

elementData 是在传入的容量值不为 0 或者传入的集合不为空的时候用来存储元素的;

DEFAULTCAPCITY_EMPTY_ELEMENTDATA 是在调用默认无参构造函数的时候用来储存元素的;

EMPTY_ELEMENT 是用来在传入容量之为 0 或者传入集合为空的时候用来储存元素的;

为什么要分开存储 DEFAULTCAPCITY_EMPTY_ELEMENTDATA 和 EMPTY_ELEMENT 呢都用一个数组来存储不好吗?

这是因为要根据你的初始化方式不同来踩去不同的扩容机制,如果你使用的是默默人无参构造函数的话,就会用DEFAULTCAPCITY_EMPTY_ELEMENTDATA 存储元素,那么在第一次调用 add() 方法的时候就会进行扩容,这个时候刚才讲到的 DEFAULT_CAPACITY 就派上用场了,会将 ArrayList 的容量扩容为 DEFAULT_CAPACITY 的值也就是 10 。

但是如果你是用传入容量大小的构造器传入 0 值或者是使用传入集合的构造器传入一个空集合时会用 EMPTY_ELEMENT 存储元素,这样的话在第一次调用 add() 方法的时候会默认按照它的扩容机制进行第一次扩容,而不是向上面那样第一次扩容直接扩容到 10。

接下来我们就讲讲 add() 方法和它的扩容机制:

方法 add():

add() 方法分为两种情况:一种是直接在数组尾部插入一个元素;一种是在指定下标处插入元素;

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

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

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

rangeCheck() 方法是为在指定下标处插入元素时检查下表是否合法;

从上面的源码中可以看到两种 add() 方法在进行插入操作前都会调用 ensureCapcityIntermal(size+1) 方法,没错这个方法就是检查在假如一个元素后容器容量(也就是数组的长度)是否够用,如果不够用会调用 grow() 方法来扩容:

    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }

    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

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

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            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;
        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)calculateCapcity() 根据初始化使用的构造器计算容器应有容量,如果是使用默认无参构造器并且是第一次扩容的话那么返回容量大小是10,否则返回现在的size+1;

(2)EnsureExplicitCapcity() 判断计入一个元素后容量是否够用;

(3)grow() 如果容量不够用就进行扩容,在方法中可以看到默认扩容大小是现在容量的2/3,也就是每次增加现在容量的1/2。

在第一次扩容的时候如果使用的是默认无参构造函数,会将容量置为 10;若传入容量为 0 或者传入空集合来初始化的话,容量增长为 1。

还有一点要注意的是:如果在扩容之后的容量超出了 ArrayList 规定的最大容量,也就是上面的 MAX_ARRAY_SIZE 常量的话,那么就调用 hugerCapcity() 方法返回一个 Integer 能保存的最大值来作为容量。

到此为止,关于 ArrayList 的扩容机制就讲完了,关于最上面为什么要根据构造器的不同来用两个都是空的 Object 数组存储元素大家也就知道是为什么了吧!

方法 remove():

remove() 方法也分为两种情况:一种是根据下标删除对应的元素;一种是根据元素值删除所匹配到的第一个元素:

    /**
     * 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)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        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
    }

根据下标删除元素时先判断传入的下标值是否合法,如果合法的话删除元素;而根据元素删除的时候,在元素不为null值的时候用 equals() 方法比较是否相同,如果相同的话获取此元素的下标值,再用 fastRemove() 方法根据此下标删除元素,这个方法不需要判断下标是否合法,因为所传入下标的元素一定存在。切记,按照元素删除的时候只会删除所匹配到的第一个元素,而之后相同的元素不会被删除。

ArrayList还有很多基本操作,比如:get() 和 set() 方法分别获取下标处的元素和修改下标处的元素;clear() 元素清空ArrayList容器等等,如果对ArrayList还有兴趣,大家就去看看源码吧!

本人是小白大学生一枚,如有不对或者不当之处,请各位前辈指教。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值