List是元素有序並且可以重複的集合。
List的主要實現:ArrayList, LinkedList, Vector。
1.ArryList
使用數組作爲底層數據結構
transient Object[] 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 boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
//判斷當前數組是否是默認構造方法生成的空數組,如果是的話minCapacity=10反之則根據原來的值傳入下一個方法去完成下一步的擴容判斷
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
//minCapacitt表示修改後的數組容量,minCapacity = size + 1
private void ensureCapacityInternal(int minCapacity) {
//判斷看看是否需要擴容
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
//判斷當前ArrayList是否需要進行擴容
private void ensureExplicitCapacity(int minCapacity) {
//快速報錯機制
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
ArrayList擴容的核心方法grow(),下面將針對三種情況對該方法進行解析:
1.當前數組是由默認構造方法生成的空數組並且第一次添加數據。此時minCapacity等於默認的容量(10)那麼根據下面邏輯可以看到最後數組的容量會從0擴容成10。而後的數組擴容纔是按照當前容量的1.5倍進行擴容;
2.當前數組是由自定義初始容量構造方法創建並且指定初始容量爲0。此時minCapacity等於1那麼根據下面邏輯可以看到最後數組的容量會從0變成1。這邊可以看到一個嚴重的問題,一旦我們執行了初始容量爲0,那麼根據下面的算法前四次擴容每次都 +1,在第5次添加數據進行擴容的時候纔是按照當前容量的1.5倍進行擴容。
3.當擴容量(newCapacity)大於ArrayList數組定義的最大值後會調用hugeCapacity來進行判斷。如果minCapacity已經大於Integer的最大值(溢出爲負數)那麼拋出OutOfMemoryError(內存溢出)否則的話根據與MAX_ARRAY_SIZE的比較情況確定是返回Integer最大值還是MAX_ARRAY_SIZE。這邊也可以看到ArrayList允許的最大容量就是Integer的最大值(-2的31次方~2的31次方減1)。
//ArrayList擴容的核心方法,此方法用來決定擴容量
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;
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
其中Arrays.copyOf具體實現如下:
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);//創建一個新數組,該數組的類型和之前ArrayList中元素的類型一致。
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));//System arrayCopy
return copy;
}
add(int index, E element),在指定位置插入一個對象。
指定的位置必須是存在的(0到size之間),由於ArrayList是數組實現,因此需要將插入位置之後的元素進行後移一個位置,騰出空間給新元素。因此這個方法多了一次數組複製的工作。
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++;
}
set(int index, E element),將制定位置的對象替換掉。
範圍檢索只對“上界”檢查,不對“下界”檢查???
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
刪除指定位置的對象remove(int index)。 remove(int index)和add(int index , E element)類似,需要通過數組的複製覆蓋或騰出空間。
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;
}
刪除指定對象remove(E element)
刪除指定的對象,需要對刪除對象是否爲null區別對待。如果爲null,則遍歷數組中的元素,並比較是否爲null(==null),如果爲null則調用fastRemove刪除。如果不爲null,則遍歷數組中的元素,並用equals比較是否相等,相等則調用fastRemove刪除。
fastRemove是簡化的remove(int index),不需要進行範圍檢查。
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
}
get(int index),傳入的參數的爲數組元素的位置。
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
獲取指定對象的位置,indexOf(Object o)。
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 boolean contains(Object o) {
return indexOf(o) >= 0;
}
iterator調用iterator會創建一個內部類Itr的實例(class Itr implements Iterator<E>)。主要關注hasNext、next方法。
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
Itr() {}
public boolean hasNext() {
return cursor != size;
}
比較當前指向數組的位置是否和數組中已有元素的個數相等。
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
調用next的時候要比較當前的modCount和創建iterator時的modCount是否相等。
如果不相等,則說明對集合大小產生了影響,此時拋出ConcurrentModificationException。
相等則調用get方法,此時有可能拋出IndexOutOfBoundsException,
在捕獲IndexOutOfBoundException後,檢查modCount(checkForComodification),
如果modCount不相等,拋出ConcurrentModificationException,
如果相等則拋出NoSuchElementException。
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}