JDK源码剖析之ArrayList浅析

ArrayList概述

        下文用昵称“小A”表示ArrayList的一个实例:)

        ArrayList是一个实现了List接口的大小可变的数组,可类比于Vector,但是ArrayList是unsynchronized(非同步的),而Vector类是synchronized(同步的)。获取ArrayList信息的一些方法比如size()、isEmpty()、get()、set()、iterator()、listIterator()运行的时间复杂度是O(1),即常数时间。add()操作在摊还分析下运行的时间复杂度也是O(1)(关于摊还分析可参考《算法导论》第三版第17章“摊还分析”里的内容),一般而言我们添加n个元素到小A中的时间复杂度是O(n)。剩下的其他操作运行的时间复杂度是O(n)。

        小A有属性capacity代表小A存储元素用到的空间大小。当然单位不是字节,而是元素的个数。小A还有一个属性size表示小A实际拥有的元素数量,而总是有capacity>=size。实际上capacity表示的就是小A能装多少元素的能力,而size则是已经装了多少,就像龙夫山泉矿泉水瓶最多能装capacity为600ml水,而现在只有size为300ml的水在瓶子里面。在向小A中添加元素的时候,capacity会自动增长。在向小A中添加大量元素之前,我们可以使用ensureCapacity()操作提升小A的capacity值,以避免小A扩容时大量的内存空间再分配。

        最后,ArrayList可是JAVA Collections Framework的成员。

ArrayList源码分析

        ArrayList扩展了AbstractList,实现了接口List、RandomAccess、Cloneable、java.io.Serializable。但是我们不分析其继承的一些特性,只分析我们常用而由容易忽略的内容。

ArrayList定义了一个默认的初始容量:

/**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;
我们大多数在使用ArrayList的时候,如果不指定容量,默认就是10。
其内部声明了一个数组:

transient Object[] elementData;
elementData就是ArrayList实际存储元素的地方,实际上ArrayList的容量capacity就是这个数组elementData的长度。

定义了size表示其拥有的元素数量:

/**
     * The size of the ArrayList (the number of elements it contains).
     * @serial
     */
    private int size;
定义了两个静态变量表示空的数组分别是EMPTY_ELEMENTDATA和DEFAULTCAPACITY_EMPTY_ELEMENTDATA:

