Java ArrayList 源碼分析


ArrayList

  • 當處理確定長度的大量數據時,如果數據更多的只是用來瀏覽,那麼可以使用 ArrayList 來記錄數據或數據索引位置,這樣雖然增刪慢但是查找元素變得很快。
  • 原因是因爲 ArrayList 的底層是數組實現的,那麼具體是怎會實現的呢?

1. API 中的變量

	private static final long serialVersionUID = 8683452581122892189L;

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

    /**
     * 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;
類型 變量 說明
long DEFAULT_CAPACITY 初始默認變量,設定爲10
int[] EMPTY_ELEMENTDATA 給空對象使用的數組
Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA 給指定了大小的對象使用的數組
Object[] elementData 給其他非空對象使用的數組
  • 細心的人就會發現了,除了最重要的非空數組 elementData 是 default 修飾詞,其他的變量都是 private 修飾的,在 elementData 後面註釋的 non-private to simplify nested class access 是指默認訪問權限可以簡化嵌套類訪問過程,又是什麼意思呢?

a. 默認訪問權限爲什麼可以簡化嵌套類訪問過程?

i. 什麼是嵌套類?

  • 在 Java 語言中允許在另外一個類中定義一個類,這樣的類被稱爲嵌套類(Nested Class),包含嵌套類的類稱爲外部類(Outer Class),也可以叫做封閉類,詳見:Java 的內部類
  • 嵌套類分爲兩類:
  • 靜態嵌套類(Static Nested Classes):使用 static 聲明,一般稱爲 嵌套類(Nested Classes)
  • 非靜態嵌套類(Non-static Nested Classes ):非 static 聲明,一般稱爲內部類(Inner Classes);
class OuterClass {
    //外部類
    static class StaticNestedClass {
        //嵌套類
    }

    class InnerClass {
        //內部類
    }
}
  • 嵌套類作爲外部類的一個成員,可以被聲明爲 private public protected 或者包範圍(即 default),而外部類只能被聲明爲 public 或者包範圍,詳見:Java 的權限修飾符
  • 嵌套類是它的外部類的成員,非靜態嵌套類(內部類)可以訪問外部類的其他成員,而靜態嵌套類只能訪問外部類的靜態成員,包括靜態私有成員和靜態非私有成員;

ii. 嵌套類的訪問過程是怎樣的?

  • 內部類在編譯時是獨立的一個類,類名爲 外部類$內部類(根據 Java 語言規範 ,$ 只用在生成的代碼中,或者用來訪問歷史遺留系統中的預置名稱),並且與外部類處於同一個包下,如前文所說,外部類只能被聲明爲 public 或者包範圍,所以內部類可以訪問到外部類;
  • 下面比較一下內部類訪問外部類的私有與非私有方法,先確定實驗代碼塊:
public class Test {
    private int test;
    //int test;
    
    class Inner {
        void access() {
            System.out.println(test);
        }
    }

    public static void main(String[] args) {
        new Test().new Inner().access();
    }
}
  • 通過代碼對比工具 Diffchecker 對比不同的 Test$Inner.class 發現,含有 private 的字節碼文件多了一個域,這個域其實是一個靜態的訪問方法,用於獲取 private 修飾的變量 test,內部類通過訪問外部類中的這個靜態方法來實現訪問私有字段的目的;
  • 由此可見,在訪問私有變量時,編譯器需要在外部類中生成靜態訪問方法,同時也需要在內部類訪問外部類字段時調用合成的方法;

iii. 總結

  • 原因簡單來說就是非 private 修飾會簡化內部類訪問該字段的過程,以此來提高性能,當然也犧牲了一些安全性,這個原理設計到反編譯到彙編級別的內容;

2. API 中的構造方法

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

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_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();
        if ((size = elementData.length) != 0) {
            // defend against c.toArray (incorrectly) not returning Object[]
            // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
構造方法 說明
public ArrayList() 構造一個初始容量爲10的空列表
public ArrayList(int initialCapacity) 構造一個指定初始容量的空列表
public ArrayList(Collection c) 構造一個包含指定集合元素的列表,按迭代器返回的順序

3. API 中的主要方法

    /**
     * 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
     * @throws OutOfMemoryError if minCapacity is less than zero
     */
    private Object[] grow(int minCapacity) {
        int oldCapacity = elementData.length;
        if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            int newCapacity = ArraysSupport.newLength(oldCapacity,
                    minCapacity - oldCapacity, /* minimum growth */
                    oldCapacity >> 1           /* preferred growth */);
            return elementData = Arrays.copyOf(elementData, newCapacity);
        } else {
            return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
        }
    }

    private Object[] grow() {
        return grow(size + 1);
    }

    /**
     * Returns the number of elements in this list.
     *
     * @return the number of elements in this list
     */
    public int size() {
        return size;
    }
    
    /**
     * This helper method split out from add(E) to keep method
     * bytecode size under 35 (the -XX:MaxInlineSize default value),
     * which helps when add(E) is called in a C1-compiled loop.
     */
    private void add(E e, Object[] elementData, int s) {
        if (s == elementData.length)
            elementData = grow();
        elementData[s] = e;
        size = s + 1;
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        modCount++;
        add(e, elementData, size);
        return true;
    }
  • 每次用 add() 方法增加新元素時,如果長度夠用,那麼會直接插入的對應位置,否則會新創建一個最小的、滿足條件的長度的數組;
  • 可見 ArrayList 本質就是增加了很多方法的數組;

4. 鏈接

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