ArrayList是什麼
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
// ...
}
- 繼承AbstractList - 說明本身數據結構是列表
- 實現List, RandomAccess, Cloneable, Serializable 這幾個接口 - 說明支持List中的各種常用方法
我們通過一個日常使用的例子來說明:
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
System.out.println(list.size());
list.remove(0);
System.out.println(list.isEmpty());
System.out.println(list.get(0));
}
打印結果:
2
false
2
- 添加1,2
- 打印
list.size()
結果 - 移除第0位的值
- 打印
list.isEmpty()
結果 - 打印第0位的值
上面是我們常見的使用方法,既然ArrayList的名字裏面有Array
,它的底層數據結構也是一個數組,那麼我們應該也可以指定初始數組的大小
List<Integer> list = new ArrayList<>(20);
這樣子的話list的初始大小就是20了。
我們到源碼裏面看看:
// 1
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);
}
}
// 2
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
// 3
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;
}
}
ArrayList一共有3個不同的構造方法:
- 第一個是傳入一個int型的值作爲初始化容量
- 第二個則是無參構造方法,大小爲默認值
- 第三個是傳入一個集合,通過
toArray()
方法把集合轉成數組,再添加到ArrayList中
這裏出現了幾個常量:
// 默認的初始化容量大小爲10
private static final int DEFAULT_CAPACITY = 10;
// 空數組
private static final Object[] EMPTY_ELEMENTDATA = {};
// 用於無參構造方法調用時的空數組
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
那麼問題來了:
EMPTY_ELEMENTDATA 和 DEFAULTCAPACITY_EMPTY_ELEMENTDATA 區別是什麼?
看起來都是空數組,爲什麼要創建兩個空數組對象呢?
ArrayList構造方法
其實答案在上面的3個構造方法裏面就有了:
調用有參構造方法但是傳入的初始大小爲0,這個時候elementData
都是EMPTY_ELEMENTDATA
,也就是說,EMPTY_ELEMENTDATA
代表的就是大小爲0的空數組。
調用無參構造方法,那麼初始值爲:DEFAULTCAPACITY_EMPTY_ELEMENTDATA
,這個對象在後面進行擴容的時候需要用到,我們可以看看源碼:
// 2
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
// 1
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
// 3
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
在調用add()
方法添加元素的時候,第一步就是調用ensureCapacityInternal()
方法來確保有足夠的容量。而在 calculateCapacity()
中判斷當前數組是否爲DEFAULTCAPACITY_EMPTY_ELEMENTDATA
,按照我們上面說的,調用無參構造方法創建ArrayList,那麼這裏就是true,因此需要返回一個默認值(10)和傳入值之間的最大值,作爲數組的容量。
我們從創建說起:
- 調用無參構造方法,此時數組爲
DEFAULTCAPACITY_EMPTY_ELEMENTDATA
,大小爲0 - 調用add()方法,發現當前是
DEFAULTCAPACITY_EMPTY_ELEMENTDATA
,於是在10和1(list.size() + 1)之間返回最大值,也就是10 - 此時10>0,調用grow()方法進行擴容
因此ArrayList在調用無參構造方法創建對象的時候,他的初始數組大小也是爲0,只有在調用add()方法添加元素的時候纔會擴容到默認大小10。
所以這兩個空數組對象看起來是一樣的,但是實際作用完全不同,一個確實是爲空,另外一個只是暫時爲空,真正用到的時候再擴容。
ArrayList擴容機制
一般的數組其容量大小是固定的,也就是說我初始化了一個大小爲10的數組,那麼當我添加了10個元素,要再添加第11個的時候,數組就會拋出數組越界異常(ArrayIndexOutOfBoundsException)。但是ArrayList則不會。它能夠實現自動擴容,具體是怎麼做到的呢?
Read the Fxxking Source Code!
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//1
int newCapacity = oldCapacity + (oldCapacity >> 1);
//2 判斷擴容1.5倍之後的容量大小和最小需要的容量大小,如果擴容後還是小於後者,那麼就取後者。簡單來說就是取兩者之中最大值。
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//3 再判斷是不是比最大容量大,如果是的話調用hugeCapacity()
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
//4.複製到新的數組
elementData = Arrays.copyOf(elementData, newCapacity);
}
注意這裏有一行代碼:int newCapacity = oldCapacity + (oldCapacity >> 1);
通過位運算來進行擴容。右移一位相當於除以2,但是位運算的效率要高很多。這一行代碼的意思就是擴容1.5倍。然後再進行數組的複製。
然後我們再看看hugeCapacity()
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
如果最小需要容量大於ArrayList定義的最大容量,那麼就返回Integer.MAX_VALUE,否則返回MAX_ARRAY_SZIE。
System.arraycopy() 和 ArrayList.copyOf()
在上面擴容方法的最後,我們看到複製數組用到的方法是: Arrays.copeOf(),而System.arraycopy()也能實現複製數組的功能。這兩個方法有什麼區別呢?
Arrays.copyOf()
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
System.arraycopy()
* @param src the source array.
* @param srcPos starting position in the source array.
* @param dest the destination array.
* @param destPos starting position in the destination data.
* @param length the number of array elements to be copied.
* @exception IndexOutOfBoundsException if copying would cause
* access of data outside array bounds.
* @exception ArrayStoreException if an element in the <code>src</code>
* array could not be stored into the <code>dest</code> array
* because of a type mismatch.
* @exception NullPointerException if either <code>src</code> or
* <code>dest</code> is <code>null</code>.
*/
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
可以看到,在Arrays.copyOf()的內部其實也調用了System.arraycopy()。
這兩者的區別就是:
- Arrays.copyOf() 不需要傳入目標數組,因爲它會返回一個新的數組。
- System.arrayCopy() 則是可以自己指定需要複製的數組,也就是說我們可以用這個方法進行數組元素的快速移動:例如刪除某個元素之後,把剩餘元素全部向前移動一位。就可以用數組複製的方法來實現。
ArrayList的內部類
ArrayList中有4個內部類:
(1)private class Itr implements Iterator
(2)private class ListItr extends Itr implements ListIterator
(3)private class SubList extends AbstractList implements RandomAccess
(4)static final class ArrayListSpliterator implements Spliterator
其中ListItr
是 Itr
的子類,並且重寫了以下幾個方法:
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
public boolean hasPrevious() {
return cursor != 0;
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[lastRet = i];
}
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
checkForComodification();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
- hasPrevious:判斷是否有前驅結點
- nextIndex: 下一個節點的索引值
- previousIndex: 上一個節點的索引值
- previous: 返回前一個節點
- set: 修改當前索引的值(當前索引用 lastRet來表示,調用next()方法的時候會修改lastRet)
- add: 在ArrayList末尾添加元素
總結
我們通過對ArrayList的源碼分析,大概瞭解了ArrayList的底層數據結構,以及它實現的接口和提供API。由於ArrayList是基於數組來實現的,所以它更適用於頻繁查詢的場景,因爲數組可以直接通過下標在O(1)時間複雜度內找到對應的值/對象。而插入或者刪除則需要O(n) 的時間複雜度。因爲需要移動數組的其他元素。因此不適用於頻繁插入/刪除的場景。
另外要注意的就是ArrayList的擴容機制。通過位運算來提高效率。
最後在ArrayList中還提供了幾個內部類,通過迭代器的模式實現了類似鏈表的前驅後繼節點功能,可以通過next()/previous() 來獲得相鄰的值。