ArrayList集合源码

基于JDK1.7版本  java

继承和实现方法数组

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

下面看几个主要方法 add(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;
    }

arrayList 内部是基于数组实现的,每一个元素对应数组中一个值,因此还有索引0,1,2……
add方法没有加锁,ArrayList中的方法都没有加锁
ensureCapacityInternal方法app

private void ensureCapacityInternal(int minCapacity) {
        modCount++;
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

保证不会数组越界溢出 继续看grow方法dom

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

ArrayList中存放最多元素个数为MAX_ARRAY_SIZE,Integer的最大值
newCapacity = oldCapacity + (oldCapacity >> 1);这行代码是将list的空间大小设置为原来的1.5倍,后面继续判断有没有越界,this

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

最大存储空间超过Integer.MAX_VALUE以后返回MAX_ARRAY_SIZE,小于0则下标越界溢出。线程

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

总结:
一、ArrayList中实际是数组存储的数据,有0,1,2……索引;
二、最大存储不是无限的,大小为MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
三、ArrayList中的方法没有加锁,不是线程安全的。code

相关文章
相关标签/搜索