編碼到必定程度以後,但願本身進一步成長,那就只能經過閱讀源碼來提高本身。源碼不敢說是最優的實現,那也得是比較優秀的實現了。樓主將開啓本身的閱讀源碼之旅,爲了讓這段旅程能堅持更久,樓主決定從最簡單的開始。因此本篇的主角就是ArrayList、雖然網上有大量的文章,對ArrayList實現也有個總體的概念,但我依然以爲有閱讀的必要,咱們依然能夠看看有沒有什麼細節,須要咱們去注意。數組
經過構造函數,咱們來看看ArrayList定義的時候,都作了什麼操做。能夠看到源碼裏面有三個構造函數、分別以下安全
//一個Object數組,用來存儲存進來的對象,由於是Object類型的,因此ArrayList並不能存儲基本類型數據
//transient 表示序列化的時候,不將該字段進行序列化,那ArrayList什麼能夠序列化呢?能夠看看下面連接的文章
transient Object[] elementData;
//靜態常量指向一個空數組
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//靜態常量指向一個空數組
private static final Object[] EMPTY_ELEMENTDATA = {};
//無參構造函數
public ArrayList() {
//經過無參構造函數構建ArrayList,只會將數組變量指向一個空的數組。
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
傳入一個初始容量,來構建ArrayList
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
//若是傳過來的數值大於0,則建立一個大小爲傳進來參數大小的數組。
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
//若是傳過來的數值等於0,則直接將數組引用直接指向一個空數組
this.elementData = EMPTY_ELEMENTDATA;
} else {
//傳過來參數小於0,直接拋出異常
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/**
經過傳過來一個集合初始化ArrayList
*/
public ArrayList(Collection<? extends E> c) {
//將集合轉爲Object數組
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
//c.toArray 可能返回的不是Object數組,暫時不明白什麼狀況下返回的不是Object[]
if (elementData.getClass() != Object[].class)
//新建一個數組,元素複製於傳進來的集合,賦值給elementData變量
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// 傳進來集合長度爲0,則將數組初始化爲空數組
this.elementData = EMPTY_ELEMENTDATA;
}
}複製代碼
問:什麼存儲的數組被定義爲transient,ArrayList還能序列化?bash
ArrayList經過Object[]對象來存儲數據,只能存對象類型數據,不能存基礎類型。構造函數若是不傳參數則直接初始化爲空數組。傳初始化容量,則初始化爲傳入的容量的數組。傳一個集合,初始化爲集合內容。併發
/**
*增長元素到尾部
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // 確保數組長度夠長,若是不夠則擴容
//將元素放到數組中
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
//calculateCapacity() 這個函數計算最小容量。即數組爲空數組時返回10,不然爲mingCapacity
//ensureExplicitCapacity函數將進行容量判斷,如須要會進行擴容
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
/**
*計算最小容量
*若是第一次插進來數據,數組還沒初始化,則默認爲max(10,minCapacit),
*不然爲傳進來的參數
*/
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
/**
*判斷,如須要進行擴容
*/
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
//若是當前數組容量小於須要的最小容量,則擴容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**擴容函數**/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//新長度爲就長度的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
//若是1.5倍還不夠,則直接擴容到傳進來的容量
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//若是容量超過Int的最大值,有些VM會拋出異常
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
//新建一個數組,容量爲newCapacity,將就數組複製到新數組中
elementData = Arrays.copyOf(elementData, newCapacity);
}
複製代碼
往List中增長元素:app
(1)、若是List還未初始化則初始容量爲 max(10,最小須要容量)。ide
(2)、若是數組已經初始化,而且剩餘容量夠存儲,則直接將元素存在進去。函數
(3)、若是容量不夠,則擴容爲 max(原來容量1.5倍,最小須要容量)。ui
再看下往特定位置增長元素this
public void add(int index, E element) {
//這個函數裏面沒什麼東西,都是傳進來的位置index大於已經存儲的元素個數,則拋出異常。
rangeCheckForAdd(index);
//判斷容量、擴展容量的,這個上面已經有說了
ensureCapacityInternal(size + 1); // Increments modCount!!
//將index位置後面的元素日後移,空出index位置,存放新添加進來的元素
System.arraycopy(elementData, index, elementData, index + 1,size - index);
elementData[index] = element;
size++;
}複製代碼
上面爲增長單個元素的,再看看增長多個元素是怎麼處理的?其實也是差很少的編碼
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 E remove(int index) {
//若是index的位置大於目前已經存儲的元素,直接拋出異常
rangeCheck(index);
modCount++;
//拿到當前index位置的數據
E oldValue = elementData(index);
//index後面的元素都須要往前移一位,計算須要日後移動的元素的數量
int numMoved = size - index - 1;
//index後面的元素往前移
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//最後空出來的位置值爲null
elementData[--size] = null; // clear to let GC do its work
//返回舊的值
return oldValue;
}複製代碼
public boolean remove(Object o) {
//若是是null,則比較用==
if (o == null) {
for (int index = 0; index < size; index++)
//查找出爲null的元素位置index
if (elementData[index] == null) {
//刪除index位置元素。將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;
}
//刪除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
}
複製代碼
public boolean removeAll(Collection<?> c) {
//若是傳進來一個空的集合,拋出NullPointException
Objects.requireNonNull(c);
//批量刪除list中的數據
return batchRemove(c, false);
}
//***************這裏稍微要費點腦看看****************
//這個方法具體的思想就是把不刪除的元素移動到數組前頭,以後若是有元素須要被刪除,則將數組後面位置置爲null
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
//這個for循環的做用就是把不須要移除的元素複製到數組開頭
/**
例子[7,9,0,6,8]刪除[0,6],通過這個for循環的接口會是[7,9,8 ,6,8]
能夠看到三個不須要刪除的元素已經被移動數組開頭位置,w會是3,指向第一個須要須要被值null的位置
*/
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.
/**執行contains方法出現異常的狀況,假設上面的例子循環到元素6的時候出現異常
例子[7,9,0,6,8]刪除[0,6] for循環的結果仍是[7,9,0,6,8] w會是2,r會是3
*/
if (r != size) {
/**拋出異常時,循環到的位置的元素及後面的元素,再也不進行刪除,因而只有0會被刪除,這裏就是
把元素6及後面的元素往前拷貝到w的位置,結果就成爲[7,9,6,8,8]*/
System.arraycopy(elementData, r,
elementData, w,
size - r);
//w的值值爲如今列表刪除後應該剩下的元素個數,例子只刪了0一個元素,因此w=4
w += size - r;
}
//有元素被刪除,把最後的位置值爲null
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;
}
複製代碼
若是刪除指定位置,或者刪除傳入的某個對象,上面的方法1,2,則定位到元素的位置,以後將要刪除位置後面的元素往前移一位,將數組最後一個元素位置置爲null。這個應該很好理解,數組刪除元素就是移動元素。
若是刪除指定集合中的元素,則將不須要刪除的元素直接移動到數組開頭位置,異常狀況下,則移動到開頭的包括兩部分((1)異常發生位置前,不須要被刪除的元素;(2)異常發生位置後面的全部元素),以後再將數組後面不須要的位置置爲null
這個不用看代碼,有沒都知道它只能遍歷數組去查
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;
}複製代碼
/**
克隆出一個ArrayList,返回,這裏返回的對象是克隆出來的新對象,
操做新對形象,並不會影響原來的ArrayList
*/
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable throw new InternalError(e); } } /** 拷貝出一個新的數組返回 */ public Object[] toArray() { return Arrays.copyOf(elementData, size); } /** 這個方法得注意下了: (1)、傳入的數組長度比ArrayList存儲的元素個數小,則會返回一個新的數組, 傳進來的數組並不會拷貝ArrayList中的元素 (2)、傳進來的數組長度大於等於ArrayList中存儲的元素個數,則只會將ArrayList中的元素拷貝到傳進來的 數組裏面,並返回該數組 */ 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;
}複製代碼
這裏比較簡單,不過得⚠️注意下toArray(T[] a)這個方法,可能一不當心會寫出Bug。
/**
實現Iterator接口,ArrayList定義的內部類,迭代器類
*/
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
/**
這個很關鍵,modCount,上面的代碼屢次出現此變量,咱們沒作出解釋.
其實他的用處是這裏,每次修改List,modCount都會自增,
因此能夠看作是ArrayList當前數據的版本,一會會用到.
*/
int expectedModCount = modCount;
Itr() {}
/**判斷是否還有下一個值,若是遊標不等於元素個數,則還有下一個值*/
public boolean hasNext() {
return cursor != size;
}
/**
拿到下一個值*
*/
@SuppressWarnings("unchecked")
public E next() {
/**上面說的版本號,就用到這裏了,若是迭代器使用期間,
有其餘線程修改了ArrayList,那麼迭代器會直接拋出ConcurrentModificationException異常。
ArrayList是非線程安全的,迭代器採用快速失敗的方法,一旦有線程修改數據,迭代就會失敗。
*/
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() {
//lastRet 上一次返回元素位置,若是<0,說明尚未使用next遍歷,直接拋出異常
if (lastRet < 0)
throw new IllegalStateException();
//併發拋出異常
checkForComodification();
try {
//刪除指定位置的元素
ArrayList.this.remove(lastRet);
/*遊標指向被刪除元素位置,
例子:[5,7,9,6],刪除7,調next返回7後,cursor此時應該是2,指向"9"的位置,lastRet爲1,指向「7」
刪除後列表爲[5,9,6],cursor置爲1,指向「9」
*/
cursor = lastRet;
lastRet = -1;
//修改迭代器版本號
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
/**
自動遍歷遊標以後的全部元素,交給consumer去處理
*/
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
//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裏面遍歷遊標到結束位置的全部元素,交給consumer去處理
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();
}
//返回是否併發修改了ArrayList
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}複製代碼
/**實現ListIterator接口,繼承自上面的Itr 遍歷器,提供了從後往前遍歷,還有修改元素,增長元素*/
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
//往前遍歷,是否還有下一個元素
public boolean hasPrevious() {
return cursor != 0;
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
//往前遍歷,返回元素
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[lastRet = i];
}
//修改元素,直接set一個元素過來
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
//增長元素,調用add方法增長
public void add(E e) {
checkForComodification();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}複製代碼
迭代器,這裏代碼也比較簡單,要注意的主要有幾個點:(1)、ArrayList是非線程安全的,一旦有其餘線程修改了,迭代器採用快速失敗的方法,直接拋出異常。(2)、ListItertor相對Itertor,除了日後遍歷,還能夠往前遍歷。(3)、ListItertor比Itertor多了增長元素,修改元素的方法。
到此,ArrayList的代碼基本解析完畢,這裏還須要明確的幾個點:
(1)、ArrayList採用數組來存儲,數組長度是是不容許擴展的,ArrayList擴展經過,建立一個新數組,並將舊數組元素拷貝到新數組,實現擴展。
(2)、數組結構存在乎味着指定位置獲取元素,是比較快的,時間複雜度是O(1),而刪除元素、增長元素涉及元素移動,時間複雜度是O(n)。