ArrayList就是一個以動態數組形式實現的集合類。所以優勢是隨機訪問元素,但是在list中間插入和移動元素時較慢。特別是插入效率。
由於要維護數組的size,即動態數組的實現就是擴容時將原數組的元素複製到更大數組中。
所以在此之前補充下複製數組元素函數,其中Arrays.copyOf()
和System.arraycopy()
的原理介紹:
數據結構
底層基於數組實現容量大小動態變化。並且元素允許 null 的存在。
其源碼如下:
/**
* 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;
初始化
有三種初始化方式(構造函數):
- 無參構造函數:
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
- 有參構造函數:指定初始容量
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);
}
}
- 有參構造函數:指定 collection 列表
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;
}
}
我們發現當初始化後集合爲空,數組則指向如下的空數組常量:
//①如果使用不帶參數的構造函數,則就用默認容量10來進行開闢空間,並且elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//②如果使用帶參數的構造函數,但是初始容量爲0,則elementData = EMPTY_ELEMENTDATA
private static final Object[] EMPTY_ELEMENTDATA = {};
兩者區別在於如何擴張數組(雖然都指向空數組,但是前者的容量爲10,後者的容量爲0),具體分析如下。
擴容
簡單來說,就是將數組擴容到渴望的數組大小minCapacity
,具體流程如下分析。
——>擴容流程:
- 首先從
ensureCapacityInternal(int minCapacity)
開始:
/**
* @param minCapacity the desired minimum capacity
*/
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
- 調用
calculateCapacity(elementData, minCapacity)
:若數組是DEFAULTCAPACITY_EMPTY_ELEMENTDATA
狀態(無參初始化狀態),則多比較下max(DEFAULT_CAPACITY, minCapacity)
,即從10開始擴容
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
- 接着,
ensureExplicitCapacity(int minCapacity)
:檢測擴容容量minCapacity
要大於elementData.length
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
grow(int minCapacity)
:開始擴容(最關鍵的部分):
- (1)每次從
1.5*oldCapacity
擴容; - (2)若
minCapacity
大於1.5*oldCapacity
, 則選minCapacity
; - (3)若擴容超過
MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8
(爲什麼選MAX_ARRAY_SIZE?),則調用hugeCapacity(int minCapacity
)選擇,最大限制的容量minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE : MAX_ARRAY_SIZE
; - (4)最後
elementData = Arrays.copyOf(elementData, newCapacity)
;複製數組到擴容後的新數組
/**
* 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);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
查找操作
1、通過索引查找元素(隨機訪問):
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
2、直接查找元素:
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
插入操作
1、插入單個元素:
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
//後移
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
2、插入集合:
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
int numMoved = size - index;
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
刪除操作
1、通過索引刪除元素:
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
2、刪除指定元素:
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
/*
* Private remove method that skips bounds checking and does not
* return the value removed.
*/
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
3、刪除部分集合:
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
//判斷元素是否需要保留
if (c.contains(elementData[r]) == complement)
//保留元素到原數組,從w=0開始
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
轉化成數組
// 返回ArrayList的Object數組
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
// 返回ArrayList元素組成的數組
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
// 若數組a的大小 < ArrayList的元素個數;
// 則新建一個T[]數組,數組大小是“ArrayList的元素個數”,並將“ArrayList”全部拷貝到新數組中
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
// 若數組a的大小 >= ArrayList的元素個數;
// 則將ArrayList的全部元素都拷貝到數組a中
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
參考:
- Java集合之ArrayList
- 【Java集合源碼剖析】ArrayList源碼剖析(jdk1.6的源碼,與jdk1.8不同)