日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

ArrayList源码分析(基于JDK1.6)

發(fā)布時(shí)間:2025/7/14 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ArrayList源码分析(基于JDK1.6) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

? ? 不積跬步,無以至千里;不積小流,無以成江海。從基礎(chǔ)做起,一點(diǎn)點(diǎn)積累,加油!

? ? 《Java集合類》中講述了ArrayList的基礎(chǔ)使用,本文將深入剖析ArrayList的內(nèi)部結(jié)構(gòu)及實(shí)現(xiàn)原理,以便更好的、更高效的使用它。

? ? ArrayList就是傳說中的動(dòng)態(tài)數(shù)組,就是Array的復(fù)雜版本,它提供了如下一些好處:動(dòng)態(tài)的增加和減少元素、靈活的設(shè)置數(shù)組的大小......

? ??認(rèn)真閱讀本文,我相信一定會(huì)對(duì)你有幫助。比如為什么ArrayList里面提供了一個(gè)受保護(hù)的removeRange方法?提供了其他沒有被調(diào)用過的私有方法?

? ? 首先看到對(duì)ArrayList的定義:

1 public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable

? ? 從ArrayList<E>可以看出它是支持泛型的,它繼承自AbstractList,實(shí)現(xiàn)了List、RandomAccess、Cloneable、java.io.Serializable接口。

? ??AbstractList提供了List接口的默認(rèn)實(shí)現(xiàn)(個(gè)別方法為抽象方法)。

? ? List接口定義了列表必須實(shí)現(xiàn)的方法。

? ??RandomAccess是一個(gè)標(biāo)記接口,接口內(nèi)沒有定義任何內(nèi)容。

? ??實(shí)現(xiàn)了Cloneable接口的類,可以調(diào)用Object.clone方法返回該對(duì)象的淺拷貝。

? ??通過實(shí)現(xiàn) java.io.Serializable 接口以啟用其序列化功能。未實(shí)現(xiàn)此接口的類將無法使其任何狀態(tài)序列化或反序列化。序列化接口沒有方法或字段,僅用于標(biāo)識(shí)可序列化的語義。

? ? ArrayList的屬性

? ??ArrayList定義只定義類兩個(gè)私有屬性:

1 /** 2 * The array buffer into which the elements of the ArrayList are stored. 3 * The capacity of the ArrayList is the length of this array buffer. 4 */ 5 private transient Object[] elementData; 6 7 /** 8 * The size of the ArrayList (the number of elements it contains). 9 * 10 * @serial 11 */ 12 private int size;

? ? 很容易理解,elementData存儲(chǔ)ArrayList內(nèi)的元素,size表示它包含的元素的數(shù)量。

? ??有個(gè)關(guān)鍵字需要解釋:transient。

? ??Java的serialization提供了一種持久化對(duì)象實(shí)例的機(jī)制。當(dāng)持久化對(duì)象時(shí),可能有一個(gè)特殊的對(duì)象數(shù)據(jù)成員,我們不想用serialization機(jī)制來保存它。為了在一個(gè)特定對(duì)象的一個(gè)域上關(guān)閉serialization,可以在這個(gè)域前加上關(guān)鍵字transient。
transient是Java語言的關(guān)鍵字,用來表示一個(gè)域不是該對(duì)象串行化的一部分。當(dāng)一個(gè)對(duì)象被串行化的時(shí)候,transient型變量的值不包括在串行化的表示中,然而非transient型的變量是被包括進(jìn)去的。

? ??有點(diǎn)抽象,看個(gè)例子應(yīng)該能明白。