/**
     * 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 = {};
EMPTY_ELEMENTDATA用于容量为0的空数组,当elementData的capacity或者size为0的时候elementData可能就会指向EMPTY_ELEMENTDATA,而DEFAULTCAPACITY_EMPTY_ELEMENTDATA用于默认容量为10的空数组,也就是说我们在调用默认构造函数new了一个ArrayList对象之后,并不是马上就会分配10个元素大小的数组elementData,而是会让成员变量elementData指向DEFAULTCAPACITY_EMPTY_ELEMENTDATA,直到有一个元素被添加到ArrayList,elementData才会指向被分配默认容量大小的数组。
接下来我们分析最长用到的两个构造函数:

public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {// 如果外部设定的容量大于0,则分配指定容量的数组
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {// 如果传入的容量为0,则让elementData指向EMPTY_ELEMENTDATA
            this.elementData = EMPTY_ELEMENTDATA;
        } else {// 传入的容量为负数,则抛出异常
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
我们用的最多的是ArrayList(),即默认构造函数,调用这个函数并不会真正的分配一个默认空间大小的数组,而仅仅是让内部的数组引用elementData指向DEFAULTCAPACITY_EMPTY_ELEMENTDATA。当然这也是一种懒人的策略,只有等到我们真正的插入元素的时候才会分配数组。但是如果当我们在创建ArrayList对象之前就已经大概知道有多少元素需要存储,就不能一味地使用无参的ArrayList(),而必须要使用ArrayList(int)指定创建数组的初始大小,再new出ArrayList对象的一开始,就分配好空间。这样做的好处是会避免大量的空间开辟、元素复制的开销——因为ArrayList内部是用的数组做的缓存,其实其并不能真正的动态扩容,当元素在elementData数组中存放不下的时候,ArrayList只有重新开辟一块内存空间,然后再把原数组里的内容依次拷贝过来,最后让elemetnData指向新的数组,如果这样的操作太过频繁,其开销是非常巨大的。所以,在使用ArrayList的时候,我们得考虑是否能优先使用ArrayList(int capacity)而不是直接闷头使用ArrayList()。

接下来我们分析trimToSize():

public void trimToSize() {
        modCount++;// 修改操作计数加
        if (size < elementData.length) {// 当然只有size小于才会执行接下来的操作
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }
这函数的目的是将当前容量裁剪到和元素数量一致。首先是让修改操作计数加1.然后判断size和数组的大小,如果size小于数组的大小则进一步进行判定。接下来是一个三元表达式,如果size已经为0,则让elemetData指向哨兵对象EMPTIY_ELEMENTDATA,如果不是,则重新分配一个和当前元素数量相同的数组给elementData。
我们再分析ensureCapacity(int mincapacity):

public void ensureCapacity(int minCapacity) {
        if (minCapacity > elementData.length
            && !(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
                 && minCapacity <= DEFAULT_CAPACITY)) {
            modCount++;
            grow(minCapacity);
        }
    }
这个函数是保证我们随便向ArrayList中添加元素而不用担心内存管理的关键,也就是ArrayList容量自动增长的关键。如果满足条件则会调用grow(int)增长elemetnData的容量。而grow(int)函数就是直接分配新的空间给elementData.

private Object[] grow(int minCapacity) {
        return elementData = Arrays.copyOf(elementData,
                                           newCapacity(minCapacity));
    }
private int newCapacity(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity <= 0) {
            if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
                return Math.max(DEFAULT_CAPACITY, minCapacity);
            if (minCapacity < 0) // overflow
                throw new OutOfMemoryError();
            return minCapacity;
        }
        return (newCapacity - MAX_ARRAY_SIZE <= 0)
            ? newCapacity
            : hugeCapacity(minCapacity);
    }
而newCapacity则会根据传入的minCapacity重新计算真正的容量。其扩容的策略是,设置新的容量newCapacity为原有容量的1.5倍。然后判断newCapacity和minCapacity的大小,如果我们传入的minCapcity比其默认的扩容策略要大则返回我们指定的容量,当然这里会考虑到一些异常和溢出的判断。如果newCapacity比minCapacity大,那么就会进入三元表达式,首先如果newCapacity不大于的最大值MAX_ARRAY_SIZE,直接返回newCapcity,如果超过了设定的最大容量则由hugeCapcity函数重新指定容量大小。

private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE)
            ? Integer.MAX_VALUE
            : MAX_ARRAY_SIZE;
    }
hugeCapcity(int)也只是简单地将minCapacity和MAX_ARRAY_SIZE做个比较,然后返回合适的大小。
接下来我们分析contains(Object o):

public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
contains()函数判定一个对象是否在数组中,其调用的是indexOf()函数,查找对象在数组中的下标,如果下标大于等于0,则说明数组中包含这个元素。
我们看indexOf(Object o)函数:

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;
    }
这个函数的时间复杂度为O(n)。因为是从第一个元素开始遍历数组中所有的元素,如果有一个元素和传入的对象匹配,那么就返回对应的下标值。在最坏的情况下就是根本没有匹配的元素,那么就会返回-1。

我再看和indexOf(Object)相似的函数lastIndexOf(Object o):

public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
其代码执行的逻辑和indexOf完全一致,只不过其是从最后一个元素开始遍历。

我们再看get(int)函数:

/**
     * 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) {
        Objects.checkIndex(index, size);
        return elementData(index);
    }
使用get()函数比起我们在使用数组时直接使用下标访问元素要安全得多,因为get()首先会进行下标合法性的检查。因为是直接通过下标访问的元素,所以get()函数执行的效率是非常高的,即O(1)的时间复杂度。

我们再看set(int, element)函数:

/**
     * 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) {
        Objects.checkIndex(index, size);
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
这个函数的实现代码很简单,不过要注意的是,在使用中不小心就会造成下标越界。正如注释里所说,这个函数是替换指定位置上的元素,而且这个元素的位置必须小于size。有时候我们在设置ArrayList的容量capacity之后(此时数组的大小为capacity),size为0,使用set函数设置元素的话,对于elementData本身是不存在越界问题的。但是set函数检查的边界是以size为准,这样就会越界。所以我们在使用set()函数的时候,一定要保证传入的下标是小于size的。

我们再看add()函数:

private void add(E e, Object[] elementData, int s) {
        if (s == elementData.length)
            elementData = grow();
        elementData[s] = e;
        size = s + 1;
    }

public boolean add(E e) {
        modCount++;
        add(e, elementData, size);
        return true;
    }

public void add(int index, E element) {
        rangeCheckForAdd(index);
        modCount++;
        final int s;
        Object[] elementData;
        if ((s = size) == (elementData = this.elementData).length)
            elementData = grow();
        System.arraycopy(elementData, index,
                         elementData, index + 1,
                         s - index);
        elementData[index] = element;
        size = s + 1;
    }

这三个add()函数都是类似的,基本思路就是添加元素的时候判断当前容量是否足够,如果不足够则分配新的内存空间。

然后我们看下几个移除函数的源码:

/**
     * 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) {
        Objects.checkIndex(index, size);

        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
     * {@code i} such that
     * {@code Objects.equals(o, get(i))}
     * (if such an element exists).  Returns {@code true} 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 {@code true} 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
    }
首先看remove(int index)函数,其实就是简单的将数组中指定位置右侧的所有元素向左依次移动一个位置,覆盖掉指定位置index的元素,然后将末尾元素的引用设置为null让GC去回收其指向的独享,最后size减1。

然后看remove(Object o),这个函数首先需要根据传入的对象在数组中知道其首次出现的位置,如果找到的话就调用fastRemove(int index)将其移除,其实fastRemove(int index)和remove(int index)是一样的,只不过少了边界检查且并不返回被移除的值,毕竟这是内部的一个私有函数。

最后我们看clear()函数:

**
     * Removes all of the elements from this list.  The list will
     * be empty after this call returns.
     */
    public void clear() {
        modCount++;
        final Object[] es = elementData;
        for (int to = size, i = size = 0; i < to; i++)
            es[i] = null;
    }
所谓的clear()函数就是遍历数组中所有的元素,然后简单地将其设置为null,最后由GC去回收数组元素指向的对象。

ArrayList的源码就简单地分析到此。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值