1. 程式人生 > >java集合: ArrayList源碼淺析

java集合: ArrayList源碼淺析

const hat 序列化 nal ref tca 添加 進行 position

ArrayList 是一個動態數組,線程不安全 ,允許元素為null。

ArrayList的數據結構是數組,查詢比較方便。

ArrayList類的接口

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

RandomAccess:RandmoAccess是一個標記接口,用於被List相關類實現。他主要的作用表明這個相關類支持快速隨機訪問。在ArrayList中,我們即可以通過元素的序號快速獲取元素對象——這就是快速隨機訪問。除了List的“快速隨機訪問”,還可以“通過Iterator叠代器訪問”。
Cloneable:實現該接口的類可以對該類的實例進行克隆(按字段進行復制)。
Serializable:ArrayList支持序列化,能通過序列化去傳輸。

構造方法

ArrayList(),初始化的時候,先分配一個空數組。添加一個元素時,容量就會擴展到DEFAULT_CAPACITY,也就是10。

   /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_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. * * 初始化的時候,分配一個空數組。添加一個元素時,容量就會擴展到DEFAULT_CAPACITY,也就是10。 * 關鍵字transient表示屬性不會被序列化。
*/ transient Object[] elementData; // non-private to simplify nested class access /** * Default initial capacity.
* 默認容量為10
*/ private static final int DEFAULT_CAPACITY = 10;

往ArrayList中添加數據的方法add() 如下:

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

擴容時,ensureCapacityInternal()方法內部調用的是grow()方法。

數組擴容。如果插入數據時容量不夠,就將容量擴大為1.5倍。
擴容的過程就是數組拷貝 Arrays.copyOf的過程,每一次擴容就會開辟一塊新的內存空間和數據的復制移動
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) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
// 左移一位表示原來的0.5倍,以下是將容量擴大為1.5倍
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); }

get(int index)方法很簡單,就是檢查一下小心數組越界,然後根據下標返回數組元素

    /**
     * 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) {
        rangeCheck(index);

        return elementData(index);
    }    

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

參考博客 :

https://www.jianshu.com/p/02f8696bf4cf

java集合: ArrayList源碼淺析