ArrayList就是傳說中的動態數組,就是Array的復雜版本,它提供了如下一些好處:動態的增加和減少元素、靈活的設置數組的大小......
? ??認真閱讀本文,我相信一定會對你有幫助。比如為什么ArrayList里面提供了一個受保護的removeRange方法?提供了其他沒有被調用過的私有方法?
? ? 首先看到對ArrayList的定義:
[java]?view plaincopy
public?class?ArrayList<E>?extends?AbstractList<E>??implements?List<E>,?RandomAccess,?Cloneable,?java.io.Serializable??
?從ArrayList<E>可以看出它是支持泛型的,它繼承自AbstractList,實現了List、RandomAccess、Cloneable、java.io.Serializable接口。
? ??AbstractList提供了List接口的默認實現(個別方法為抽象方法)。
? ? List接口定義了列表必須實現的方法。
? ??RandomAccess是一個標記接口,接口內沒有定義任何內容。
? ??實現了Cloneable接口的類,可以調用Object.clone方法返回該對象的淺拷貝。
? ??通過實現 java.io.Serializable 接口以啟用其序列化功能。未實現此接口的類將無法使其任何狀態序列化或反序列化。序列化接口沒有方法或字段,僅用于標識可序列化的語義。
? ??ArrayList的屬性
? ??ArrayList定義只定義類兩個私有屬性:
[java]?view plaincopy
? ? ? ?? ?????private?transient?Object[]?elementData;?? ??? ?????? ? ? ? ?? ?????private?int?size;??
[java]?view plaincopy
很容易理解,elementData存儲ArrayList內的元素,size表示它包含的元素的數量。?? ?? ??有個關鍵字需要解釋:transient。?? ?? ??Java的serialization提供了一種持久化對象實例的機制。當持久化對象時,可能有一個特殊的對象數據成員,我們不想用serialization機制來保存它。為了在一個特定對象的一個域上關閉serialization,可以在這個域前加上關鍵字transient。?? ansient是Java語言的關鍵字,用來表示一個域不是該對象串行化的一部分。當一個對象被串行化的時候,transient型變量的值不包括在串行化的表示中,然而非transient型的變量是被包括進去的。?? ?? ??有點抽象,看個例子應該能明白。??
[java]?view plaincopy
public?class?UserInfo?implements?Serializable?{?? ?????private?static?final?long?serialVersionUID?=?996890129747019948L;?? ?????private?String?name;?? ?????private?transient?String?psw;?? ??? ?????public?UserInfo(String?name,?String?psw)?{?? ?????????this.name?=?name;?? ?????????this.psw?=?psw;?? ?????}?? ??? ?????public?String?toString()?{?? ?????????return?"name="?+?name?+?",?psw="?+?psw;?? ?????}?? ?}?? ??? ?public?class?TestTransient?{?? ?????public?static?void?main(String[]?args)?{?? ?????????UserInfo?userInfo?=?new?UserInfo("張三",?"123456");?? ?????????System.out.println(userInfo);?? ?????????try?{?? ??????????????? ?????????????ObjectOutputStream?o?=?new?ObjectOutputStream(new?FileOutputStream(?? ?????????????????????"UserInfo.out"));?? ?????????????o.writeObject(userInfo);?? ?????????????o.close();?? ?????????}?catch?(Exception?e)?{?? ??????????????? ?????????????e.printStackTrace();?? ?????????}?? ?????????try?{?? ??????????????? ?????????????ObjectInputStream?in?=?new?ObjectInputStream(new?FileInputStream(?? ?????????????????????"UserInfo.out"));?? ?????????????UserInfo?readUserInfo?=?(UserInfo)?in.readObject();?? ??????????????? ?????????????System.out.println(readUserInfo.toString());?? ?????????}?catch?(Exception?e)?{?? ??????????????? ?????????????e.printStackTrace();?? ?????????}?? ?????}?? ?}??
?被標記為transient的屬性在對象被序列化的時候不會被保存。
? ? 接著回到ArrayList的分析中......
? ??ArrayList的構造方法
? ? 看完屬性看構造方法。ArrayList提供了三個構造方法:
[java]?view plaincopy
? ? ?? ?????public?ArrayList(int?initialCapacity)?{?? ?????super();?? ?????????if?(initialCapacity?<?0)?? ?????????????throw?new?IllegalArgumentException("Illegal?Capacity:?"+?? ????????????????????????????????????????????????initialCapacity);?? ?????this.elementData?=?new?Object[initialCapacity];?? ?????}?? ??? ?????? ? ?? ?????public?ArrayList()?{?? ?????this(10);?? ?????}?? ??? ?????? ? ? ? ?? ?????public?ArrayList(Collection<??extends?E>?c)?{?? ?????elementData?=?c.toArray();?? ?????size?=?elementData.length;?? ??????? ?????if?(elementData.getClass()?!=?Object[].class)?? ?????????elementData?=?Arrays.copyOf(elementData,?size,?Object[].class);?? ?????}??
? ?第一個構造方法使用提供的initialCapacity來初始化elementData數組的大小。第二個構造方法調用第一個構造方法并傳入參數10,即默認elementData數組的大小為10。第三個構造方法則將提供的集合轉成數組返回給elementData(返回若不是Object[]將調用Arrays.copyOf方法將其轉為Object[])。
? ??ArrayList的其他方法
? ? add(E e)
? ? add(E e)都知道是在尾部添加一個元素,如何實現的呢?
[java]?view plaincopy
public?boolean?add(E?e)?{?? ????ensureCapacity(size?+?1);???? ????elementData[size++]?=?e;?? ????return?true;?? ????}??
?書上都說ArrayList是基于數組實現的,屬性中也看到了數組,具體是怎么實現的呢?比如就這個添加元素的方法,如果數組大,則在將某個位置的值設置為指定元素即可,如果數組容量不夠了呢?
? ? 看到add(E e)中先調用了ensureCapacity(size+1)方法,之后將元素的索引賦給elementData[size],而后size自增。例如初次添加時,size為0,add將elementData[0]賦值為e,然后size設置為1(類似執行以下兩條語句elementData[0]=e;size=1)。將元素的索引賦給elementData[size]不是會出現數組越界的情況嗎?這里關鍵就在ensureCapacity(size+1)中了。
? ? 根據ensureCapacity的方法名可以知道是確保容量用的。ensureCapacity(size+1)后面的注釋可以明白是增加modCount的值(加了倆感嘆號,應該蠻重要的,來看看)。
[java]?view plaincopy
? ? ? ? ? ? ?? ?????public?void?ensureCapacity(int?minCapacity)?{?? ?????modCount++;?? ?????int?oldCapacity?=?elementData.length;?? ?????if?(minCapacity?>?oldCapacity)?{?? ?????????Object?oldData[]?=?elementData;?? ?????????int?newCapacity?=?(oldCapacity?*?3)/2?+?1;?? ?????????????if?(newCapacity?<?minCapacity)?? ?????????newCapacity?=?minCapacity;?? ??????????????? ?????????????elementData?=?Arrays.copyOf(elementData,?newCapacity);?? ?????}?? ?????}??
The number of times this list has been structurally modified.
? ? 這是對modCount的解釋,意為記錄list結構被改變的次數(觀察源碼可以發現每次調用ensureCapacoty方法,modCount的值都將增加,但未必數組結構會改變,所以感覺對modCount的解釋不是很到位)。
? ??增加modCount之后,判斷minCapacity(即size+1)是否大于oldCapacity(即elementData.length),若大于,則調整容量為max((oldCapacity*3)/2+1,minCapacity),調整elementData容量為新的容量,即將返回一個內容為原數組元素,大小為新容量的數組賦給elementData;否則不做操作。
? ? 所以調用ensureCapacity至少將elementData的容量增加的1,所以elementData[size]不會出現越界的情況。
? ??容量的拓展將導致數組元素的復制,多次拓展容量將執行多次整個數組內容的復制。若提前能大致判斷list的長度,調用ensureCapacity調整容量,將有效的提高運行速度。
? ? 可以理解提前分配好空間可以提高運行速度,但是測試發現提高的并不是很大,而且若list原本數據量就不會很大效果將更不明顯。
? ??add(int index, E element)
??? add(int index,E element)在指定位置插入元素。
[java]?view plaincopy
public?void?add(int?index,?E?element)?{?? ?????if?(index?>?size?||?index?<?0)?? ?????????throw?new?IndexOutOfBoundsException(?? ?????????"Index:?"+index+",?Size:?"+size);?? ??? ?????ensureCapacity(size+1);???? ?????System.arraycopy(elementData,?index,?elementData,?index?+?1,?? ??????????????size?-?index);?? ?????elementData[index]?=?element;?? ?????size++;?? ?????}??
? ?首先判斷指定位置index是否超出elementData的界限,之后調用ensureCapacity調整容量(若容量足夠則不會拓展),調用System.arraycopy將elementData從index開始的size-index個元素復制到index+1至size+1的位置(即index開始的元素都向后移動一個位置),然后將index位置的值指向element。? ? ? ?
? ? addAll(Collection<? extends E> c)
[java]?view plaincopy
public?boolean?addAll(Collection<??extends?E>?c)?{?? ?????Object[]?a?=?c.toArray();?? ?????????int?numNew?=?a.length;?? ?????ensureCapacity(size?+?numNew);???? ?????????System.arraycopy(a,?0,?elementData,?size,?numNew);?? ?????????size?+=?numNew;?? ?????return?numNew?!=?0;?? ?????}??
? 先將集合c轉換成數組,根據轉換后數組的程度和ArrayList的size拓展容量,之后調用System.arraycopy方法復制元素到elementData的尾部,調整size。根據返回的內容分析,只要集合c的大小不為空,即轉換后的數組長度不為0則返回true。
? ? addAll(int index,Collection<? extends E> c)
[java]?view plaincopy
public?boolean?addAll(int?index,?Collection<??extends?E>?c)?{?? ?????if?(index?>?size?||?index?<?0)?? ?????????throw?new?IndexOutOfBoundsException(?? ?????????"Index:?"?+?index?+?",?Size:?"?+?size);?? ??? ?????Object[]?a?=?c.toArray();?? ?????int?numNew?=?a.length;?? ?????ensureCapacity(size?+?numNew);???? ??? ?????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;?? ?????}??
? 先判斷index是否越界。其他內容與addAll(Collection<? extends E> c)基本一致,只是復制的時候先將index開始的元素向后移動X(c轉為數組后的長度)個位置(也是一個復制的過程),之后將數組內容復制到elementData的index位置至index+X。
? ? clear()
[java]?view plaincopy
public?void?clear()?{?? ?????modCount++;?? ??? ??????? ?????for?(int?i?=?0;?i?<?size;?i++)?? ?????????elementData[i]?=?null;?? ??? ?????size?=?0;?? ?????}??
clear的時候并沒有修改elementData的長度(好不容易申請、拓展來的,憑什么釋放,留著搞不好還有用呢。這使得確定不再修改list內容之后最好調用trimToSize來釋放掉一些空間),只是將所有元素置為null,size設置為0。
? ? clone()
? ? 返回此 ArrayList 實例的淺表副本。(不復制這些元素本身。)
[java]?view plaincopy
public?Object?clone()?{?? ?????try?{?? ?????????ArrayList<E>?v?=?(ArrayList<E>)?super.clone();?? ?????????v.elementData?=?Arrays.copyOf(elementData,?size);?? ?????????v.modCount?=?0;?? ?????????return?v;?? ?????}?catch?(CloneNotSupportedException?e)?{?? ??????????? ?????????throw?new?InternalError();?? ?????}?? ?????}??
? 調用父類的clone方法返回一個對象的副本,將返回對象的elementData數組的內容賦值為原對象elementData數組的內容,將副本的modCount設置為0。
? ? contains(Object)
[html]?view plaincopy
public?boolean?contains(Object?o)?{?? ?????return?indexOf(o)?>=?0;?? ?????}??
?indexOf方法返回值與0比較來判斷對象是否在list中。接著看indexOf。
? ? indexOf(Object)
[java]?view plaincopy
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;?? ?????}??
通過遍歷elementData數組來判斷對象是否在list中,若存在,返回index([0,size-1]),若不存在則返回-1。所以contains方法可以通過indexOf(Object)方法的返回值來判斷對象是否被包含在list中。
? ? 既然看了indexOf(Object)方法,接著就看lastIndexOf,光看名字應該就明白了返回的是傳入對象在elementData數組中最后出現的index值。
[java]?view plaincopy
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;?? ?????}??
采用了從后向前遍歷element數組,若遇到Object則返回index值,若沒有遇到,返回-1。
? ??get(int index)
? ? 這個方法看著很簡單,應該是返回elementData[index]就完了。
[java]?view plaincopy
public?E?get(int?index)?{?? ?????RangeCheck(index);?? ?? ?????return?(E)?elementData[index];?? ?????}??
但看代碼的時候看到調用了RangeCheck方法,而且還是大寫的方法,看看究竟有什么內容吧。
[java]?view plaincopy
? ? ?? ?private?void?RangeCheck(int?index)?{?? ?????if?(index?>=?size)?? ?????????throw?new?IndexOutOfBoundsException(?? ?????????"Index:?"+index+",?Size:?"+size);?? ?????}??
?就是檢查一下是不是超出數組界限了,超出了就拋出IndexOutBoundsException異常。為什么要大寫呢???
? ? isEmpty()
? ? 直接返回size是否等于0。
? ? remove(int index)
[java]?view plaincopy
public?E?remove(int?index)?{?? ?????RangeCheck(index);?? ?????modCount++;?? ?????E?oldValue?=?(E)?elementData[index];?? ?????int?numMoved?=?size?-?index?-?1;?? ?????if?(numMoved?>?0)?? ?????????System.arraycopy(elementData,?index+1,?elementData,?index,?? ??????????????????numMoved);?? ?????elementData[--size]?=?null;??? ?????return?oldValue;?? ?????}??
首先是檢查范圍,修改modCount,保留將要被移除的元素,將移除位置之后的元素向前挪動一個位置,將list末尾元素置空(null),返回被移除的元素。
? ? remove(Object o)
[java]?view plaincopy
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;?? ?????}??
? 首先通過代碼可以看到,當移除成功后返回true,否則返回false。remove(Object o)中通過遍歷element尋找是否存在傳入對象,一旦找到就調用fastRemove移除對象。為什么找到了元素就知道了index,不通過remove(index)來移除元素呢?因為fastRemove跳過了判斷邊界的處理,因為找到元素就相當于確定了index不會超過邊界,而且fastRemove并不返回被移除的元素。下面是fastRemove的代碼,基本和remove(index)一致。
[java]?view plaincopy
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;??? ?????}??
? removeRange(int fromIndex,int toIndex)
[java]?view plaincopy
protected?void?removeRange(int?fromIndex,?int?toIndex)?{?? ?????modCount++;?? ?????int?numMoved?=?size?-?toIndex;?? ?????????System.arraycopy(elementData,?toIndex,?elementData,?fromIndex,?? ??????????????????????????numMoved);?? ??? ??????? ?????int?newSize?=?size?-?(toIndex-fromIndex);?? ?????while?(size?!=?newSize)?? ?????????elementData[--size]?=?null;?? ?????}??
執行過程是將elementData從toIndex位置開始的元素向前移動到fromIndex,然后將toIndex位置之后的元素全部置空順便修改size。
? ??這個方法是protected,及受保護的方法,為什么這個方法被定義為protected呢?
? ? 這是一個解釋,但是可能不容易看明白。http://stackoverflow.com/questions/2289183/why-is-javas-abstractlists-removerange-method-protected
? ? 先看下面這個例子
[java]?view plaincopy
ArrayList<Integer>?ints?=?new?ArrayList<Integer>(Arrays.asList(0,?1,?2,?? ?????????????????3,?4,?5,?6));?? ??????????? ??????????? ????????ints.subList(2,?4).clear();?? ?????????System.out.println(ints);??
?
輸出結果是[0, 1, 4, 5, 6],結果是不是像調用了removeRange(int fromIndex,int toIndex)!哈哈哈,就是這樣的。但是為什么效果相同呢?是不是調用了removeRange(int fromIndex,int toIndex)呢?
set(int index,E element)
[java]?view plaincopy
public?E?set(int?index,?E?element)?{?? ?????RangeCheck(index);?? ??? ?????E?oldValue?=?(E)?elementData[index];?? ?????elementData[index]?=?element;?? ?????return?oldValue;?? ?????}??
? 首先檢查范圍,用新元素替換舊元素并返回舊元素。
? ? size()
? ? size()方法直接返回size。
? ? toArray()
[java]?view plaincopy
public?Object[]?toArray()?{?? ?????????return?Arrays.copyOf(elementData,?size);?? ?????}??
?調用Arrays.copyOf將返回一個數組,數組內容是size個elementData的元素,即拷貝elementData從0至size-1位置的元素到新數組并返回。
? ? toArray(T[] a)
[java]?view plaincopy
public?<T>?T[]?toArray(T[]?a)?{?? ?????????if?(a.length?<?size)?? ??????????????? ?????????????return?(T[])?Arrays.copyOf(elementData,?size,?a.getClass());?? ?????System.arraycopy(elementData,?0,?a,?0,?size);?? ?????????if?(a.length?>?size)?? ?????????????a[size]?=?null;?? ?????????return?a;?? ?????}??
?如果傳入數組的長度小于size,返回一個新的數組,大小為size,類型與傳入數組相同。所傳入數組長度與size相等,則將elementData復制到傳入數組中并返回傳入的數組。若傳入數組長度大于size,除了復制elementData外,還將把返回數組的第size個元素置為空。
? ? trimToSize()
[java]?view plaincopy
public?void?trimToSize()?{?? ?????modCount++;?? ?????int?oldCapacity?=?elementData.length;?? ?????if?(size?<?oldCapacity)?{?? ?????????????elementData?=?Arrays.copyOf(elementData,?size);?? ?????}?? ?????}??
由于elementData的長度會被拓展,size標記的是其中包含的元素的個數。所以會出現size很小但elementData.length很大的情況,將出現空間的浪費。trimToSize將返回一個新的數組給elementData,元素內容保持不變,length很size相同,節省空間。
?? ? 學習Java最好的方式還必須是讀源碼。讀完源碼你才會發現這東西為什么是這么玩的,有哪些限制,關鍵點在哪里等等。而且這些源碼都是大牛們寫的,你能從中學習到很多。
總結
以上是生活随笔為你收集整理的java源码分析之ArrayList的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。