ArrayList是List接口的可變數(shù)組的實現(xiàn)。實現(xiàn)了所有可選列表操作,并允許包括 null 在內(nèi)的所有元素。除了實現(xiàn) List 接口外,此類還提供一些方法來操作內(nèi)部用來存儲列表的數(shù)組的大小。
每個ArrayList實例都有一個容量,該容量是指用來存儲列表元素的數(shù)組的大小。它總是至少等于列表的大小。隨著向ArrayList中不斷添加元素,其容量也自動增長。自動增長會帶來數(shù)據(jù)向新數(shù)組的重新拷貝,因此,如果可預(yù)知數(shù)據(jù)量的多少,可在構(gòu)造ArrayList時指定其容量。在添加大量元素前,應(yīng)用程序也可以使用ensureCapacity操作來增加ArrayList實例的容量,這可以減少遞增式再分配的數(shù)量。
注意,此實現(xiàn) 不是同步 的。如果多個線程同時訪問一個ArrayList實例,而其中至少一個線程從結(jié)構(gòu)上修改了列表,那么它必須保持外部同步。這通常是通過同步那些用來封裝列表的對象來實現(xiàn)的。但如果沒有這樣的對象存在,則該列表需要運用{@link Collections#synchronizedSet Collections.synchronizedSet}來進行“包裝”,該方法最好是在創(chuàng)建列表對象時完成,為了避免對列表進行突發(fā)的非同步操作。
List list = Collections.synchronizedList(new ArrayList(...));建議在單線程中才使用ArrayList,而在多線程中可以選擇Vector或者CopyOnWriteArrayList。
二、ArrayList源碼解析
1. ArrayList類結(jié)構(gòu)
//通過ArrayList實現(xiàn)的接口可知,其支持隨機訪問,能被克隆,支持序列化public class ArrayList<E> extends AbstractList<E> implements List<E>, Randomaccess, Cloneable, java.io.Serializable{ //序列版本號 PRivate static final long serialVersionUID = 8683452581122892189L; //默認初始容量 private static final int DEFAULT_CAPACITY = 10; //被用于空實例的共享空數(shù)組實例 private static final Object[] EMPTY_ELEMENTDATA = {}; //被用于默認大小的空實例的共享數(shù)組實例。其與EMPTY_ELEMENTDATA的區(qū)別是:當(dāng)我們向數(shù)組中添加第一個元素時,知道數(shù)組該擴充多少。 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; /** * Object[]類型的數(shù)組,保存了添加到ArrayList中的元素。ArrayList的容量是該Object[]類型數(shù)組的長度 * 當(dāng)?shù)谝粋€元素被添加時,任何空ArrayList中的elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA將會被 * 擴充到DEFAULT_CAPACITY(默認容量)。 */ transient Object[] elementData; //非private是為了方便嵌套類的訪問 // ArrayList的大小(指其所含的元素個數(shù)) private int size; ...... }View CodeArrayList包含了兩個重要的對象:elementData 和 size。
(01) elementData 是"Object[] 類型的數(shù)組",它保存了添加到ArrayList中的元素。實際上,elementData是個動態(tài)數(shù)組,我們能通過構(gòu)造函數(shù) ArrayList(int initialCapacity)來執(zhí)行它的初始容量為initialCapacity;如果通過不含參數(shù)的構(gòu)造函數(shù)ArrayList()來創(chuàng)建 ArrayList,則elementData的容量默認是10。elementData數(shù)組的大小會根據(jù)ArrayList容量的增長而動態(tài)的增長,具 體的增長方式,請參考源碼分析中的ensureCapacity()函數(shù)。
(02) size 則是動態(tài)數(shù)組的實際大小。
2. 構(gòu)造函數(shù)
ArrayList提供了三種方式的構(gòu)造器,可以構(gòu)造一個默認初始容量為10的空列表、構(gòu)造一個指定初始容量的空列表以及構(gòu)造一個包含指定collection的元素的列表,這些元素按照該collection的迭代器返回的順序排列的。
/** * 構(gòu)造一個指定初始容量的空列表 * @param initialCapacity ArrayList的初始容量 * @throws IllegalArgumentException 如果給定的初始容量為負值 */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); }}// 構(gòu)造一個默認初始容量為10的空列表public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;}/** * 構(gòu)造一個包含指定collection的元素的列表,這些元素按照該collection的迭代器返回的順序排列的 * @param c 包含用于去構(gòu)造ArrayList的元素的collection * @throws NullPointerException 如果指定的collection為空 */public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray()可能不會正確地返回一個 Object[]數(shù)組,那么使用Arrays.copyOf()方法 if (elementData.getClass() != Object[].class) //Arrays.copyOf()返回一個 Object[].class類型的,大小為size,元素為elementData[0,...,size-1] elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; }}View Code此處重點說明一下, ArrayList是如何構(gòu)造一個默認初始容量為10的空列表的 ?
// 構(gòu)造一個默認初始容量為10的空列表public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; //DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}}//而在在JDK1.6中,其構(gòu)造函數(shù)為public ArrayList() { this(10); //public ArrayList(int initialCapacity)中this.elementData = new Object[initialCapacity];}ArrayList構(gòu)造一個默認初始容量為10的空列表:
1) 初始情況:elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; size = 0;
2) 當(dāng)向數(shù)組中添加第一個元素時,通過add(E e)方法中調(diào)用的ensureCapacityInternal(size + 1)方法,即ensureCapacityInternal(1);
3) 在ensureCapacityInternal(int minCapacity)方法中,可得的minCapacity=DEFAULT_CAPACITY=10,然后再調(diào)用ensureExplicitCapacity(minCapacity)方法,即ensureExplicitCapacity(10);
4) 在ensureExplicitCapacity(minCapacity)方法中調(diào)用grow(minCapacity)方法,即grow(10),此處為真正具體的數(shù)組擴容的算法,在此方法中,通過 elementData = Arrays.copyOf(elementData,10 ) 具體實現(xiàn)了elementData數(shù)組初始容量為10的構(gòu)造。
3. 調(diào)整數(shù)組的容量
從add()與addAll()方法中可以看出,每當(dāng)向數(shù)組中添加元素時,都要去檢查添加元素后的個數(shù)是否會超出當(dāng)前數(shù)組的長度,如果超出,數(shù)組將會進行擴容,以滿足添加數(shù)據(jù)的需求。數(shù)組擴容實質(zhì)上是通過私有的方法ensureCapacityInternal(int minCapacity) -> ensureExplicitCapacity(int minCapacity) -> grow(int minCapacity)來實現(xiàn)的,但在jdk1.8中,向用戶提供了一個public的方法ensureCapacity(int minCapacity)使用戶可以手動的 設(shè)置 ArrayList實例的容量,以減少遞增式再分配的數(shù)量。此處與jdk1.6中直接通過一個公開的方法ensureCapacity(int minCapacity)來實現(xiàn)數(shù)組容量的調(diào)整有區(qū)別。
/** * public方法,讓用戶能手動設(shè)置ArrayList的容量 * @param minCapacity 期望的最小容量 */ public void ensureCapacity(int minCapacity) { int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) // any size if not default element table ? 0 // larger than default for default empty table. It's already // supposed to be at default size. : DEFAULT_CAPACITY; if (minCapacity > minExpand) { ensureExplicitCapacity(minCapacity); } } private void ensureCapacityInternal(int minCapacity) { //當(dāng)elementData為空時,ArrayList的初始容量最小為DEFAULT_CAPACITY(10) 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); } //數(shù)組可被分配的最大容量;當(dāng)需要的數(shù)組尺寸超過VM的限制時,可能導(dǎo)致OutOfMemoryError private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /** * 增加數(shù)組的容量,確保它至少能容納指定的最小容量的元素量 * @param minCapacity 期望的最小容量 */ private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; //注意此處擴充capacity的方式是將其向右一位再加上原來的數(shù),實際上是擴充了1.5倍 int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); //設(shè)置數(shù)組可被分配的最大容量 // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); } private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; }View Code附:jdk1.6中ensureCapacity(int minCapacity)方法:
// 確定ArrarList的容量。// 若ArrayList的容量不足以容納當(dāng)前的全部元素,設(shè)置 新的容量=“(原始容量x3)/2 + 1” public void ensureCapacity(int minCapacity) { modCount++; // 將“修改統(tǒng)計數(shù)”+1 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); } }View Code為什么ArrayList自動容量擴充選擇擴充1.5倍?
這種算法構(gòu)造出來的新的數(shù)組長度的增量都會比上一次大( 而且是越來越大) ,即認為客戶需要增加的數(shù)據(jù)很多,而避免頻繁newInstance 的情況。
4.添加元素
ArrayList提供了add(E e)、add(int index, E element)、addAll(Collection<? extends E> c)、addAll(int index, Collection<? extends E> c)這些添加元素的方法。
//將指定的元素(E e)添加到此列表的尾部 public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } //將指定的元素(E e)插入到列表的指定位置(index) public void add(int index, E element) { rangeCheckForAdd(index); //判斷參數(shù)index是否IndexOutOfBoundsException ensureCapacityInternal(size + 1); // Increments modCount!! 如果數(shù)組長度不足,將進行擴容 System.arraycopy(elementData, index, elementData, index + 1, size - index); //將源數(shù)組中從index位置開始后的size-index個元素統(tǒng)一后移一位 elementData[index] = element; size++; } /** * 按照指定collection的迭代器所返回的元素順序,將該collection中的所有元素添加到此列表的尾部 * @throws NullPointerException if the specified collection is null */ public boolean addAll(Collection<? extends E> c) { Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); // Increments modCount //將數(shù)組a[0,...,numNew-1]復(fù)制到數(shù)組elementData[size,...,size+numNew-1] System.arraycopy(a, 0, elementData, size, numNew); size += numNew; return numNew != 0; } /** * 從指定的位置開始,將指定collection中的所有元素插入到此列表中,新元素的順序為指定collection的迭代器所返回的元素順序 * @throws IndexOutOfBoundsException {@inheritDoc} * @throws NullPointerException if the specified collection is null */ public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); //判斷參數(shù)index是否IndexOutOfBoundsException Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); // Increments modCount int numMoved = size - index; if (numMoved > 0) //先將數(shù)組elementData[index,...,index+numMoved-1]復(fù)制到elementData[index+numMoved,...,index+2*numMoved-1] //即,將源數(shù)組中從index位置開始的后numMoved個元素統(tǒng)一后移numNew位 System.arraycopy(elementData, index, elementData, index + numNew, numMoved); //再將數(shù)組a[0,...,numNew-1]復(fù)制到數(shù)組elementData[index,...,index+numNew-1] System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; }View Code5.刪除元素
ArrayList提供了remove(int index)、remove(Object o)、clear()、removeRange(int fromIndex, int toIndex)、removeAll(Collection<?> c)、retainAll(Collection<?> c)這些刪除元素的方法。
/** * 移除此列表中指定位置上的元素 * @param index 需被移除的元素的索引 * @return the element 被移除的元素值 * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) { rangeCheck(index); //判斷index是否 <= size modCount++; E oldValue = elementData(index); //將數(shù)組elementData中index位置之后的所有元素向前移一位 int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; //將原數(shù)組最后一個位置置為null,由GC清理 return oldValue; } //移除ArrayList中首次出現(xiàn)的指定元素(如果存在),ArrayList中允許存放重復(fù)的元素 public boolean remove(Object o) { // 由于ArrayList中允許存放null,因此下面通過兩種情況來分別處理。 if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); //私有的移除方法,跳過index參數(shù)的邊界檢查以及不返回任何值 return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; } //私有的刪除指定位置元素的方法,跳過index參數(shù)的邊界檢查以及不返回任何值 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 } //清空ArrayList,將全部的元素設(shè)為null public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } //刪除ArrayList中從fromIndex(包含)到toIndex(不包含)之間所有的元素,共移除了toIndex-fromIndex個元素 protected void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex; //需向前移動的元素的個數(shù) System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); // clear to let GC do its work int newSize = size - (toIndex-fromIndex); for (int i = newSize; i < size; i++) { elementData[i] = null; } size = newSize; } //刪除ArrayList中包含在指定容器c中的所有元素 public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c); //檢查指定的對象c是否為空 return batchRemove(c, false); } //移除ArrayList中不包含在指定容器c中的所有元素,與removeAll(Collection<?> c)正好相反 public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, true); } private boolean batchRemove(Collection<?> c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; //讀寫雙指針 boolean modified = false; try { for (; r < size; r++) if (c.contains(elementData[r]) == complement) //判斷指定容器c中是否含有elementData[r]元素 elementData[w++] = elementData[r]; } finally { // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } if (w != size) { // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; }View Code6.修改元素
ArrayList提供了set(int index, E element)方法來修改指定索引上的值。
//將指定索引上的值替換為新值,并返回舊值 public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; }View Code7.查找元素
ArrayList提供了get(int index)、contains(Object o)、indexOf(Object o)、lastIndexOf(Object o)、get(int index)這些查找元素的方法。
//判斷ArrayList中是否包含Object(o)public boolean contains(Object o) { return indexOf(o) >= 0;}//正向查找,返回ArrayList中元素Object o第一次出現(xiàn)的位置,如果元素不存在,則返回-1public 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;}//逆向查找,返回ArrayList中元素Object o最后一次出現(xiàn)的位置,如果元素不存在,則返回-1public 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;}@SuppressWarnings("unchecked")E elementData(int index) { return (E) elementData[index];}//返回指定索引處的值public E get(int index) { rangeCheck(index); return elementData(index); //實質(zhì)上return (E) elementData[index]}View Code8.其他public方法
trimToSize()、size()、isEmpty()、clone()、toArray()、toArray(T[] a)
//將底層數(shù)組的容量調(diào)整為當(dāng)前列表保存的實際元素的大小的功能 public void trimToSize() { modCount++; if (size < elementData.length) { elementData = (size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size); } } //返回ArrayList的大小(元素個數(shù)) public int size() { return size; }//判斷ArrayList是否為空 public boolean isEmpty() { return size == 0; } //返回此 ArrayList實例的淺拷貝 public Object clone() { try { ArrayList<?> v = (ArrayList<?>) super.clone(); v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(e); } } //返回一個包含ArrayList中所有元素的數(shù)組 public Object[] toArray() { return Arrays.copyOf(elementData, size); } //如果給定的參數(shù)數(shù)組長度足夠,則將ArrayList中所有元素按序存放于參數(shù)數(shù)組中,并返回 //如果給定的參數(shù)數(shù)組長度小于ArrayList的長度,則返回一個新分配的、長度等于ArrayList長度的、包含ArrayList中所有元素的新數(shù)組 @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { if (a.length < size) // Make a new array of a's runtime type, but my contents: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } View Code支持序列化的寫入函數(shù) writeObject(java.io.ObjectOutputStream s)和讀取函數(shù) readObject(java.io.ObjectInputStream s)
//序列化:將ArrayList的“大小,所有的元素值”都寫入到輸出流中 private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ // Write out element count, and any hidden stuff int expectedModCount = modCount; s.defaultWriteObject(); // Write out size as capacity for behavioural compatibility with clone() s.writeInt(size); // Write out all elements in the proper order. for (int i=0; i<size; i++) { s.writeObject(elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } //反序列化:先將ArrayList的“大小”讀出,然后將“所有的元素值”讀出 private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { elementData = EMPTY_ELEMENTDATA; // Read in size, and any hidden stuff s.defaultReadObject(); // Read in capacity s.readInt(); // ignored if (size > 0) { // be like clone(), allocate array based upon size not capacity ensureCapacityInternal(size); Object[] a = elementData; // Read in all elements in the proper order. for (int i=0; i<size; i++) { a[i] = s.readObject(); } } }View Code關(guān)于java的序列化與反序列化可以參考: Java對象的序列化和反序列化
9.ArrayList的四種遍歷方式
1)通過迭代器Iterator遍歷:
Iterator iter = list.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); }2)通過迭代器ListIterator遍歷:
ListIterator<String> lIter = list.listIterator(); //順向遍歷 while(lIter.hasNext()){ System.out.println(lIter.next()); } //逆向遍歷 while(lIter.hasprevious()){ System.out.println(lIter.previous()); }Iterator與ListIterator主要的區(qū)別:
①Iterator可以應(yīng)用于所有的集合,Set、List和Map和這些集合的子類型。而ListIterator只能用于List及其子類型;
②Iterator只能實現(xiàn)順序向后遍歷,ListIterator可實現(xiàn)順序向后遍歷和逆向(順序向前)遍歷;
③Iterator只能實現(xiàn)remove操作,ListIterator可以實現(xiàn)remove操作,add操作,set操作。
3)隨機訪問,通過索引值去遍歷,由于ArrayList實現(xiàn)了RandomAccess接口
int size = list.size(); for (int i=0; i<size; i++) { System.out.println(list.get(i)); }4)foreach循環(huán)遍歷
for(String str:list) { System.out.println(str); }foreach與迭代器:在Java SE5引入了新的被稱為Iterable接口,該接口包含一個能夠產(chǎn)生Iterator的Iterator()方法,并且Iterable接口被foreach用來在序列中移動。因此 如果你創(chuàng)建了任何實現(xiàn)Iterable的類,都可以將它用于foreach語句中 。
10. Fail-Fast機制
ArrayList也采用了快速失敗的機制,通過記錄modCount參數(shù)來實現(xiàn)。在面對并發(fā)的修改時,迭代器很快就會完全失敗,而不是冒著在將來某個不確定時間發(fā)生任意不確定行為的風(fēng)險。
新聞熱點
疑難解答