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

相關文章
相關標籤/搜索