Java中ArrayList底層實現原理(JDK1.8)源碼分析

簡介:

  ArrayList是我們開發中非常常用的數據存儲容器之一,其底層是數組實現的,我們可以在集合中存儲任意類型的數據,ArrayList是線程不安全的,非常適合用於對元素進行查找,效率非常高。

線程安全性:

  對ArrayList的操作一般分爲兩個步驟,改變位置(size)和操作元素(e)。所以這個過程在多線程的環境下是不能保證具有原子性的,因此ArrayList在多線程的環境下是線程不安全的。

源碼分析:

/**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] 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 == EMPTY_ELEMENTDATA will be expanded to
     * DEFAULT_CAPACITY when the first element is added.
     */
    private transient Object[] elementData;

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

擴展:什麼是序列化
序列化是指:將對象轉換成以字節序列的形式來表示,以便用於持久化和傳輸。
實現方法:實現Serializable接口。
然後用的時候拿出來進行反序列化即可又變成Java對象。

transient關鍵字解析
Java中transient關鍵字的作用,簡單地說,就是讓某些被修飾的成員屬性變量不被序列化。
有了transient關鍵字聲明,則這個變量不會參與序列化操作,即使所在類實現了Serializable接口,反序列化後該變量爲空值。

那麼問題來了:ArrayList中數組聲明:transient Object[] elementData;,事實上我們使用ArrayList在網絡傳輸用的很正常,並沒有出現空值。
原來:ArrayList在序列化的時候會調用writeObject()方法,將size和element寫入ObjectOutputStream;反序列化時調用readObject(),從ObjectInputStream獲取size和element,再恢復到elementData。

那爲什麼不直接用elementData來序列化,而採用上述的方式來實現序列化呢?
原因在於elementData是一個緩存數組,它通常會預留一些容量,等容量不足時再擴充容量,那麼有些空間可能就沒有實際存儲元素,採用上訴的方式來實現序列化時,就可以保證只序列化實際存儲的那些元素,而不是整個數組,從而節省空間和時間。

2.構造方法分析

根據initialCapacity 初始化一個空數組,如果值爲0,則初始化一個空數組:

/**
     * 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) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }

不帶參數初始化,默認容量爲10:

/**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        super();
        this.elementData = EMPTY_ELEMENTDATA;
    }

通過集合做參數的形式初始化:如果集合爲空,則初始化爲空數組:

/**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }

3.主幹方法

add(E 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;
    }

看到它首先調用了ensureCapacityInternal()方法.注意參數是size+1,這是個面試考點

private void ensureCapacityInternal(int minCapacity) {
        if (elementData == EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

這個方法裏又嵌套調用了兩個方法:計算容量+確保容量
計算容量:如果elementData是空,則返回默認容量10和size+1的最大值,否則返回size+1

計算完容量後,進行確保容量可用:(modCount不用理它,它用來計算修改次數)
如果size+1 > elementData.length證明數組已經放滿,則增加容量,調用grow()。

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

增加容量:默認1.5倍擴容。
獲取當前數組長度=>oldCapacity
oldCapacity>>1 表示將oldCapacity右移一位(位運算),相當於除2。再加上1,相當於新容量擴容1.5倍。
如果newCapacity&gt;1=1,1&lt;2所以如果不處理該情況,擴容將不能正確完成。
如果新容量比最大值還要大,則將新容量賦值爲VM要求最大值。
將elementData拷貝到一個新的容量中。

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

size+1的問題

好了,那到這裏可以說一下爲什麼要size+1。
size+1代表的含義是:
如果集合添加元素成功後,集合中的實際元素個數。
爲了確保擴容不會出現錯誤。
假如不加一處理,如果默認size是0,則0+0>>1還是0。
如果size是1,則1+1>>1還是1。有人問:不是默認容量大小是10嗎?事實上,jdk1.8版本以後,ArrayList的擴容放在add()方法中。之前放在構造方法中。我用的是1.8版本,所以默認ArrayList arrayList = new ArrayList();後,size應該是0.所以,size+1對擴容來講很必要.

 

ArrayList優缺點

優點:
因爲其底層是數組,所以修改和查詢效率高。
可自動擴容(1.5倍)。
缺點:
插入和刪除效率不高。
線程不安全。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章