java 源碼閱讀(二) ArrayList
ArrayList是一種變長集合類,基於數組實現。ArrayList允許空值和重複元素。當往ArrayList中添加的元素數量超過底層數量時,會進行擴容。ArrayList實現了RandomAccess接口,所以可以保證在O(1)複雜度下完成隨機查找操作。是一個非線程安全類,併發環境下,會出現錯誤。
實現/繼承的類和接口
extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable
構造函數
transient Object[] elementData;
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final int DEFAULT_CAPACITY = 10;
private int size;
protected transient int modCount = 0;
1.ArrayList()
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
初始化了一個空的數組對象。
2.ArrayList(int initialCapacity)
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);
}
}
如果參數值大於0,則初始化一個長度爲initialCapacity的數組。否則初始化一個空數組。爲負時拋出異常。
add(E)
新建一個ArrayList對象,然後插入數據,進入到**add(E)**方法.
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
此時size爲0,進入到ensureCapacityInternal()方法。
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
minCapacity =10,進入到ensureExplicitCapacity()。
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
modCount = 1,minCapacity - elementData.length > 0 成立,進入**grow()**方法
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);
}
newCapacity = 0,小於minCapacity,newCapacity = minCapacity,然後進入**Arrays.copyOf()**方法返回一個新的數組,這個數組長度爲newCapacity ,也就是10。
返回**add()**方法,elementData[size++] = e ,然後直接返回true。添加一個元素成功。
add(int,E)
初始化一個長度爲10的數組,然後向指定索引插入元素。
public static void main(String[] args) {
ArrayList arrayList = new ArrayList(10);
arrayList.add(0);
arrayList.add(10);
arrayList.add(1, 2);
}
進入**add(int,E)**方法
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++;
}
進入rangeCheckForAdd(index);
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
size爲2,驗證通過。進入 ensureCapacityInternal(size + 1);
然後通過System.arraycopy(elementData, index, elementData, index + 1,size - index);方法,將後面的數據後移一位。
elementData[index] = element,將指定位置的數據變成要插入的數據。
擴容機制
public class StringTest {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList(10);
for (int i = 0; i < 11; i++) {
arrayList.add(10);
}
System.out.println(arrayList.size());
System.out.println(getCapacity(arrayList));
}
public static Integer getCapacity(ArrayList list) {
Integer length = 0;
Class<? extends ArrayList> aClass = list.getClass();
Field f;
try {
f = aClass.getDeclaredField("elementData");
f.setAccessible(true);
Object[] o = (Object[]) f.get(list);
length = o.length;
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
return length;
}
}
11
15
最後arrayList的長度爲11,容量爲15。
核心部分爲:
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
if (minCapacity - elementData.length > 0) 條件成立,此時就進入grow方法進行擴容。
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);
}
**int newCapacity = oldCapacity + (oldCapacity >> 1);**我們可以看出,新的數組大小是原來的1.5倍。
remove(int)
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;
}
fastRemove(int)
快速刪除,並沒有進行邊界檢查等操作。在調用的方法內部會有校驗。
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
}
remove(Object)
代碼邏輯比較簡單,此處不再贅述
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;
}
trimToSize()
arrayList刪除大量元素後,會有一部分內存空間被空閒,我們可以調用該方法,將數組容量進行縮小,從而節省空間。
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
例子:
public class StringTest {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList(10);
for (int i = 0; i < 200; i++) {
arrayList.add(10);
}
System.out.println(getCapacity(arrayList));
for (int i = 199; i > 100; i--) {
arrayList.remove(i);
}
System.out.println(getCapacity(arrayList));
arrayList.trimToSize();
System.out.println(getCapacity(arrayList));
}
public static Integer getCapacity(ArrayList list) {
Integer length = 0;
Class<? extends ArrayList> aClass = list.getClass();
Field f;
try {
f = aClass.getDeclaredField("elementData");
f.setAccessible(true);
Object[] o = (Object[]) f.get(list);
length = o.length;
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
return length;
}
}
244
244
101