文章有點長,比較啰嗦,請耐心看完!(基于Android API 25)
一、概述
首先得明白ArrayList在數據結構中是個什么,從名字看,可以直譯為“數組集合”,內部的實現八九不離十是用數組來實現的,因此在數據結構中屬于線性表結構(0個或者多個元素的有限序列):數據的存儲和關系
是這樣:
而不是這樣的樹形的:
ArrayList內部用到了數組來做基本的數據存儲結構,那就說明是它一個連續內存塊或者存儲塊的順序存儲結構。
這樣的存儲結構是優缺點是:
優點:由于是連續的內存地址存儲塊,對于查詢一個或者多個存儲內容,就很容易了,只要找到一個元素的內容a,加上每個元素所占的內存字節數c,a+c就很容易找到下一個元素,計算量小很高效。
缺點:缺點也顯而易見,舉個栗子。
a: 你在火車站買票,這個時候,一個漂亮的主播妹紙突然插隊到你前面,你和你后面的一起排隊的人是不是都得往后退一個位置,妹紙才能插入到你的位置上吧。這個時候這一隊中需要挪動位置的人(也就是數組位置)是不是很多,當你和后面排隊的人都后退一個位置后,妹紙的插隊才算是完成了。這是不是很耗費時間。
b: 你前面的一個哥們突然不想排隊走了,空出了一個位置,這時候你和后面排隊的人是不是都得往前挪動一個位置,當所有人都挪動完后,這個隊伍才恢復原來沒有人走的情況,是不是也很耗費時間。
這優缺點要說明的是什么呢,順序存儲的線性表插入和刪除的都比較耗費時間,而查詢確非常的快。
二、源碼解析(Android API 25)
-
ArrayList的類繼承關系結構
ArrayList類繼承關系結構.png - 構造函數
/**
* Constructs an empty list with an initial capacity of ten.
* 使用10個初始容量構造一個空的集合
*/
public ArrayList() {
super();
// 用一個空的數組進行初始化
this.elementData = EMPTY_ELEMENTDATA;
}
// 來看看 elementData和EMPTY_ELEMENTDATA是什么
/**
* Shared empty array instance used for empty instances.
* 就是一個空數組常量,可是無參的構造的注釋又說是內置了10個初始容量,
* 搞不懂哪里有內置,Google的工程師注釋亂寫的么,逗我
*/
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的所有元素都存儲在elementData這個數組中,
* 并且ArrayList的容量就是這個緩存數組的長度。
* 任何一個使用elementData == EMPTY_ELEMENTDATA初始化的空的ArrayList
*(也就是用 new ArrayList()來構造一個對象的)
* 在第一次調用add方法的時候,都會被擴充容量到DEFAULT_CAPACITY
*(原來是在第一次調用add方法的時候用了默認的10作為ArrayList的容量,
* 看來Android工程師注釋不是亂寫的)
*
* Package private to allow access from java.util.Collections.
*/
transient Object[] elementData;
這樣的設計也是體現了性能的優化:
new ArrayList()構造的時候并沒有馬上的擴容去申請一堆的Object[] 數據緩存堆內存,而是等到用的時候才去申請。這個性能優化的小技巧可以學習,初始化的時候盡量少開辟還暫時不用的堆內存,等到需要使用的時候再去申請。果然Android工程師都是身經百戰的老司機啊,性能優化還的多看看源碼好啊。
/**
* 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];
}
這個構造沒啥好說的,先檢查初始化容量參數的合法性,別整個小于0的容量(不合法就拋出容量參數不合法異常,代碼邏輯嚴謹),根據指定的容量初始化緩存ArrayList數據元素的數組。
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
* 構造一個包含了參數里的集合的ArrayList
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
* 傳進來的集合如果是null的話會拋出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);
}
首先把傳進來的collection集合轉換成Object[]數組對象賦值給內部的數組緩存對象,然后初始化ArrayList的size大小,最后注釋寫c.toArray可能出錯返回的不是Object[], 判斷下如果返回的不是Object[]的類類型,就用Object[].class,復制一個Object[]類型的數組給elementData長度是size。
在使用這個構造函數初始化ArrayList的時候,需要注意的是傳遞的collection不是為null,比如使用的時候:
List<User> userList = null;
List<LoginUser> loginUserList = null;
if(null != userList) {
loginUserList =new ArrayList(userList);
}
一定得對userList進行先行的判斷,不然指不定程序在什么情況下給你來個沒女朋友、沒對象、沒媳婦的異常報錯奔潰。據騰訊Bugly報告反饋2016年Android應用奔潰最高的錯誤異常就是這個NullPointerException 沒媳婦了,java就是這么蛋疼凡是使用前都得先做下非空判斷。
- 增刪改查
- 增加
/** * Appends the specified element to the end of this list. * 追加一個元素到集合列表的末尾 * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { // 確認內部容量,并增加一次操作計數modCount ensureCapacityInternal(size + 1); // Increments modCount!! // 把新的元素賦值給緩存數組的size位置后size加一, elementData[size++] = e; return true; }
這里需要留意的是add方法并沒有判斷或者拋出一次說追加進來的e元素不能為null,ArrayList是運行add一個為null的對象的,如下圖:
// 確定內部的容量大小
private void ensureCapacityInternal(int minCapacity) {
// 當使用new ArrayList()構造ArrayList對象的時候,
// 在第一次add元素(這時候elementData還是一個空的緩存數組),
// 此時入參數minCapacity是1,以為在調用add方法的時候size+1了
if (elementData == EMPTY_ELEMENTDATA) {
// 就用DEFAULT_CAPACITY來作為最小的容量值10
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
// 再一次確定明確的容量
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
// minCapacity為10,此時elementData還沒有元素長度是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
// 從上面一路調用下來,minCapacity為10,elementData還是空的對象數組,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是個啥玩意,請看下面解釋
if (newCapacity - MAX_ARRAY_SIZE > 0)
// 當想要申請的數組容量大小超過了最大的虛擬機允許的大小,
// 就會重新計算出合適的
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
// 很顯然這里我們沒有超過,通常情況下minCapacity是比較接近size值的,
// 那么接下來就是真正的給elementData緩存數組擴容,
// Arrays.copyOf返回了一個復制好原來elementData內容的新的數組對象給elementData,
// 對于我們這樣從上門一直調用下來的情況elementData只是擴充了容量elementData.length變成了10,
// 但是這個數組里面目前還沒有元素,ArrayList的屬性size還是為0,
// 擴容完成后,我們再回過頭來看上面add(E e)方法中:
// elementData[size++] = e就很容易理解了,
// 此處e只是添加到了elementData數組的第0個位置,
// 然后size+1變成1,ArrayList.size()是1,
// 表示里面真實的元素有1個,而非里面數組的長度是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[]的類類型,于是重新實例化了一個Object[]數組對象
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
// 并把傳遞進來的original就是elementData復制到新創建的copy數組對象里,
// 這是一個jni的本地接口,因為數組的復制計算性能耗費高,
// 所以Android工程師就采用了jni底層c/c++來更高效的執行復制操作,
// 最后返回復制好的新創建的數組對象
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
// 處理巨大容量的問題
private static int hugeCapacity(int minCapacity) {
// 當前最小的容量小于0就拋出內存溢出錯誤
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
// 否則如果超過虛擬機允許的最大的數組大小,
// 就使用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
* 這是數組能夠申請最大的大小,如果試圖申請比這個還要大的大小,
* 就會超過VM虛擬機的限制而拋出內存溢出的錯誤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) {
// 檢查下需要刪除的index會不會超過size大小,
// 超過了雖然不一定會超出elementData的數組下標大小,
// 當是木有元素內容啊,沒有意義,
// 而且數組刪除內容是要移動元素位置的,容易出現問題,所以拋出了一個下標越界異常
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
// 操作計數加一
modCount++;
// 臨時緩存下要被刪除的元素對象
E oldValue = (E) elementData[index];
// 表示刪除一個元素數組需要移動的個數
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
// 緩存數組size-1的位置的引用置空,交給GC來管理內存
elementData[--size] = null; // clear to let GC do its work
// 返回被刪除的元素對象
return oldValue;
}
(畫的這么丑也好意思貼出來,真是表臉),
①、調用remove(1)方法時,index為1,如圖假設我們ArrayList的容量是10,元素有5個即size為5。
②、計算后,numMove為3。
③、通過System.arraycopy來copy移動elementData數組,b為需要移動的元素,移動到a(也就是覆蓋了index為1的值)。
④、元素少了一個size減一,移動后elementData[4]的元素就沒用了騰出來了,置為null后交給GC去處理內存。
最后返回被刪除的舊元素對象。
注意事項:從上面可以看出,調用remove方法的時候,size是變動的,所以一下邊遍歷邊刪除就會出現問題:
邊遍歷邊刪除.png
執行結果
對應的值錯亂了。解決方案:改用迭代器來刪除。
// 刪除集合中的指定的一個元素
public boolean remove(Object o) {
// 當指定的元素為null時
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;
}
```
從上面源碼可以看出,這個remove方法只是刪除遍歷的時候第一個與入參對象相等的元素,如下圖所示:

> 注意事項:add了null的元素后,RecyclerView出現了空白項item的問題,所以數據在設置到適配器前得做非空檢查

```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方法就很簡單了,把遍歷把緩存數組中有元素部分遍歷置空,size也為0后交給GC處理。
- 修改
public E set(int index, E element) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
// 保存修改前舊的元素對象
E oldValue = (E) elementData[index];
// 直接賦值修改index下標對應的緩存數組里的元素
elementData[index] = element;
// 返回修改前舊的元素對象
return oldValue;
}
```
- **查詢**
```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} 下標邊界值異常
*/
public E get(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
// 很簡單直接獲取緩存數組對應下標的元素對象
return (E) elementData[index];
}
```
通常我們查詢遍歷ArrayList的時候還會用到迭代器:
```java
Iterator<String> iterator = dataList.iterator();
while (iterator.hasNext()){
String item = iterator.next();
System.out.println("item_iterator = " + item);
}
來看看內部的實現:
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;
// 游標值表示下一個元素的index下標
int cursor; // index of next element to return
// 表示當前遍歷到了哪一個元素的index下標,如果沒有了就為-1
int lastRet = -1; // index of last element returned; -1 if no such
// 操作計數器
int expectedModCount = modCount;
public boolean hasNext() {
// 如果下一個index小于當前具體的元素個數(初始值是集合的size,使用迭代器來add、remove元素的時候會被修改)表示集合中還有下一個元素返回true,否則為false
return cursor < limit;
}
@SuppressWarnings("unchecked")
public E next() {
// 操作計數器不相等,拋出并發修改值異常(ArrayList是一個線程不安全的線性表,
// 不同線程都操作一個ArrayList對象會出現線程同步問題)
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
// 臨時存儲游標值
int i = cursor;
// 如果游標值大于等于現有的元素個數,拋出沒有此元素異常
if (i >= limit)
throw new NoSuchElementException();
// 賦值給一個新的Object數組對象,避免全局的elementData被修改
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();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
try {
// 使用ArrayList的remove方法刪除當前遍歷位置的元素
ArrayList.this.remove(lastRet);
// 回退當前的游標值
cursor = lastRet;
// 當前遍歷的元素已經被刪除了index不存在則為-1
lastRet = -1;
expectedModCount = modCount;
// 集合可被遍歷的元素個數值減一
limit--;
} catch (IndexOutOfBoundsException ex) {
// 刪除元素的時候,當前遍歷的元素大于等于集合的size則拋出異常,
// 不過這里不太明白,為什么是拋出并發修改異常,
// 估計是只有不同線程同時在做remove,
// 或者add操作的時候由于size的變動而導致lastRet>=size的情況,
// maybe暫且這么理解吧,希望有知道的小伙伴們告知留言
throw new ConcurrentModificationException();
}
}
}
三、總結
- ArrayList是線性表中的順序存儲結構的順序表,因為內部維護的是一個數組,數組是一個擁有連續存儲地址的存儲塊。
- ArrayList因為內部維護的是一個數組,查詢和修改的效率很高,但是插入添加和刪除的效率比較低,特別是數據量大的情況下必較明顯。
- 在使用普通的for循環遍歷ArrayList的時候刪除其中的元素容易出現數據刪除錯亂問題,改用Iterator迭代器能夠很好的解決這個問題。
- ArrayList在添加元素的時候是允許加入null元素的,為了避免后續使用數據時出現NullPointerException的異常,請先對要添加的元素做非空判斷。
-
ArrayList從上面的源碼分析可以看出,它可以添加重復的元素對象,所以在添加對象的時候做好相等對象的判斷。
添加重復元素對象.png - 從上面源碼可以看出,ArrayList的size和真實申請的堆內存對象容量不同,所以在使用的時候控制好ArrayList的容量使用也是很好的性能優化手段。
- ArrayList的是線程不安全的,在多線程環境下需要注意對象數據同步問題。