java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > ArrayList初始化长度的作用及影响

基于ArrayList初始化长度的作用及影响

作者:不负好时光⁡

这篇文章主要介绍了基于ArrayList初始化长度的作用及影响,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

平时写代码都直接写

List<String> list = new ArrayList<>();

由于公司做政.府项目,对并发和响应没有太苛刻的要求,平时就没有考虑到这一块。

今天看同事代码在new ArrayList<>()的时候带入初始容量,于是好奇百度一下,讲结果记录下来。

一、有无初始容量的区别

    /**
     * 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;
    
    /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;

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

    /**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};    

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

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

以上是JDK1.8的ArrayList源码,可以看出,

由此可以想到,如果存在上千上万数据量的操作,不初始容量和初始化了合适的容量,处理时间肯定不同,因为初始化和扩容是需要时间的。

测试代码如下:

public static void main(String[] args) {
    final int count = 200 * 10000;
    List<Integer> list = new ArrayList<>();
    long begin = System.currentTimeMillis();
    for(int i = 0; i < count ; i++) {
        list.add(i);
    }
    System.out.println("没有设置ArrayList初始容量: " + (System.currentTimeMillis() - begin) + " ms");

    List<Integer> list2 = new ArrayList<>(10);
    long begin2 = System.currentTimeMillis();
    for(int i = 0; i < count ; i++) {
        list2.add(i);
    }
    System.out.println("设置了ArrayList初始容量: " + (System.currentTimeMillis() - begin2) + " ms");
}

输出:

没有设置ArrayList初始容量: 96 ms
设置了ArrayList初始容量: 26 ms

分析:

在list.add()方法执行时,先调用ArrayList的:

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

进入方法:

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

再往下:

private static int calculateCapacity(Object[] elementData, int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {// 第一次add的时候,都会走这一步
        return Math.max(DEFAULT_CAPACITY, minCapacity);//初始化容量小于默认值10都会取10,反之取自定义的容量
    }
    return minCapacity;
}

扩容方法:

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) {//minCapacity是当前容量,比如,默认容量下,add一次后就是10+1
    // 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);
}

总结:

上例不同大小初始容量的耗时:

initialCapacitytime
未初始化96
<=1026
10026
100023
10000648
10000024
100000018
10000000609

二、initialCapacity != list.size()

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>(10);
    list.set(0, 666);
}

console:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:657)
    at java.util.ArrayList.set(ArrayList.java:448)
    at top.chengsw.demo.test.ListTest.main(ListTest.java:25)

此时,list.size() = 0。

也就是说,该构造方法并不是将ArrayList()初始化为指定长度,而是指定了其内部的Object数组的长度,也就是其容量。

当我们调用size()时,返回的是其实际长度,而非容量大小。

对超出ArrayList长度的部分进行访问或赋值操作时也会造成访问越界,尽管它的容量大小足够。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文