ArrayList(一)原始碼分析
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); } } 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; } }
(3)元素儲存
a. set(int index, E element) 用指定的元素替換該列表中指定位置的元素。
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
b. add(E e) 將指定元素追加到該列表的末尾。
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
c. add(int index, E element) 將指定元素插入該列表中的指定位置。將當前位置上的元素(如果有)和其他元素移到右邊(將一個元素新增到它們的索引中)。
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++; }
d. addAll(Collection<? extends E> c) 將指定集合中的所有元素附加到該列表的末尾,以便由指定集合的迭代器返回它們。如果在執行過程中修改指定的集合,則此操作的行為是未定義的。(這意味著如果指定的集合是這個列表,而且這個列表是非空的,這個呼叫的行為是未定義的。)
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;
}
e. addAll(int index, Collection<? extends E> c) 將指定集合中的所有元素插入該列表,從指定位置開始。將當前位置上的元素(如果有)和其他元素移到右邊(增加它們的索引)。新元素將出現在列表中,它們由指定集合的迭代器返回。
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;
}
(4)元素讀取
get(int index)
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
(5)元素刪除
ArrayList提供了兩種刪除方法,一種通過下標刪除,一種通過指定物件刪除。
a. remove(int index) : 將元素移到該列表中的指定位置。將後面的元素移到左邊(從它們的索引中減去一個),並返回被移除的元素。
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;
}
b. remove(Object o) : 從這個列表中刪除指定元素的第一個出現,如果它存在的話。如果列表中不包含元素,那麼它是不變的
public boolean remove(Object o) {
if (o == null) { // 由於ArrayList中允許存放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;
}
首先通過程式碼可以看到,當移除成功後返回true,否則返回false。remove(Object o)中通過遍歷element尋找是否存在傳入物件,一旦找到就呼叫fastRemove移除物件。為什麼找到了元素就知道了index,不通過remove(index)來移除元素呢?因為fastRemove跳過了判斷邊界的處理,因為找到元素就相當於確定了index不會超過邊界,而且fastRemove並不返回被移除的元素。下面是fastRemove的程式碼,基本和remove(index)一致。
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
}
c. removeRange(int fromIndex, int toIndex) : 從這個列表中刪除索引之間的所有元素
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
(6)調整陣列容量
從上面介紹的向ArrayList中儲存元素的程式碼中,我們看到,每當向陣列中新增元素時,都要去檢查新增後元素的個數是否會超出當前陣列的長度,如果超出,陣列將會進行擴容,以滿足新增資料的需求。陣列擴容通過一個公開的方法ensureCapacity(int minCapacity)來實現。在實際新增大量元素前,我也可以使用ensureCapacity來手動增加ArrayList例項的容量,以減少遞增式再分配的數量。
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table
? 0
// larger than default for default empty table. It's already
// supposed to be at default size.
: DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
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);
}
MAX_ARRAY_SIZE
要分配的陣列的最大大小。一些vm在陣列中保留一些標題字。嘗試分配更大的陣列可能會導致OutOfMemoryError:請求的陣列大小超過VM限制
要注意的是在jdk1.6中 每當陣列滿了,擴容是通過算術運算子運算,從jdk1.7開始,擴容是通過位運算來操作(預設擴充套件1.5倍),提高了效率。
從上述程式碼中可以看出,陣列進行擴容時,會將老陣列中的元素重新拷貝一份到新的陣列中,每次陣列容量的增長大約是其原容量的1.5倍。這種操作的代價是很高的,因此在實際使用時,我們應該儘量避免陣列容量的擴張。當我們可預知要儲存的元素的多少時,要在構造ArrayList例項時,就指定其容量,以避免陣列擴容的發生。或者根據實際需求,通過呼叫ensureCapacity方法來手動增加ArrayList例項的容量。
trimToSize() 將這個 ArrayList 例項的容量作為列表的當前大小。應用程式可以使用此操作來最小化 ArrayList 例項的儲存。
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
由於elementData的長度會被拓展,size標記的是其中包含的元素的個數。所以會出現size很小但elementData.length很大的情況,將出現空間的浪費。trimToSize將返回一個新的陣列給elementData,元素內容保持不變,length和size相同,節省空間。
(7)將列表轉為靜態資料
ArrayList 提供了兩個 toArray 方法:
a. 呼叫Arrays.copyOf將返回一個數組,陣列內容是size個elementData的元素,即拷貝elementData從0至size-1位置的元素到新陣列並返回。
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
b. 如果傳入陣列的長度小於size,返回一個新的陣列,大小為size,型別與傳入陣列相同。所傳入陣列長度與size相等,則將elementData複製到傳入陣列中並返回傳入的陣列。若傳入陣列長度大於size,除了複製elementData外,還將把返回陣列的第size個元素置為空。
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}