文章有點(diǎn)長(zhǎng),比較啰嗦,請(qǐng)耐心看完!(基于Android API 25)
一、概述
首先得明白ArrayList在數(shù)據(jù)結(jié)構(gòu)中是個(gè)什么,從名字看,可以直譯為“數(shù)組集合”,內(nèi)部的實(shí)現(xiàn)八九不離十是用數(shù)組來(lái)實(shí)現(xiàn)的,因此在數(shù)據(jù)結(jié)構(gòu)中屬于線性表結(jié)構(gòu)(0個(gè)或者多個(gè)元素的有限序列):數(shù)據(jù)的存儲(chǔ)和關(guān)系
是這樣:

而不是這樣的樹(shù)形的:

ArrayList內(nèi)部用到了數(shù)組來(lái)做基本的數(shù)據(jù)存儲(chǔ)結(jié)構(gòu),那就說(shuō)明是它一個(gè)連續(xù)內(nèi)存塊或者存儲(chǔ)塊的順序存儲(chǔ)結(jié)構(gòu)。

這樣的存儲(chǔ)結(jié)構(gòu)是優(yōu)缺點(diǎn)是:
優(yōu)點(diǎn):由于是連續(xù)的內(nèi)存地址存儲(chǔ)塊,對(duì)于查詢(xún)一個(gè)或者多個(gè)存儲(chǔ)內(nèi)容,就很容易了,只要找到一個(gè)元素的內(nèi)容a,加上每個(gè)元素所占的內(nèi)存字節(jié)數(shù)c,a+c就很容易找到下一個(gè)元素,計(jì)算量小很高效。
缺點(diǎn):缺點(diǎn)也顯而易見(jiàn),舉個(gè)栗子。
a: 你在火車(chē)站買(mǎi)票,這個(gè)時(shí)候,一個(gè)漂亮的主播妹紙突然插隊(duì)到你前面,你和你后面的一起排隊(duì)的人是不是都得往后退一個(gè)位置,妹紙才能插入到你的位置上吧。這個(gè)時(shí)候這一隊(duì)中需要挪動(dòng)位置的人(也就是數(shù)組位置)是不是很多,當(dāng)你和后面排隊(duì)的人都后退一個(gè)位置后,妹紙的插隊(duì)才算是完成了。這是不是很耗費(fèi)時(shí)間。
b: 你前面的一個(gè)哥們突然不想排隊(duì)走了,空出了一個(gè)位置,這時(shí)候你和后面排隊(duì)的人是不是都得往前挪動(dòng)一個(gè)位置,當(dāng)所有人都挪動(dòng)完后,這個(gè)隊(duì)伍才恢復(fù)原來(lái)沒(méi)有人走的情況,是不是也很耗費(fèi)時(shí)間。
這優(yōu)缺點(diǎn)要說(shuō)明的是什么呢,順序存儲(chǔ)的線性表插入和刪除的都比較耗費(fèi)時(shí)間,而查詢(xún)確非常的快。
二、源碼解析(Android API 25)
-
ArrayList的類(lèi)繼承關(guān)系結(jié)構(gòu)
ArrayList類(lèi)繼承關(guān)系結(jié)構(gòu).png - 構(gòu)造函數(shù)
/**
* Constructs an empty list with an initial capacity of ten.
* 使用10個(gè)初始容量構(gòu)造一個(gè)空的集合
*/
public ArrayList() {
super();
// 用一個(gè)空的數(shù)組進(jìn)行初始化
this.elementData = EMPTY_ELEMENTDATA;
}
// 來(lái)看看 elementData和EMPTY_ELEMENTDATA是什么
/**
* Shared empty array instance used for empty instances.
* 就是一個(gè)空數(shù)組常量,可是無(wú)參的構(gòu)造的注釋又說(shuō)是內(nèi)置了10個(gè)初始容量,
* 搞不懂哪里有內(nèi)置,Google的工程師注釋亂寫(xiě)的么,逗我
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == EMPTY_ELEMENTDATA will be expanded to
* DEFAULT_CAPACITY when the first element is added.
* ArrayList的所有元素都存儲(chǔ)在elementData這個(gè)數(shù)組中,
* 并且ArrayList的容量就是這個(gè)緩存數(shù)組的長(zhǎng)度。
* 任何一個(gè)使用elementData == EMPTY_ELEMENTDATA初始化的空的ArrayList
*(也就是用 new ArrayList()來(lái)構(gòu)造一個(gè)對(duì)象的)
* 在第一次調(diào)用add方法的時(shí)候,都會(huì)被擴(kuò)充容量到DEFAULT_CAPACITY
*(原來(lái)是在第一次調(diào)用add方法的時(shí)候用了默認(rèn)的10作為ArrayList的容量,
* 看來(lái)Android工程師注釋不是亂寫(xiě)的)
*
* Package private to allow access from java.util.Collections.
*/
transient Object[] elementData;
這樣的設(shè)計(jì)也是體現(xiàn)了性能的優(yōu)化:
new ArrayList()構(gòu)造的時(shí)候并沒(méi)有馬上的擴(kuò)容去申請(qǐng)一堆的Object[] 數(shù)據(jù)緩存堆內(nèi)存,而是等到用的時(shí)候才去申請(qǐng)。這個(gè)性能優(yōu)化的小技巧可以學(xué)習(xí),初始化的時(shí)候盡量少開(kāi)辟還暫時(shí)不用的堆內(nèi)存,等到需要使用的時(shí)候再去申請(qǐng)。果然Android工程師都是身經(jīng)百戰(zhàn)的老司機(jī)啊,性能優(yōu)化還的多看看源碼好啊。
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
這個(gè)構(gòu)造沒(méi)啥好說(shuō)的,先檢查初始化容量參數(shù)的合法性,別整個(gè)小于0的容量(不合法就拋出容量參數(shù)不合法異常,代碼邏輯嚴(yán)謹(jǐn)),根據(jù)指定的容量初始化緩存ArrayList數(shù)據(jù)元素的數(shù)組。
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
* 構(gòu)造一個(gè)包含了參數(shù)里的集合的ArrayList
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
* 傳進(jìn)來(lái)的集合如果是null的話會(huì)拋出NullPointerException 異常
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
首先把傳進(jìn)來(lái)的collection集合轉(zhuǎn)換成Object[]數(shù)組對(duì)象賦值給內(nèi)部的數(shù)組緩存對(duì)象,然后初始化ArrayList的size大小,最后注釋寫(xiě)c.toArray可能出錯(cuò)返回的不是Object[], 判斷下如果返回的不是Object[]的類(lèi)類(lèi)型,就用Object[].class,復(fù)制一個(gè)Object[]類(lèi)型的數(shù)組給elementData長(zhǎng)度是size。
在使用這個(gè)構(gòu)造函數(shù)初始化ArrayList的時(shí)候,需要注意的是傳遞的collection不是為null,比如使用的時(shí)候:
List<User> userList = null;
List<LoginUser> loginUserList = null;
if(null != userList) {
loginUserList =new ArrayList(userList);
}
一定得對(duì)userList進(jìn)行先行的判斷,不然指不定程序在什么情況下給你來(lái)個(gè)沒(méi)女朋友、沒(méi)對(duì)象、沒(méi)媳婦的異常報(bào)錯(cuò)奔潰。據(jù)騰訊Bugly報(bào)告反饋2016年Android應(yīng)用奔潰最高的錯(cuò)誤異常就是這個(gè)NullPointerException 沒(méi)媳婦了,java就是這么蛋疼凡是使用前都得先做下非空判斷。
- 增刪改查
- 增加
/** * Appends the specified element to the end of this list. * 追加一個(gè)元素到集合列表的末尾 * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { // 確認(rèn)內(nèi)部容量,并增加一次操作計(jì)數(shù)modCount ensureCapacityInternal(size + 1); // Increments modCount!! // 把新的元素賦值給緩存數(shù)組的size位置后size加一, elementData[size++] = e; return true; }
這里需要留意的是add方法并沒(méi)有判斷或者拋出一次說(shuō)追加進(jìn)來(lái)的e元素不能為null,ArrayList是運(yùn)行add一個(gè)為null的對(duì)象的,如下圖:

// 確定內(nèi)部的容量大小
private void ensureCapacityInternal(int minCapacity) {
// 當(dāng)使用new ArrayList()構(gòu)造ArrayList對(duì)象的時(shí)候,
// 在第一次add元素(這時(shí)候elementData還是一個(gè)空的緩存數(shù)組),
// 此時(shí)入?yún)?shù)minCapacity是1,以為在調(diào)用add方法的時(shí)候size+1了
if (elementData == EMPTY_ELEMENTDATA) {
// 就用DEFAULT_CAPACITY來(lái)作為最小的容量值10
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
// 再一次確定明確的容量
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
// minCapacity為10,此時(shí)elementData還沒(méi)有元素長(zhǎng)度是0
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
// 從上面一路調(diào)用下來(lái),minCapacity為10,elementData還是空的對(duì)象數(shù)組,oldCapacity為0
int oldCapacity = elementData.length;
// oldCapacity 的向右位移一位就是除以2的意思,newCapacity也為0
int newCapacity = oldCapacity + (oldCapacity >> 1);
// 0 - 10 < 0成立
if (newCapacity - minCapacity < 0)
// newCapacity為10
newCapacity = minCapacity;
// MAX_ARRAY_SIZE是個(gè)啥玩意,請(qǐng)看下面解釋
if (newCapacity - MAX_ARRAY_SIZE > 0)
// 當(dāng)想要申請(qǐng)的數(shù)組容量大小超過(guò)了最大的虛擬機(jī)允許的大小,
// 就會(huì)重新計(jì)算出合適的
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
// 很顯然這里我們沒(méi)有超過(guò),通常情況下minCapacity是比較接近size值的,
// 那么接下來(lái)就是真正的給elementData緩存數(shù)組擴(kuò)容,
// Arrays.copyOf返回了一個(gè)復(fù)制好原來(lái)elementData內(nèi)容的新的數(shù)組對(duì)象給elementData,
// 對(duì)于我們這樣從上門(mén)一直調(diào)用下來(lái)的情況elementData只是擴(kuò)充了容量elementData.length變成了10,
// 但是這個(gè)數(shù)組里面目前還沒(méi)有元素,ArrayList的屬性size還是為0,
// 擴(kuò)容完成后,我們?cè)倩剡^(guò)頭來(lái)看上面add(E e)方法中:
// elementData[size++] = e就很容易理解了,
// 此處e只是添加到了elementData數(shù)組的第0個(gè)位置,
// 然后size+1變成1,ArrayList.size()是1,
// 表示里面真實(shí)的元素有1個(gè),而非里面數(shù)組的長(zhǎng)度是1。
// 所以ArrayList的size和容量不一定是一樣的,是不同的概念。
elementData = Arrays.copyOf(elementData, newCapacity);
}
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
// newType我們就是Object[]的類(lèi)類(lèi)型,于是重新實(shí)例化了一個(gè)Object[]數(shù)組對(duì)象
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
// 并把傳遞進(jìn)來(lái)的original就是elementData復(fù)制到新創(chuàng)建的copy數(shù)組對(duì)象里,
// 這是一個(gè)jni的本地接口,因?yàn)閿?shù)組的復(fù)制計(jì)算性能耗費(fèi)高,
// 所以Android工程師就采用了jni底層c/c++來(lái)更高效的執(zhí)行復(fù)制操作,
// 最后返回復(fù)制好的新創(chuàng)建的數(shù)組對(duì)象
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
// 處理巨大容量的問(wèn)題
private static int hugeCapacity(int minCapacity) {
// 當(dāng)前最小的容量小于0就拋出內(nèi)存溢出錯(cuò)誤
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
// 否則如果超過(guò)虛擬機(jī)允許的最大的數(shù)組大小,
// 就使用Integer的最大值,反正使用Array的最大的值
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
* Integer的最大值減去8 = 2147483647 - 8 = 2147483639
* 這是數(shù)組能夠申請(qǐng)最大的大小,如果試圖申請(qǐng)比這個(gè)還要大的大小,
* 就會(huì)超過(guò)VM虛擬機(jī)的限制而拋出內(nèi)存溢出的錯(cuò)誤OutOfMemoryError
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
```
- **刪除**
```java
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
// 檢查下需要?jiǎng)h除的index會(huì)不會(huì)超過(guò)size大小,
// 超過(guò)了雖然不一定會(huì)超出elementData的數(shù)組下標(biāo)大小,
// 當(dāng)是木有元素內(nèi)容啊,沒(méi)有意義,
// 而且數(shù)組刪除內(nèi)容是要移動(dòng)元素位置的,容易出現(xiàn)問(wèn)題,所以拋出了一個(gè)下標(biāo)越界異常
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
// 操作計(jì)數(shù)加一
modCount++;
// 臨時(shí)緩存下要被刪除的元素對(duì)象
E oldValue = (E) elementData[index];
// 表示刪除一個(gè)元素?cái)?shù)組需要移動(dòng)的個(gè)數(shù)
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
// 緩存數(shù)組size-1的位置的引用置空,交給GC來(lái)管理內(nèi)存
elementData[--size] = null; // clear to let GC do its work
// 返回被刪除的元素對(duì)象
return oldValue;
}

(畫(huà)的這么丑也好意思貼出來(lái),真是表臉),
①、調(diào)用remove(1)方法時(shí),index為1,如圖假設(shè)我們ArrayList的容量是10,元素有5個(gè)即size為5。
②、計(jì)算后,numMove為3。
③、通過(guò)System.arraycopy來(lái)copy移動(dòng)elementData數(shù)組,b為需要移動(dòng)的元素,移動(dòng)到a(也就是覆蓋了index為1的值)。
④、元素少了一個(gè)size減一,移動(dòng)后elementData[4]的元素就沒(méi)用了騰出來(lái)了,置為null后交給GC去處理內(nèi)存。
最后返回被刪除的舊元素對(duì)象。
注意事項(xiàng):從上面可以看出,調(diào)用remove方法的時(shí)候,size是變動(dòng)的,所以一下邊遍歷邊刪除就會(huì)出現(xiàn)問(wèn)題:
邊遍歷邊刪除.png
執(zhí)行結(jié)果
對(duì)應(yīng)的值錯(cuò)亂了。解決方案:改用迭代器來(lái)刪除。
// 刪除集合中的指定的一個(gè)元素
public boolean remove(Object o) {
// 當(dāng)指定的元素為null時(shí)
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;
}
```
從上面源碼可以看出,這個(gè)remove方法只是刪除遍歷的時(shí)候第一個(gè)與入?yún)?duì)象相等的元素,如下圖所示:

> 注意事項(xiàng):add了null的元素后,RecyclerView出現(xiàn)了空白項(xiàng)item的問(wèn)題,所以數(shù)據(jù)在設(shè)置到適配器前得做非空檢查

```java
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
clear方法就很簡(jiǎn)單了,把遍歷把緩存數(shù)組中有元素部分遍歷置空,size也為0后交給GC處理。
- 修改
public E set(int index, E element) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
// 保存修改前舊的元素對(duì)象
E oldValue = (E) elementData[index];
// 直接賦值修改index下標(biāo)對(duì)應(yīng)的緩存數(shù)組里的元素
elementData[index] = element;
// 返回修改前舊的元素對(duì)象
return oldValue;
}
```
- **查詢(xún)**
```java
/**
* Returns the element at the specified position in this list.
* 返回指定位置的列表元素
*
* @param index index of the element to return 指定的位置
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc} 下標(biāo)邊界值異常
*/
public E get(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
// 很簡(jiǎn)單直接獲取緩存數(shù)組對(duì)應(yīng)下標(biāo)的元素對(duì)象
return (E) elementData[index];
}
```
通常我們查詢(xún)遍歷ArrayList的時(shí)候還會(huì)用到迭代器:
```java
Iterator<String> iterator = dataList.iterator();
while (iterator.hasNext()){
String item = iterator.next();
System.out.println("item_iterator = " + item);
}
來(lái)看看內(nèi)部的實(shí)現(xiàn):
private class Itr implements Iterator<E> {
// The "limit" of this iterator. This is the size of the list at the time the
// iterator was created. Adding & removing elements will invalidate the iteration
// anyway (and cause next() to throw) so saving this value will guarantee that the
// value of hasNext() remains stable and won't flap between true and false when elements
// are added and removed from the list.
protected int limit = ArrayList.this.size;
// 游標(biāo)值表示下一個(gè)元素的index下標(biāo)
int cursor; // index of next element to return
// 表示當(dāng)前遍歷到了哪一個(gè)元素的index下標(biāo),如果沒(méi)有了就為-1
int lastRet = -1; // index of last element returned; -1 if no such
// 操作計(jì)數(shù)器
int expectedModCount = modCount;
public boolean hasNext() {
// 如果下一個(gè)index小于當(dāng)前具體的元素個(gè)數(shù)(初始值是集合的size,使用迭代器來(lái)add、remove元素的時(shí)候會(huì)被修改)表示集合中還有下一個(gè)元素返回true,否則為false
return cursor < limit;
}
@SuppressWarnings("unchecked")
public E next() {
// 操作計(jì)數(shù)器不相等,拋出并發(fā)修改值異常(ArrayList是一個(gè)線程不安全的線性表,
// 不同線程都操作一個(gè)ArrayList對(duì)象會(huì)出現(xiàn)線程同步問(wèn)題)
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
// 臨時(shí)存儲(chǔ)游標(biāo)值
int i = cursor;
// 如果游標(biāo)值大于等于現(xiàn)有的元素個(gè)數(shù),拋出沒(méi)有此元素異常
if (i >= limit)
throw new NoSuchElementException();
// 賦值給一個(gè)新的Object數(shù)組對(duì)象,避免全局的elementData被修改
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
// 游標(biāo)值加一,便于下一次迭代器遍歷使用
cursor = i + 1;
// 取出當(dāng)前元素對(duì)象返回
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
try {
// 使用ArrayList的remove方法刪除當(dāng)前遍歷位置的元素
ArrayList.this.remove(lastRet);
// 回退當(dāng)前的游標(biāo)值
cursor = lastRet;
// 當(dāng)前遍歷的元素已經(jīng)被刪除了index不存在則為-1
lastRet = -1;
expectedModCount = modCount;
// 集合可被遍歷的元素個(gè)數(shù)值減一
limit--;
} catch (IndexOutOfBoundsException ex) {
// 刪除元素的時(shí)候,當(dāng)前遍歷的元素大于等于集合的size則拋出異常,
// 不過(guò)這里不太明白,為什么是拋出并發(fā)修改異常,
// 估計(jì)是只有不同線程同時(shí)在做remove,
// 或者add操作的時(shí)候由于size的變動(dòng)而導(dǎo)致lastRet>=size的情況,
// maybe暫且這么理解吧,希望有知道的小伙伴們告知留言
throw new ConcurrentModificationException();
}
}
}
三、總結(jié)
- ArrayList是線性表中的順序存儲(chǔ)結(jié)構(gòu)的順序表,因?yàn)閮?nèi)部維護(hù)的是一個(gè)數(shù)組,數(shù)組是一個(gè)擁有連續(xù)存儲(chǔ)地址的存儲(chǔ)塊。
- ArrayList因?yàn)閮?nèi)部維護(hù)的是一個(gè)數(shù)組,查詢(xún)和修改的效率很高,但是插入添加和刪除的效率比較低,特別是數(shù)據(jù)量大的情況下必較明顯。
- 在使用普通的for循環(huán)遍歷ArrayList的時(shí)候刪除其中的元素容易出現(xiàn)數(shù)據(jù)刪除錯(cuò)亂問(wèn)題,改用Iterator迭代器能夠很好的解決這個(gè)問(wèn)題。
- ArrayList在添加元素的時(shí)候是允許加入null元素的,為了避免后續(xù)使用數(shù)據(jù)時(shí)出現(xiàn)NullPointerException的異常,請(qǐng)先對(duì)要添加的元素做非空判斷。
-
ArrayList從上面的源碼分析可以看出,它可以添加重復(fù)的元素對(duì)象,所以在添加對(duì)象的時(shí)候做好相等對(duì)象的判斷。
添加重復(fù)元素對(duì)象.png - 從上面源碼可以看出,ArrayList的size和真實(shí)申請(qǐng)的堆內(nèi)存對(duì)象容量不同,所以在使用的時(shí)候控制好ArrayList的容量使用也是很好的性能優(yōu)化手段。
- ArrayList的是線程不安全的,在多線程環(huán)境下需要注意對(duì)象數(shù)據(jù)同步問(wèn)題。