1 public class UserInfo implements Serializable { 2 private static final long serialVersionUID = 996890129747019948L; 3 private String name; 4 private transient String psw; 5 6 public UserInfo(String name, String psw) { 7 this.name = name; 8 this.psw = psw; 9 } 10 11 public String toString() { 12 return "name=" + name + ", psw=" + psw; 13 } 14 } 15 16 public class TestTransient { 17 public static void main(String[] args) { 18 UserInfo userInfo = new UserInfo("張三", "123456"); 19 System.out.println(userInfo); 20 try { 21 // 序列化,被設(shè)置為transient的屬性沒有被序列化 22 ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream( 23 "UserInfo.out")); 24 o.writeObject(userInfo); 25 o.close(); 26 } catch (Exception e) { 27 // TODO: handle exception 28 e.printStackTrace(); 29 } 30 try { 31 // 重新讀取內(nèi)容 32 ObjectInputStream in = new ObjectInputStream(new FileInputStream( 33 "UserInfo.out")); 34 UserInfo readUserInfo = (UserInfo) in.readObject(); 35 //讀取后psw的內(nèi)容為null 36 System.out.println(readUserInfo.toString()); 37 } catch (Exception e) { 38 // TODO: handle exception 39 e.printStackTrace(); 40 } 41 } 42 }

? ? 被標(biāo)記為transient的屬性在對(duì)象被序列化的時(shí)候不會(huì)被保存。

? ? 接著回到ArrayList的分析中......

? ??ArrayList的構(gòu)造方法

? ? 看完屬性看構(gòu)造方法。ArrayList提供了三個(gè)構(gòu)造方法:

1 /** 2 * Constructs an empty list with the specified initial capacity. 3 */ 4 public ArrayList(int initialCapacity) { 5 super(); 6 if (initialCapacity < 0) 7 throw new IllegalArgumentException("Illegal Capacity: "+ 8 initialCapacity); 9 this.elementData = new Object[initialCapacity]; 10 } 11 12 /** 13 * Constructs an empty list with an initial capacity of ten. 14 */ 15 public ArrayList() { 16 this(10); 17 } 18 19 /** 20 * Constructs a list containing the elements of the specified 21 * collection, in the order they are returned by the collection's 22 * iterator. 23 */ 24 public ArrayList(Collection<? extends E> c) { 25 elementData = c.toArray(); 26 size = elementData.length; 27 // c.toArray might (incorrectly) not return Object[] (see 6260652) 28 if (elementData.getClass() != Object[].class) 29 elementData = Arrays.copyOf(elementData, size, Object[].class); 30 }

? ? 第一個(gè)構(gòu)造方法使用提供的initialCapacity來初始化elementData數(shù)組的大小。第二個(gè)構(gòu)造方法調(diào)用第一個(gè)構(gòu)造方法并傳入?yún)?shù)10,即默認(rèn)elementData數(shù)組的大小為10。第三個(gè)構(gòu)造方法則將提供的集合轉(zhuǎn)成數(shù)組返回給elementData(返回若不是Object[]將調(diào)用Arrays.copyOf方法將其轉(zhuǎn)為Object[])。

? ??ArrayList的其他方法

? ? add(E e)

? ? add(E e)都知道是在尾部添加一個(gè)元素,如何實(shí)現(xiàn)的呢?

public boolean add(E e) {ensureCapacity(size + 1); // Increments modCount!!elementData[size++] = e;return true;}

? ? 書上都說ArrayList是基于數(shù)組實(shí)現(xiàn)的,屬性中也看到了數(shù)組,具體是怎么實(shí)現(xiàn)的呢?比如就這個(gè)添加元素的方法,如果數(shù)組大,則在將某個(gè)位置的值設(shè)置為指定元素即可,如果數(shù)組容量不夠了呢?

? ? 看到add(E e)中先調(diào)用了ensureCapacity(size+1)方法,之后將元素的索引賦給elementData[size],而后size自增。例如初次添加時(shí),size為0,add將elementData[0]賦值為e,然后size設(shè)置為1(類似執(zhí)行以下兩條語句elementData[0]=e;size=1)。將元素的索引賦給elementData[size]不是會(huì)出現(xiàn)數(shù)組越界的情況嗎?這里關(guān)鍵就在ensureCapacity(size+1)中了。

? ? 根據(jù)ensureCapacity的方法名可以知道是確保容量用的。ensureCapacity(size+1)后面的注釋可以明白是增加modCount的值(加了倆感嘆號(hào),應(yīng)該蠻重要的,來看看)。

1 /** 2 * Increases the capacity of this <tt>ArrayList</tt> instance, if 3 * necessary, to ensure that it can hold at least the number of elements 4 * specified by the minimum capacity argument. 5 * 6 * @param minCapacity the desired minimum capacity 7 */ 8 public void ensureCapacity(int minCapacity) { 9 modCount++; 10 int oldCapacity = elementData.length; 11 if (minCapacity > oldCapacity) { 12 Object oldData[] = elementData; 13 int newCapacity = (oldCapacity * 3)/2 + 1; 14 if (newCapacity < minCapacity) 15 newCapacity = minCapacity; 16 // minCapacity is usually close to size, so this is a win: 17 elementData = Arrays.copyOf(elementData, newCapacity); 18 } 19 }

? ? The number of times this list has been structurally modified.

? ? 這是對(duì)modCount的解釋,意為記錄list結(jié)構(gòu)被改變的次數(shù)(觀察源碼可以發(fā)現(xiàn)每次調(diào)用ensureCapacoty方法,modCount的值都將增加,但未必?cái)?shù)組結(jié)構(gòu)會(huì)改變,所以感覺對(duì)modCount的解釋不是很到位)。

? ??增加modCount之后,判斷minCapacity(即size+1)是否大于oldCapacity(即elementData.length),若大于,則調(diào)整容量為max((oldCapacity*3)/2+1,minCapacity),調(diào)整elementData容量為新的容量,即將返回一個(gè)內(nèi)容為原數(shù)組元素,大小為新容量的數(shù)組賦給elementData;否則不做操作。

? ? 所以調(diào)用ensureCapacity至少將elementData的容量增加的1,所以elementData[size]不會(huì)出現(xiàn)越界的情況。

? ??容量的拓展將導(dǎo)致數(shù)組元素的復(fù)制,多次拓展容量將執(zhí)行多次整個(gè)數(shù)組內(nèi)容的復(fù)制。若提前能大致判斷l(xiāng)ist的長(zhǎng)度,調(diào)用ensureCapacity調(diào)整容量,將有效的提高運(yùn)行速度。

? ? 可以理解提前分配好空間可以提高運(yùn)行速度,但是測(cè)試發(fā)現(xiàn)提高的并不是很大,而且若list原本數(shù)據(jù)量就不會(huì)很大效果將更不明顯。

? ??add(int index, E element)

??? add(int index,E element)在指定位置插入元素。

1 public void add(int index, E element) { 2 if (index > size || index < 0) 3 throw new IndexOutOfBoundsException( 4 "Index: "+index+", Size: "+size); 5 6 ensureCapacity(size+1); // Increments modCount!! 7 System.arraycopy(elementData, index, elementData, index + 1, 8 size - index); 9 elementData[index] = element; 10 size++; 11 }

? ? 首先判斷指定位置index是否超出elementData的界限,之后調(diào)用ensureCapacity調(diào)整容量(若容量足夠則不會(huì)拓展),調(diào)用System.arraycopy將elementData從index開始的size-index個(gè)元素復(fù)制到index+1至size+1的位置(即index開始的元素都向后移動(dòng)一個(gè)位置),然后將index位置的值指向element。? ? ? ?

? ? addAll(Collection<? extends E> c)

1 public boolean addAll(Collection<? extends E> c) { 2 Object[] a = c.toArray(); 3 int numNew = a.length; 4 ensureCapacity(size + numNew); // Increments modCount 5 System.arraycopy(a, 0, elementData, size, numNew); 6 size += numNew; 7 return numNew != 0; 8 }

? ? 先將集合c轉(zhuǎn)換成數(shù)組,根據(jù)轉(zhuǎn)換后數(shù)組的程度和ArrayList的size拓展容量,之后調(diào)用System.arraycopy方法復(fù)制元素到elementData的尾部,調(diào)整size。根據(jù)返回的內(nèi)容分析,只要集合c的大小不為空,即轉(zhuǎn)換后的數(shù)組長(zhǎng)度不為0則返回true。

? ? addAll(int index,Collection<? extends E> c)

1 public boolean addAll(int index, Collection<? extends E> c) { 2 if (index > size || index < 0) 3 throw new IndexOutOfBoundsException( 4 "Index: " + index + ", Size: " + size); 5 6 Object[] a = c.toArray(); 7 int numNew = a.length; 8 ensureCapacity(size + numNew); // Increments modCount 9 10 int numMoved = size - index; 11 if (numMoved > 0) 12 System.arraycopy(elementData, index, elementData, index + numNew, 13 numMoved); 14 15 System.arraycopy(a, 0, elementData, index, numNew); 16 size += numNew; 17 return numNew != 0; 18 }

? ? ?先判斷index是否越界。其他內(nèi)容與addAll(Collection<? extends E> c)基本一致,只是復(fù)制的時(shí)候先將index開始的元素向后移動(dòng)X(c轉(zhuǎn)為數(shù)組后的長(zhǎng)度)個(gè)位置(也是一個(gè)復(fù)制的過程),之后將數(shù)組內(nèi)容復(fù)制到elementData的index位置至index+X。

? ? clear()

1 public void clear() { 2 modCount++; 3 4 // Let gc do its work 5 for (int i = 0; i < size; i++) 6 elementData[i] = null; 7 8 size = 0; 9 }

? ? clear的時(shí)候并沒有修改elementData的長(zhǎng)度(好不容易申請(qǐng)、拓展來的,憑什么釋放,留著搞不好還有用呢。這使得確定不再修改list內(nèi)容之后最好調(diào)用trimToSize來釋放掉一些空間),只是將所有元素置為null,size設(shè)置為0。

? ? clone()

? ? 返回此 ArrayList 實(shí)例的淺表副本。(不復(fù)制這些元素本身。)

1 public Object clone() { 2 try { 3 ArrayList<E> v = (ArrayList<E>) super.clone(); 4 v.elementData = Arrays.copyOf(elementData, size); 5 v.modCount = 0; 6 return v; 7 } catch (CloneNotSupportedException e) { 8 // this shouldn't happen, since we are Cloneable 9 throw new InternalError(); 10 } 11 }

? ? 調(diào)用父類的clone方法返回一個(gè)對(duì)象的副本,將返回對(duì)象的elementData數(shù)組的內(nèi)容賦值為原對(duì)象elementData數(shù)組的內(nèi)容,將副本的modCount設(shè)置為0。

? ? contains(Object)

1 public boolean contains(Object o) { 2 return indexOf(o) >= 0; 3 }

? ? indexOf方法返回值與0比較來判斷對(duì)象是否在list中。接著看indexOf。

? ? indexOf(Object)

1 public int indexOf(Object o) { 2 if (o == null) { 3 for (int i = 0; i < size; i++) 4 if (elementData[i]==null) 5 return i; 6 } else { 7 for (int i = 0; i < size; i++) 8 if (o.equals(elementData[i])) 9 return i; 10 } 11 return -1; 12 }

? ? 通過遍歷elementData數(shù)組來判斷對(duì)象是否在list中,若存在,返回index([0,size-1]),若不存在則返回-1。所以contains方法可以通過indexOf(Object)方法的返回值來判斷對(duì)象是否被包含在list中。

? ? 既然看了indexOf(Object)方法,接著就看lastIndexOf,光看名字應(yīng)該就明白了返回的是傳入對(duì)象在elementData數(shù)組中最后出現(xiàn)的index值。

1 public int lastIndexOf(Object o) { 2 if (o == null) { 3 for (int i = size-1; i >= 0; i--) 4 if (elementData[i]==null) 5 return i; 6 } else { 7 for (int i = size-1; i >= 0; i--) 8 if (o.equals(elementData[i])) 9 return i; 10 } 11 return -1; 12 }

? ? 采用了從后向前遍歷element數(shù)組,若遇到Object則返回index值,若沒有遇到,返回-1。

? ??get(int index)

? ? 這個(gè)方法看著很簡(jiǎn)單,應(yīng)該是返回elementData[index]就完了。

1 public E get(int index) { 2 RangeCheck(index); 3 4 return (E) elementData[index]; 5 }

? ? 但看代碼的時(shí)候看到調(diào)用了RangeCheck方法,而且還是大寫的方法,看看究竟有什么內(nèi)容吧。

1 /** 2 * Checks if the given index is in range. 3 */ 4 private void RangeCheck(int index) { 5 if (index >= size) 6 throw new IndexOutOfBoundsException( 7 "Index: "+index+", Size: "+size); 8 }

? ? 就是檢查一下是不是超出數(shù)組界限了,超出了就拋出IndexOutBoundsException異常。為什么要大寫呢???

? ? isEmpty()

? ? 直接返回size是否等于0。

? ? remove(int index)

1 public E remove(int index) { 2 RangeCheck(index); 3 modCount++; 4 E oldValue = (E) elementData[index]; 5 int numMoved = size - index - 1; 6 if (numMoved > 0) 7 System.arraycopy(elementData, index+1, elementData, index, 8 numMoved); 9 elementData[--size] = null; // Let gc do its work 10 return oldValue; 11 }

? ? 首先是檢查范圍,修改modCount,保留將要被移除的元素,將移除位置之后的元素向前挪動(dòng)一個(gè)位置,將list末尾元素置空(null),返回被移除的元素。

? ? remove(Object o)

1 public boolean remove(Object o) { 2 if (o == null) { 3 for (int index = 0; index < size; index++) 4 if (elementData[index] == null) { 5 fastRemove(index); 6 return true; 7 } 8 } else { 9 for (int index = 0; index < size; index++) 10 if (o.equals(elementData[index])) { 11 fastRemove(index); 12 return true; 13 } 14 } 15 return false; 16 }

? ? 首先通過代碼可以看到,當(dāng)移除成功后返回true,否則返回false。remove(Object o)中通過遍歷element尋找是否存在傳入對(duì)象,一旦找到就調(diào)用fastRemove移除對(duì)象。為什么找到了元素就知道了index,不通過remove(index)來移除元素呢?因?yàn)閒astRemove跳過了判斷邊界的處理,因?yàn)檎业皆鼐拖喈?dāng)于確定了index不會(huì)超過邊界,而且fastRemove并不返回被移除的元素。下面是fastRemove的代碼,基本和remove(index)一致。

1 private void fastRemove(int index) { 2 modCount++; 3 int numMoved = size - index - 1; 4 if (numMoved > 0) 5 System.arraycopy(elementData, index+1, elementData, index, 6 numMoved); 7 elementData[--size] = null; // Let gc do its work 8 }

? ? removeRange(int fromIndex,int toIndex)

1 protected void removeRange(int fromIndex, int toIndex) { 2 modCount++; 3 int numMoved = size - toIndex; 4 System.arraycopy(elementData, toIndex, elementData, fromIndex, 5 numMoved); 6 7 // Let gc do its work 8 int newSize = size - (toIndex-fromIndex); 9 while (size != newSize) 10 elementData[--size] = null; 11 }

? ? 執(zhí)行過程是將elementData從toIndex位置開始的元素向前移動(dòng)到fromIndex,然后將toIndex位置之后的元素全部置空順便修改size。

? ? 這個(gè)方法是protected,及受保護(hù)的方法,為什么這個(gè)方法被定義為protected呢?

? ? 這是一個(gè)解釋,但是可能不容易看明白。http://stackoverflow.com/questions/2289183/why-is-javas-abstractlists-removerange-method-protected

? ? 先看下面這個(gè)例子

1 ArrayList<Integer> ints = new ArrayList<Integer>(Arrays.asList(0, 1, 2, 2 3, 4, 5, 6)); 3 // fromIndex low endpoint (inclusive) of the subList 4 // toIndex high endpoint (exclusive) of the subList 5 ints.subList(2, 4).clear(); 6 System.out.println(ints);

? ? 輸出結(jié)果是[0, 1, 4, 5, 6],結(jié)果是不是像調(diào)用了removeRange(int fromIndex,int toIndex)!哈哈哈,就是這樣的。但是為什么效果相同呢?是不是調(diào)用了removeRange(int fromIndex,int toIndex)呢?這個(gè)問題將領(lǐng)寫一篇博文討論。

? ? ?《ArrayList removeRange方法深入分析》:http://www.cnblogs.com/hzmark/archive/2012/12/19/ArrayList_removeRange.html

? ? set(int index,E element)

1 public E set(int index, E element) { 2 RangeCheck(index); 3 4 E oldValue = (E) elementData[index]; 5 elementData[index] = element; 6 return oldValue; 7 }

? ? 首先檢查范圍,用新元素替換舊元素并返回舊元素。

? ? size()

? ? size()方法直接返回size。

? ? toArray()

1 public Object[] toArray() { 2 return Arrays.copyOf(elementData, size); 3 }

? ? 調(diào)用Arrays.copyOf將返回一個(gè)數(shù)組,數(shù)組內(nèi)容是size個(gè)elementData的元素,即拷貝elementData從0至size-1位置的元素到新數(shù)組并返回。

? ? toArray(T[] a)

1 public <T> T[] toArray(T[] a) { 2 if (a.length < size) 3 // Make a new array of a's runtime type, but my contents: 4 return (T[]) Arrays.copyOf(elementData, size, a.getClass()); 5 System.arraycopy(elementData, 0, a, 0, size); 6 if (a.length > size) 7 a[size] = null; 8 return a; 9 }

? ? 如果傳入數(shù)組的長(zhǎng)度小于size,返回一個(gè)新的數(shù)組,大小為size,類型與傳入數(shù)組相同。所傳入數(shù)組長(zhǎng)度與size相等,則將elementData復(fù)制到傳入數(shù)組中并返回傳入的數(shù)組。若傳入數(shù)組長(zhǎng)度大于size,除了復(fù)制elementData外,還將把返回?cái)?shù)組的第size個(gè)元素置為空。

? ? trimToSize()

1 public void trimToSize() { 2 modCount++; 3 int oldCapacity = elementData.length; 4 if (size < oldCapacity) { 5 elementData = Arrays.copyOf(elementData, size); 6 } 7 }

? ? 由于elementData的長(zhǎng)度會(huì)被拓展,size標(biāo)記的是其中包含的元素的個(gè)數(shù)。所以會(huì)出現(xiàn)size很小但elementData.length很大的情況,將出現(xiàn)空間的浪費(fèi)。trimToSize將返回一個(gè)新的數(shù)組給elementData,元素內(nèi)容保持不變,length很size相同,節(jié)省空間。

?

? ? 學(xué)習(xí)Java最好的方式還必須是讀源碼。讀完源碼你才會(huì)發(fā)現(xiàn)這東西為什么是這么玩的,有哪些限制,關(guān)鍵點(diǎn)在哪里等等。而且這些源碼都是大牛們寫的,你能從中學(xué)習(xí)到很多。?

?

?

? ??

轉(zhuǎn)載于:https://www.cnblogs.com/hzmark/archive/2012/12/20/ArrayList.html

總結(jié)

以上是生活随笔為你收集整理的ArrayList源码分析(基于JDK1.6)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。