Java Review - ArrayList 源码解读
文章目錄
- 概述
- 方法的執(zhí)行效率
- 源碼剖析
- 底層數(shù)據(jù)結(jié)構(gòu) -數(shù)組
- 構(gòu)造函數(shù)
- 自動(dòng)擴(kuò)容機(jī)制
- set()
- get
- add()/addAll()
- remove()
- trimToSize()
- indexOf(), lastIndexOf()
- Fail-Fast
概述
從類(lèi)的繼承圖上我們可知道,ArrayList實(shí)現(xiàn)了List接口。
-
同時(shí)List是順序容器,即元素存放的數(shù)據(jù)與放進(jìn)去的順序相同,允許放入null元素,
-
ArrayList底層基于數(shù)組實(shí)現(xiàn)。
-
每個(gè)ArrayList都有一個(gè)容量(capacity),表示底層數(shù)組的實(shí)際大小,容器內(nèi)存儲(chǔ)元素的個(gè)數(shù)不能多于當(dāng)前容量。
-
當(dāng)向容器中添加元素時(shí),如果容量不足,容器自動(dòng)擴(kuò)容。
-
ArrayList<E>,可以看到是泛型類(lèi)型, Java泛型只是編譯器提供的語(yǔ)法糖,數(shù)組是一個(gè)Object數(shù)組,可以容納任何類(lèi)型的對(duì)象。
方法的執(zhí)行效率
- size(), isEmpty(), get(), set()方法均能在常數(shù)時(shí)間內(nèi)完成
- add()方法的時(shí)間開(kāi)銷(xiāo)跟插入位置有關(guān)
- addAll()方法的時(shí)間開(kāi)銷(xiāo)跟添加元素的個(gè)數(shù)成正比。
- 其余方法大都是線性時(shí)間。
為追求效率,ArrayList沒(méi)有實(shí)現(xiàn)同步(synchronized),如果需要多個(gè)線程并發(fā)訪問(wèn),用戶可以手動(dòng)同步,也可使用Vector替代
源碼剖析
底層數(shù)據(jù)結(jié)構(gòu) -數(shù)組
構(gòu)造函數(shù)
/*** 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) {if (initialCapacity > 0) {this.elementData = new Object[initialCapacity];} else if (initialCapacity == 0) {this.elementData = EMPTY_ELEMENTDATA;} else {throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);}}/*** Constructs an empty list with an initial capacity of ten.*/public ArrayList() {this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;}/*** Constructs a list containing the elements of the specified* collection, in the order they are returned by the collection's* iterator.** @param c the collection whose elements are to be placed into this list* @throws NullPointerException if the specified collection is null*/public ArrayList(Collection<? extends E> c) {Object[] a = c.toArray();if ((size = a.length) != 0) {if (c.getClass() == ArrayList.class) {elementData = a;} else {elementData = Arrays.copyOf(a, size, Object[].class);}} else {// replace with empty array.elementData = EMPTY_ELEMENTDATA;}}演示如下:
/*** 初始化的時(shí)候指定容量*/List list = new ArrayList<>(1);list.add(1);list.add(2);System.out.println(list.size());/*** 默認(rèn)構(gòu)造函數(shù) ,數(shù)組大小為0*/list = new ArrayList();list.add("artisan");list.add("review");list.add("java");System.out.println(list.size());/*** 使用集合初始化一個(gè)ArrayList*/list = new ArrayList(Arrays.asList("I" , "Love" ,"Code"));System.out.println(list.size());自動(dòng)擴(kuò)容機(jī)制
-
每當(dāng)向數(shù)組中添加元素時(shí),都需要檢查添加后元素的個(gè)數(shù)是否會(huì)超出當(dāng)前數(shù)組的長(zhǎng)度,如果超出,數(shù)組將會(huì)進(jìn)行擴(kuò)容,以滿足添加數(shù)據(jù)的需求。
-
數(shù)組進(jìn)行擴(kuò)容時(shí),會(huì)將老數(shù)組中的元素重新拷貝一份到新的數(shù)組中,每次數(shù)組容量的增長(zhǎng)大約是其原容量的1.5倍。
這種操作的代價(jià)是很高的,因此在實(shí)際使用時(shí),我們應(yīng)該盡量避免數(shù)組容量的擴(kuò)張。當(dāng)我們可預(yù)知要保存的元素的多少時(shí),要在構(gòu)造ArrayList實(shí)例時(shí),就指定其容量,以避免數(shù)組擴(kuò)容的發(fā)生。
或者根據(jù)實(shí)際需求,通過(guò)調(diào)用ensureCapacity方法來(lái)手動(dòng)增加ArrayList實(shí)例的容量。
- ArrayList#ensureCapacity(int minCapacity)暴漏了public方法可以允許程序猿手工擴(kuò)容增加ArrayList實(shí)例的容量,以減少遞增式再分配的數(shù)量。
我們來(lái)看下效率對(duì)比
/*** 擴(kuò)容對(duì)比*/long begin = System.currentTimeMillis();// 初始化1億的數(shù)據(jù)量final int number = 100000000 ;Object o = new Object();ArrayList list1 = new ArrayList<String>();for (int i = 0; i < number; i++) {list1.add(o);}System.out.println("依賴(lài)ArrayList的自動(dòng)擴(kuò)容機(jī)制,添加數(shù)據(jù)耗時(shí):" +(System.currentTimeMillis() - begin));begin = System.currentTimeMillis();ArrayList list2 = new ArrayList<String>();// 手工擴(kuò)容list2.ensureCapacity(number);for (int i = 0; i < number; i++) {list2.add(o);}System.out.println("手工ensureCapacity擴(kuò)容后,添加數(shù)據(jù)耗時(shí):" + (System.currentTimeMillis() - begin));
原因是因?yàn)?#xff0c;第一段如果沒(méi)有一次性擴(kuò)到想要的最大容量的話,它就會(huì)在添加元素的過(guò)程中,一點(diǎn)一點(diǎn)的進(jìn)行擴(kuò)容,要知道對(duì)數(shù)組擴(kuò)容是要進(jìn)行數(shù)組拷貝的,這就會(huì)浪費(fèi)大量的時(shí)間。如果已經(jīng)預(yù)知容器可能會(huì)裝多少元素,最好顯示的調(diào)用ensureCapacity這個(gè)方法一次性擴(kuò)容到位。
過(guò)程圖如下:
set()
底層是一個(gè)數(shù)組, 那ArrayList的set()方法也就是直接對(duì)數(shù)組的指定位置賦值
/*** Replaces the element at the specified position in this list with* the specified element.** @param index index of the element to replace* @param element element to be stored at the specified position* @return the element previously at the specified position* @throws IndexOutOfBoundsException {@inheritDoc}*/public E set(int index, E element) {rangeCheck(index);E oldValue = elementData(index);elementData[index] = element;return oldValue;}get
get()方法也很簡(jiǎn)單,需要注意的是由于底層數(shù)組是Object[],得到元素后需要進(jìn)行類(lèi)型轉(zhuǎn)換。
/*** 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) {rangeCheck(index);return elementData(index);} @SuppressWarnings("unchecked")E elementData(int index) {return (E) elementData[index];}add()/addAll()
這兩個(gè)方法都是向容器中添加新元素,這可能會(huì)導(dǎo)致capacity不足,因此在添加元素之前,都需要進(jìn)行剩余空間檢查,如果需要?jiǎng)t自動(dòng)擴(kuò)容。擴(kuò)容操作最終是通過(guò)grow()方法完成的
/*** 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) {ensureCapacityInternal(size + 1); // Increments modCount!!elementData[size++] = e;return true;}/*** Inserts the specified element at the specified position in this* list. Shifts the element currently at that position (if any) and* any subsequent elements to the right (adds one to their indices).** @param index index at which the specified element is to be inserted* @param element element to be inserted* @throws IndexOutOfBoundsException {@inheritDoc}*/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++;}- add(E e) 在末尾添加
- add(int index, E e)需要先對(duì)元素進(jìn)行移動(dòng),然后完成插入操作,也就意味著該方法有著線性的時(shí)間復(fù)雜度。
-
addAll()方法能夠一次添加多個(gè)元素,根據(jù)位置不同也有兩個(gè)把本
一個(gè)是在末尾添加的addAll(Collection<? extends E> c)方法,
一個(gè)是從指定位置開(kāi)始插入的addAll(int index, Collection<? extends E> c)方法。
跟add()方法類(lèi)似,在插入之前也需要進(jìn)行空間檢查,如果需要?jiǎng)t自動(dòng)擴(kuò)容;如果從指定位置插入,也會(huì)存在移動(dòng)元素的情況。]
addAll()的時(shí)間復(fù)雜度不僅跟插入元素的多少有關(guān),也跟插入的位置相關(guān)。
remove()
remove()方法也有兩個(gè)方法
- 一個(gè)是remove(int index)刪除指定位置的元素
- 一個(gè)是remove(Object o)刪除第一個(gè)滿足o.equals(elementData[index])的元素
刪除操作是add()操作的逆過(guò)程,需要將刪除點(diǎn)之后的元素向前移動(dòng)一個(gè)位置。需要注意的是為了讓GC起作用,必須顯式的為最后一個(gè)位置賦null值。
上面代碼中如果不手動(dòng)賦null值,除非對(duì)應(yīng)的位置被其他元素覆蓋,否則原來(lái)的對(duì)象就一直不會(huì)被回收。
/*** Removes the first occurrence of the specified element from this list,* if it is present. If the list does not contain the element, it is* unchanged. More formally, removes the element with the lowest index* <tt>i</tt> such that* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>* (if such an element exists). Returns <tt>true</tt> if this list* contained the specified element (or equivalently, if this list* changed as a result of the call).** @param o element to be removed from this list, if present* @return <tt>true</tt> if this list contained the specified element*/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;}trimToSize()
將底層數(shù)組的容量調(diào)整為當(dāng)前列表保存的實(shí)際元素的大小
/*** Trims the capacity of this <tt>ArrayList</tt> instance to be the* list's current size. An application can use this operation to minimize* the storage of an <tt>ArrayList</tt> instance.*/public void trimToSize() {modCount++;if (size < elementData.length) {elementData = (size == 0)? EMPTY_ELEMENTDATA: Arrays.copyOf(elementData, size);}}indexOf(), lastIndexOf()
獲取元素的第一次出現(xiàn)的index
/*** Returns the index of the first occurrence of the specified element* in this list, or -1 if this list does not contain the element.* More formally, returns the lowest index <tt>i</tt> such that* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,* or -1 if there is no such index.*/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;}獲取元素的最后一次出現(xiàn)的index
/*** Returns the index of the last occurrence of the specified element* in this list, or -1 if this list does not contain the element.* More formally, returns the highest index <tt>i</tt> such that* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,* or -1 if there is no such index.*/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;}Fail-Fast
ArrayList同樣采用了快速失敗的機(jī)制,通過(guò)記錄modCount參數(shù)來(lái)實(shí)現(xiàn)。在面對(duì)并發(fā)的修改時(shí),迭代器很快就會(huì)完全失敗,而不是冒著在將來(lái)某個(gè)不確定時(shí)間發(fā)生任意不確定行為的風(fēng)險(xiǎn)。
具體參考前段時(shí)間寫(xiě)的一篇博文如下:
Java - Java集合中的快速失敗Fail Fast 機(jī)制
總結(jié)
以上是生活随笔為你收集整理的Java Review - ArrayList 源码解读的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java Review - 集合框架=C
- 下一篇: Java Review - Linked