ArrayList是最經常使用的一種集合類型。今天經過閱讀源碼的方式來加深對它的學習和理解。 ##實現接口java
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable 複製代碼
經過源碼能夠看到ArrayList繼承自AbstractList,實現了List接口、RandomAccess接口、Cloneable接口、Serializable接口。 說明它具有如下特色:數組
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
複製代碼
DEFAULT_CAPACITY 表示默認的容量是10個元素。安全
transient Object[] elementData;
private int size;
複製代碼
elementData爲實際存儲元素的數組,這裏能夠看到ArrayList的底層實際是一個數組。所以它具備數組的特色,隨機讀寫快,插入刪除慢。 transient關鍵字說明底層數組不能被序列化。 ??dom
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;
}
}
複製代碼
經過另一個集合來構造。ui
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
複製代碼
這裏能夠看到add方法是線程不安全的,由於size++操做並不是原子操做。所以也說明ArrayList類是線程不安全的類。 ensureCapacityInternal()方法保證數組容量能夠容納新增的這個元素,不會出現數組越界的狀況。this
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++;
}
複製代碼
指定index位置插入元素,其邏輯以下:spa
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;
}
複製代碼
和追加單個元素的原理相似,不一樣之處在於追加方式在於使用System.arraycopy方法。線程
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;
}
複製代碼
和插入單個元素的原理相似,不一樣之處在於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;
}
複製代碼
邏輯以下:
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;
}
複製代碼
原理簡單,就是經過遍歷的方式。可是須要注意的是,只會移除第一個找到的元素。 fastRemove方法和remove(index) 方法做用相同,只是去掉了邊界校驗和返回值。
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
複製代碼
原理就是經過數組獲取指定index的元素。
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;
}
複製代碼
並集就是addAll方法
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
複製代碼
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
複製代碼
交集和差集都調用了batchRemove方法,經過一個boolean標記來表示要留下的是相同的一部分仍是不一樣的一部分。 batchRemove方法的寫法仍是值得學習。
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)
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;
}
複製代碼
雙指針的思路,一個讀指針,一個寫指針。讀指針每次往前增長一個位置,寫指針遇到要保留的元素時,再往前移動一個位置。 最後,若是讀指針沒走到最後就異常了,那把剩下讀指針剩下的元素拷貝到寫指針以後。 若是寫指針沒到最後,說明寫指針後面的元素都須要剔除,手動置爲null,不然會內存泄露。 若是寫指針走到了最後,說明一個元素都沒有移除掉,因此返回false。