java數(shù)據(jù)結(jié)構(gòu)ArrayList詳解
簡(jiǎn)介
ArrayList 是 java 集合框架中比較常用的數(shù)據(jù)結(jié)構(gòu)了。繼承自 AbstractList,實(shí)現(xiàn)了 List 接口。底層基于數(shù)組實(shí)現(xiàn)容量大小動(dòng)態(tài)變化。允許 null 的存在。同時(shí)還實(shí)現(xiàn)了 RandomAccess、Cloneable、Serializable 接口,所以ArrayList 是支持快速訪(fǎng)問(wèn)、復(fù)制、序列化的。
成員變量
ArrayList 底層是基于數(shù)組來(lái)實(shí)現(xiàn)容量大小動(dòng)態(tài)變化的。
/** * The size of the ArrayList (the number of elements it contains). */ private int size; // 實(shí)際元素個(gè)數(shù) transient Object[] elementData;
注意:上面的 size 是指 elementData 中實(shí)際有多少個(gè)元素,而 elementData.length 為集合容量,表示最多可以容納多少個(gè)元素。
默認(rèn)初始容量大小為 10;
/** * Default initial capacity. */ private static final int DEFAULT_CAPACITY = 10;
這個(gè)變量是定義在 AbstractList 中的。記錄對(duì) List 操作的次數(shù)。主要使用是在 Iterator,是防止在迭代的過(guò)程中集合被修改。
protected transient int modCount = 0;
下面兩個(gè)變量是用在構(gòu)造函數(shù)里面的
/** * Shared empty array instance used for empty instances. */ private static final Object[] EMPTY_ELEMENTDATA = {}; /** * Shared empty array instance used for default sized empty instances. We * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when * first element is added. */ private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
兩個(gè)空的數(shù)組有什么區(qū)別呢? We distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when first element is added. 簡(jiǎn)單來(lái)講就是第一次添加元素時(shí)知道該 elementData 從空的構(gòu)造函數(shù)還是有參構(gòu)造函數(shù)被初始化的。以便確認(rèn)如何擴(kuò)容。
構(gòu)造函數(shù)
無(wú)參構(gòu)造函數(shù)
/** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }
注意:注釋是說(shuō)構(gòu)造一個(gè)容量大小為 10 的空的 list 集合,但構(gòu)造函數(shù)了只是給 elementData 賦值了一個(gè)空的數(shù)組,其實(shí)是在第一次添加元素時(shí)容量擴(kuò)大至 10 的。
構(gòu)造一個(gè)初始容量大小為 initialCapacity 的 ArrayList
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); } }
由以上源碼可見(jiàn): 當(dāng)使用無(wú)參構(gòu)造函數(shù)時(shí)是把 DEFAULTCAPACITY_EMPTY_ELEMENTDATA 賦值給 elementData。 當(dāng) initialCapacity 為零時(shí)則是把 EMPTY_ELEMENTDATA 賦值給 elementData。 當(dāng) initialCapacity 大于零時(shí)初始化一個(gè)大小為 initialCapacity 的 object 數(shù)組并賦值給 elementData。
使用指定 Collection 來(lái)構(gòu)造 ArrayList 的構(gòu)造函數(shù)
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; } }
將 Collection 轉(zhuǎn)化為數(shù)組并賦值給 elementData,把 elementData 中元素的個(gè)數(shù)賦值給 size。 如果 size 不為零,則判斷 elementData 的 class 類(lèi)型是否為 Object[],不是的話(huà)則做一次轉(zhuǎn)換。 如果 size 為零,則把 EMPTY_ELEMENTDATA 賦值給 elementData,相當(dāng)于new ArrayList(0)。
主要操作方法解析
add 操作
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); }
由此可見(jiàn):每次添加元素到集合中時(shí)都會(huì)先確認(rèn)下集合容量大小。然后將 size 自增 1。ensureCapacityInternal 函數(shù)中判斷如果 elementData =DEFAULTCAPACITY_EMPTY_ELEMENTDATA 就取 DEFAULT_CAPACITY 和 minCapacity 的最大值也就是 10。這就是 EMPTY_ELEMENTDATA 與DEFAULTCAPACITY_EMPTY_ELEMENTDATA 的區(qū)別所在。同時(shí)也驗(yàn)證了上面的說(shuō)法:使用無(wú)慘構(gòu)造函數(shù)時(shí)是在第一次添加元素時(shí)初始化容量為 10 的。ensureExplicitCapacity 中對(duì) modCount 自增 1,記錄操作次數(shù),然后如果 minCapacity 大于 elementData 的長(zhǎng)度,則對(duì)集合進(jìn)行擴(kuò)容。顯然第一次添加元素時(shí) elementData 的長(zhǎng)度為零。那我們來(lái)看看 grow 函數(shù)。
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); }
很簡(jiǎn)單明了的一個(gè)函數(shù),默認(rèn)將擴(kuò)容至原來(lái)容量的 1.5 倍。但是擴(kuò)容之后也不一定適用,有可能太小,有可能太大。所以才會(huì)有下面兩個(gè) if 判斷。如果1.5倍太小的話(huà),則將我們所需的容量大小賦值給newCapacity,如果1.5倍太大或者我們需要的容量太大,那就直接拿 newCapacity = (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE
來(lái)擴(kuò)容。然后將原數(shù)組中的數(shù)據(jù)復(fù)制到大小為 newCapacity 的新數(shù)組中,并將新數(shù)組賦值給 elementData。
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++; } 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; }
有以上源碼可知,add(int index, E element),addAll(Collection<? extends E> c),addAll(int index, Collection<? extends E> c) 操作是都是先對(duì)集合容量檢查 ,以確保不會(huì)數(shù)組越界。然后通過(guò) System.arraycopy() 方法將舊數(shù)組元素拷貝至一個(gè)新的數(shù)組中去。
remove 操作
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 }
當(dāng)我們調(diào)用 remove(int index) 時(shí),首先會(huì)檢查 index 是否合法,然后再判斷要?jiǎng)h除的元素是否位于數(shù)組的最后一個(gè)位置。如果 index 不是最后一個(gè),就再次調(diào)用 System.arraycopy() 方法拷貝數(shù)組。說(shuō)白了就是將從 index + 1 開(kāi)始向后所有的元素都向前挪一個(gè)位置。然后將數(shù)組的最后一個(gè)位置空,size - 1。如果 index 是最后一個(gè)元素那么就直接將數(shù)組的最后一個(gè)位置空,size - 1即可。 當(dāng)我們調(diào)用 remove(Object o) 時(shí),會(huì)把 o 分為是否為空來(lái)分別處理。然后對(duì)數(shù)組做遍歷,找到第一個(gè)與 o 對(duì)應(yīng)的下標(biāo) index,然后調(diào)用 fastRemove 方法,刪除下標(biāo)為 index 的元素。其實(shí)仔細(xì)觀(guān)察 fastRemove(int index) 方法和 remove(int index) 方法基本全部相同。
get操作
public E get(int index) { rangeCheck(index); return elementData(index); }
由于 ArrayList 底層是基于數(shù)組實(shí)現(xiàn)的,所以獲取元素就相當(dāng)簡(jiǎn)單了,直接調(diào)用數(shù)組隨機(jī)訪(fǎng)問(wèn)即可。
迭代器 iterator
有使用過(guò)集合的都知道,在用 for 遍歷集合的時(shí)候是不可以對(duì)集合進(jìn)行 remove操作的,因?yàn)?remove 操作會(huì)改變集合的大小。從而容易造成結(jié)果不準(zhǔn)確甚至數(shù)組下標(biāo)越界,更嚴(yán)重者還會(huì)拋出 ConcurrentModificationException。
foreach 遍歷等同于 iterator。為了搞清楚異常原因,我們還必須過(guò)一遍源碼。
public Iterator<E> iterator() { return new Itr(); }
原來(lái)是直接返回一個(gè) Itr 對(duì)象。
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; 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(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
從源碼可以看出,ArrayList 定義了一個(gè)內(nèi)部類(lèi) Itr 實(shí)現(xiàn)了 Iterator 接口。在 Itr 內(nèi)部有三個(gè)成員變量。 cursor:代表下一個(gè)要訪(fǎng)問(wèn)的元素下標(biāo)。 lastRet:代表上一個(gè)要訪(fǎng)問(wèn)的元素下標(biāo)。 expectedModCount:代表對(duì) ArrayList 修改次數(shù)的期望值,初始值為 modCount。
下面看看 Itr 的三個(gè)主要函數(shù)。
- hasNext 實(shí)現(xiàn)比較簡(jiǎn)單,如果下一個(gè)元素的下標(biāo)等于集合的大小 ,就證明到最后了。
- next 方法也不復(fù)雜,但很關(guān)鍵。首先判斷 expectedModCount 和 modCount 是否相等。然后對(duì) cursor 進(jìn)行判斷,看是否超過(guò)集合大小和數(shù)組長(zhǎng)度。然后將 cursor 賦值給 lastRet ,并返回下標(biāo)為 lastRet 的元素。最后將 cursor 自增 1。開(kāi)始時(shí),cursor = 0,lastRet = -1;每調(diào)用一次 next 方法, cursor 和 lastRet 都會(huì)自增 1。
- remove 方法首先會(huì)判斷 lastRet? 的值是否小于 0,然后在檢查 expectedModCount 和 modCount 是否相等。接下來(lái)是關(guān)鍵,直接調(diào)用 ArrayList 的 remove 方法刪除下標(biāo)為 lastRet 的元素。然后將 lastRet 賦值給 cursor ,將 lastRet 重新賦值為 -1,并將 modCount 重新賦值給 expectedModCount。
下面我們一步一步來(lái)分析 Itr 的操作。如圖一所示,開(kāi)始時(shí) cursor 指向下標(biāo)為 0 的元素,lastRet 指向下標(biāo)為 -1 的元素,也就是 null。每調(diào)用一次 next,cursor 和lastRet 就分別會(huì)自增 1。當(dāng) next 返回 “C” 時(shí),cursor 和 lastRet 分別為 3 和 2 [圖二]。
此時(shí)調(diào)用 remove,注意是 ArrayList 的 remove,而不是 Itr 的 remove。會(huì)將 D E 兩個(gè)元素直接往前移動(dòng)一位,最后一位置空,并且 modCount 會(huì)自增 1。從 remove 方法可以看出。[圖三]。
此時(shí) cursor = 3,size = 4,沒(méi)有到數(shù)組末尾,所以循環(huán)繼續(xù)。來(lái)到 next 方法,因?yàn)樯弦徊降?remove 方法對(duì) modCount 做了修改 ,致使 expectedModCount 與 modCount 不相等,這就是 ConcurrentModificationException 異常的原因所在。從例子.png中也可以看出異常出自 ArrayList 中的內(nèi)部類(lèi) Itr 中的 checkForComodification 方法。
異常的解決:
直接調(diào)用 iterator.remove() 即可。因?yàn)樵谠摲椒ㄖ性黾恿?expectedModCount = modCount 操作。但是這個(gè) remove 方法也有弊端。
- 1、只能進(jìn)行remove操作,add、clear 等 Itr 中沒(méi)有。
- 2、調(diào)用 remove 之前必須先調(diào)用 next。因?yàn)?remove 開(kāi)始就對(duì) lastRet 做了校驗(yàn)。而 lastRet 初始化時(shí)為 -1。
- 3、next 之后只可以調(diào)用一次 remove。因?yàn)?remove 會(huì)將 lastRet 重新初始化為 -1
總結(jié)
ArrayList 底層基于數(shù)組實(shí)現(xiàn)容量大小動(dòng)態(tài)可變。 擴(kuò)容機(jī)制為首先擴(kuò)容為原始容量的 1.5 倍。如果1.5倍太小的話(huà),則將我們所需的容量大小賦值給 newCapacity,如果1.5倍太大或者我們需要的容量太大,那就直接拿 newCapacity = (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE
來(lái)擴(kuò)容。 擴(kuò)容之后是通過(guò)數(shù)組的拷貝來(lái)確保元素的準(zhǔn)確性的,所以盡可能減少擴(kuò)容操作。 ArrayList 的最大存儲(chǔ)能力:Integer.MAX_VALUE。 size 為集合中存儲(chǔ)的元素的個(gè)數(shù)。elementData.length 為數(shù)組長(zhǎng)度,表示最多可以存儲(chǔ)多少個(gè)元素。 如果需要邊遍歷邊 remove ,必須使用 iterator。且 remove 之前必須先 next,next 之后只能用一次 remove。
以上所述是小編給大家介紹的java數(shù)據(jù)結(jié)構(gòu)ArrayList詳解,希望對(duì)大家有所幫助。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
idea神級(jí)插件及如何安裝Bito插件【Bito-ChatGPT】
這篇文章主要介紹了介紹一款idea神級(jí)插件【Bito-ChatGPT】,Bito插件的強(qiáng)大之處在于它可以幫助開(kāi)發(fā)人員更快地提交代碼,同時(shí)還提供了一些有用的功能,如自動(dòng)補(bǔ)全提交信息、快速查看歷史記錄等,需要的朋友可以參考下2023-04-04mybatis自定義參數(shù)類(lèi)型轉(zhuǎn)換器數(shù)據(jù)庫(kù)字段加密脫敏
這篇文章主要為大家介紹了mybatis自定義參數(shù)類(lèi)型轉(zhuǎn)換器數(shù)據(jù)庫(kù)字段加密脫敏,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09JavaWeb使用mvc模式實(shí)現(xiàn)登錄功能
本文主要介紹了JavaWeb使用mvc模式實(shí)現(xiàn)登錄功能,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01Java使用過(guò)濾器防止SQL注入XSS腳本注入的實(shí)現(xiàn)
這篇文章主要介紹了Java使用過(guò)濾器防止SQL注入XSS腳本注入,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01Java中抽象類(lèi)和接口的區(qū)別_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
java抽象類(lèi)和接口最本質(zhì)的區(qū)別是接口里不能實(shí)現(xiàn)方法--接口中的方法全是抽象方法。抽象類(lèi)中可實(shí)現(xiàn)方法--抽象類(lèi)中的方法可以不是抽象方法,下文給大家簡(jiǎn)單介紹下,需要的的朋友參考下2017-04-04