概述
ArrayList是一個以動態陣列為基礎實作的非執行緒安全性的集合,ArrayList的元素可以為空、可以重複,同時又是有序的(讀取和存放的順序一致)。
ArrayList繼承AbstractList,實作了List
、RandomAccess
(可以快速存取)、Cloneable
(可以被複製)、java .io.Serializable
(支援序列化)
更多免費相關影片推薦:java影片
ArrayList的初始化方式有三種:
1、無參構造,預設長度為10,是我們使用的最多的一種初始化方式:
/** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }
這個時候,我們從原始碼中可以看到,裡面只有一行程式碼:this.elementData = DEFAULTCAPACITY_EMPTY_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 = {};
透過註解可以得知,來源碼中定義了一個空的陣列作為預設的大小,並且在第一個元素添加進來的時候再確定把數組擴充多少,這段邏輯會在接下來添加元素部分作出解釋。
2、指定初始化長度:
/** * 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); } }
3、用一個Collection物件來建構
/** * 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) { // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } }
相關文章教學推薦:java開發入門
以上是java中的ArrayList集合的初始化方式的詳細內容。更多資訊請關注PHP中文網其他相關文章!