ArrayList
基於數組,線程不安全,隨機存取,查詢快增刪慢,以1.5倍擴容,最大是Integer.MAX - 8
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
重點字段
// 默認容量
private static final int DEFAULT_CAPACITY = 10;
/**
* 用於有參構造函數初始化時,如果傳入的容量爲0則用其進行初始化數組
* 1.7 如果是這種情況是new一個容量爲0的數組,如果存在多個這種情況就會創建多個容量爲0的數組
* 1.8做了一定優化使其指向一個實例
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* 用於無參構造函數初始化數組,與 EMPTY_ELEMENTDATA 的區別在於
* DEFAULTCAPACITY_EMPTY_ELEMENTDATA在添加一個元素後以 DEFAULT_CAPACITY 進行擴容,擴容後 elementData.length=10
* 而 EMPTY_ELEMENTDATA 擴容後 elementData.length=1
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
// 底層封裝的數組,用於存儲元素
transient Object[] elementData; // non-private to simplify nested class access
// 集合的大小(實際存儲的元素數)
private int size;
構造函數
// 空參構造 初始化容量爲 10 的空列表
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
// 構造具有指定容量的列表 如果容量爲0則使用 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);
}
}
// 構造一個包含指定集合元素的列表 如果集合容量爲0則使用 EMPTY_ELEMENTDATA
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;
}
}
對於空參構造函數使用的是DEFAULTCAPACITY_EMPTY_ELEMENTDATA
的空數組,但是爲什麼註釋爲-“初始化容量爲 10 的空列表”?詳見擴容
對於ArrayList(Collection<? extends E> c)
爲什麼需要if (elementData.getClass() != Object[].class)
判斷然後進行轉換?
這是因爲jdk的一個bug(6260652),toArray方法返回的不一定是Object[]類型的數組,導致在調用toArray後進行數組賦值會報錯,所以構造函數中判斷不是Object[].class就會進行轉換,以下例子能夠證明:
List<String> list = new ArrayList<>(Arrays.asList("java")); // 構造器做了轉換
System.out.println(list.getClass()); // class java.util.ArrayList
Object[] objects = list.toArray();
System.out.println(objects.getClass()); // class [Ljava.lang.Object;
objects[0] = new Object();
List<String> list2 = Arrays.asList("java");
System.out.println(list2.getClass()); // class java.util.Arrays$ArrayList
Object[] objects1 = list2.toArray();
System.out.println(objects1.getClass()); // class [Ljava.lang.String;
objects1[0] = new Object(); // java.lang.ArrayStoreException: java.lang.Object
// 對於 ArrayList 的 toArray 返回的一定是Object[]
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
// 而對於 Arrays$ArrayList 的 toArray 返回的是泛型類型的數組,所以還是實際類型,這個時候將 Object 賦值給 String 就會報錯
private final E[] a;
@Override
public Object[] toArray() {
return a.clone();
}
擴容
// 增加數組的容量,確保能存儲 minCapacity 個元素
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);
}
}
如果是數組是 DEFAULTCAPACITY_EMPTY_ELEMENTDATA
實例。minExpand會被設置爲10,如果此時minCapacity小於等於minExpand,則不馬上進行擴容,而是在進行add操作時初始化一個容量爲10的空數組,所以無參構造函數的註釋才那麼寫
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
在add操作內存會調用 ensureCapacityInternal
私有方法來確保有足夠的容量放置元素,其中 calculateCapacity
判斷是否是 DEFAULTCAPACITY_EMPTY_ELEMENTDATA
實例,如果是的話並且 minCapacity 小於 DEFAULT_CAPACITY
則初始化一個容量爲10的空數組,這其實是一個延遲初始化的技巧。
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// 如果需要擴容的大小大於原容量則調用擴容方法
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
// 允許分配的最大數組大小,一些 VM 會在數組頭部儲存頭數據,試圖嘗試創建一個比 Integer.MAX_VALUE - 8 大的數組可能會產生 OOM 異常
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// 按照原容量的1.5倍進行擴容
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;
}
對於無參構造函數確實是構造了容量爲10的數組,只是不是一開始就初始化,而是使用了延遲初始化的方式,在add的時候才進行初始化。對於空參構造使用 DEFAULTCAPACITY_EMPTY_ELEMENTDATA
,而 new ArrayList(0)
使用 EMPTY_ELEMENTDATA
,前者不知道需要的容量大小,後者預估的容量比較小,所以通過不同的空數組實例使用不同的擴容算法,對於無參構造:10 ->15->22…,有參且參數爲0: 0->1->2-3->4->6->9…
存儲
// 將指定的元素追加到此列表的末尾
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++;
}
// 按指定集合的Iterator返回的順序將指定集合中的所有元素追加到此列表的末尾
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;
}
System.arraycopy()
方法
src:源數組;
srcPos:源數組要複製的起始位置
dest:目的數組;
destPos:目的數組放置的起始位置
length:複製的長度
注意:src and dest都必須是同類型或者可以進行轉換類型的數組.
有趣的是這個函數可以實現自己到自己複製
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
// 往指定角標 index 插入指定元素 element
int index = 1;
int element = 4;
int size = 3;
Integer[] elementData = new Integer[4];
elementData[0] = 1;
elementData[1] = 2;
elementData[2] = 3;
System.out.println(Arrays.toString(elementData)); // [1, 2, 3, null]
System.arraycopy(elementData, index, elementData, index + 1,
size - index); // [1, 2, 2, 3]
elementData[index] = element;
System.out.println(Arrays.toString(elementData)); // [1, 4, 2, 3]
刪除
// 刪除該列表中指定位置的元素
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;
}
// 私有的刪除方法,跳過邊界檢查,並且不會返回被刪除的值
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
}
// 從列表中刪除所有元素
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
// 從這個列表中刪除所有索引在 fromIndex (含)和 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;
}
// 從此列表中刪除指定集合中包含的所有元素
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
// 僅保留此列表中包含在指定集合中的元素
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
// 批量刪除 complement=false 刪除不包含的,=true 刪除包含的
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
// r : 從0~size-1遍歷元素每次循環遞增 w : 遇到包含(complement=true)/不包含(complement=false)的元素就自增
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
// complement=false,c包含元素則用r角標的數據覆蓋掉w角標的數據,並且r自增,w自增。否則r自增,w不動
// complement=true,c不包含元素則用r角標的數據覆蓋掉w角標的數據,並且r自增,w自增。否則r自增,w不動
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
// 把需要移除的數據都替換掉,不需要移除的數據都前移
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
// 異常流,存在併發修改的情況
if (r != size) {
// 如果存在併發刪除,則 size - r 爲負數,System.arraycopy 會報 java.lang.ArrayIndexOutOfBoundsException
// 如果存在併發添加,則將添加的元素追加到w索引後面
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
// w 是最後一個被替換的元素,其餘元素都前移了,所以把index > w的都置null,然後修改modCount和size
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;
}
removeAll例子理解
List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5, 6);
List<Integer> otherList = Lists.newArrayList(2, 4, 6);
list.removeAll(otherList);
循環次數 | r | w | if | elementData[w++] = elementData[r] | 原數組 | 替換值 | 替換後 |
---|---|---|---|---|---|---|---|
1 | 0 | 0 | true | elementData[0] = elementData[0] | 123456 | 1->1 | 123456 |
2 | 1 | 1 | false | ||||
3 | 2 | 1 | true | elementData[1] = elementData[2] | 123456 | 3->2 | 133456 |
4 | 3 | 2 | false | ||||
5 | 4 | 2 | true | elementData[2] = elementData[4] | 133456 | 5->3 | 135456 |
6 | 5 | 3 | false |
循環結束後 w == 3 從原數組的下標 3開始將下標大於3的的置空 modcount + 3 數組長度變爲 3
序列化和反序列化
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject();
// Write out size as capacity for behavioural compatibility with clone()
s.writeInt(size);
// 用的是size而不是elementData.length,說明只序列化實際存儲的元素
for (int i=0; i<size; i++) {
s.writeObject(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
elementData = EMPTY_ELEMENTDATA;
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in capacity
s.readInt(); // ignored
if (size > 0) {
// be like clone(), allocate array based upon size not capacity
int capacity = calculateCapacity(elementData, size);
SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity);
ensureCapacityInternal(size);
Object[] a = elementData;
// Read in all elements in the proper order.
for (int i=0; i<size; i++) {
a[i] = s.readObject();
}
}
}
Object[] elementData
用了 transient
修飾,代表序列化時忽略,但是他自身實現了序列化和反序列,那爲什麼還要用 transient
修飾呢?實際上,ArrayList 通過動態數組的技術,當數組放滿後,自動擴容,但是擴容後的容量往往都是大於或者等於 ArrayList 所存元素的個數。如果直接序列化 elementData 數組,那麼就會序列化一大部分沒有元素的數組,導致浪費空間,爲了保證在序列化的時候不會將這大部分沒有元素的數組進行序列化,因此設置爲 transient
jdk1.8新增的方法實現
// -> implement Iterator jdk1.8
@Override
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int expectedModCount = modCount;
@SuppressWarnings("unchecked")
final E[] elementData = (E[]) this.elementData;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
action.accept(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
// -> implement Collection jdk1.8
@Override
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
int removeCount = 0;
// BitSize使用一個Long(64位)的數組中的每一位是否爲1來標識當前index的元素是否存在
final BitSet removeSet = new BitSet(size);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
@SuppressWarnings("unchecked")
final E element = (E) elementData[i];
// 將符合filter的元素下標設置到BitSet中,即BitSet中對應的下標設置爲 1
if (filter.test(element)) {
removeSet.set(i);
removeCount++;
}
}
// 判斷是否有併發修改
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
// 判斷是否有元素需要刪除
final boolean anyToRemove = removeCount > 0;
if (anyToRemove) {
// 新數組大小
final int newSize = size - removeCount;
for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
// 返回下一個清除位(0)的索引(從本身開始)
i = removeSet.nextClearBit(i);
elementData[j] = elementData[i];
}
// 將多餘的位置空
for (int k=newSize; k < size; k++) {
elementData[k] = null; // Let gc do its work
}
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
return anyToRemove;
}
// -> implemenet List jdk1.8
@Override
@SuppressWarnings("unchecked")
public void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
elementData[i] = operator.apply((E) elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
// -> implement List jdk1.8
@Override
@SuppressWarnings("unchecked")
public void sort(Comparator<? super E> c) {
final int expectedModCount = modCount;
Arrays.sort((E[]) elementData, 0, size, c);
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
// implement List, Collection jdk1.8
@Override
public Spliterator<E> spliterator() {
return new ArrayListSpliterator<>(this, 0, -1, 0);
}
// jdk1.8
static final class ArrayListSpliterator<E> implements Spliterator<E> {
...
}
BitSet
BitSet bit = new BitSet();
bit.set(2);
bit.set(4);
bit.set(6); // [0, 0, 1, 0, 1, 0, 1]
System.out.println(Arrays.toString(bit.toLongArray())); // [84] = 4 + 16 + 64 = 84
for(int i = 0; i < 7; i++){
int i1 = bit.nextClearBit(i); // 0 1 3 3 5 5 7
// index = 0 時 bit[0] == 0 bit.nextClearBit == 0
// index = 1 時 bit[1] == 0 bit.nextClearBit == 1
// index = 2 時 bit[2] == 1 bit.nextClearBit == 3
// index = 3 時 bit[3] == 0 bit.nextClearBit == 3
// ...以此類推,當前bit[n]不爲0時就從下一位找直到找到bit[n]爲0的角標n
}
其餘方法
// 將集合大小調整爲當前實際容量
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
// 返回此列表中的元素數
public int size() {
return size;
}
// 如果此列表不包含元素,則返回 true
public boolean isEmpty() {
return size == 0;
}
// 如果此列表包含指定的元素,則返回 true
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
// 返回此列表中指定元素的第一次出現的索引,如果此列表不包含元素,則返回-1
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;
}
// 返回此列表中指定元素的最後一次出現的索引,如果此列表不包含元素,則返回-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;
}
// 以正確的順序(從第一個到最後一個元素)返回一個包含此列表中所有元素的數組
public Object[] toArray() {
return Arrays.copyOf(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;
}
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
// 返回此列表中指定位置的元素
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
// 用指定的元素替換此列表中指定位置的元素
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
public ListIterator<E> listIterator() {
return new ListItr(0);
}
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
...
}
private class ListItr extends Itr implements ListIterator<E> {
...
}
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
private class SubList extends AbstractList<E> implements RandomAccess {
...
}