天天看點

jdk源碼ArrayList

類關系圖

jdk源碼ArrayList

有些抽象類沒有展示。圖檔來源忘了,侵立删

本來想自己寫一篇的,但是發現了一個寫的比較全面的部落格

ArrayList

https://www.cnblogs.com/skywang12345/p/3308556.html

這裡記錄一下自己的了解

和Vector不同,ArrayList中的操作不是線程安全的!是以,建議在單線程中才使用ArrayList,而在多線程中可以選擇Vector或者CopyOnWriteArrayList

ArrayList的底層是array存儲object[]數組,對數組進行擴充,類的聲明和屬性

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
    private static final long serialVersionUID = L;

    /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = ;//數組初始化時的大小

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

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

因為數組不能擴容,實際開發中需要用到擴容,就有了ArrayList

擴容的大小為原來大小的1.5倍實作代碼

private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> );//這裡可以看出
        if (newCapacity - minCapacity < )
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > )
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
           

繼續閱讀