ArrayList基於數組實現,是一個動態的數組隊列,空間(增刪)效率不高,時間(查詢)效率很高。可是它和Java中的數組又不同,它的容量能夠自動增加。當集合中的元素超出這個容量,便會進行擴容操做。擴容操做也是ArrayList 的一個性能消耗比較大的地方,因此若咱們能夠提早預知數據的規模,應該指定集合的大小,去構建ArrayList實例,以減小擴容次數,提升效率。或者在須要擴容的時候,手動調用 ensureCapacity(int minCapacity) 方法擴容。 html
ArrayList繼承了AbstractList,實現了RandomAccess、Cloneable和Serializable接口。java
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
AbstractList又繼承了AbstractCollection實現了List接口,它是一個數組隊列,提供了相關的添加、刪除、修改、遍歷等功能。api
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { /** * Sole constructor. (For invocation by subclass constructors, typically * implicit.) */ protected AbstractList() { }
實現了RandomAccess接口,提供了隨機訪問功能,實際上就是經過下標序號進行快速訪問。
實現了Cloneable接口,即覆蓋了函數clone(),能被克隆。
實現了Serializable接口,支持序列化,也就意味了ArrayList可以經過序列化傳輸。數組
java.lang.Object ↳ java.util.AbstractCollection<E> ↳ java.util.AbstractList<E> ↳ java.util.ArrayList<E> public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {}
API詳解安全
一、elementData 是"Object[]類型的數組",它保存了添加到ArrayList中的元素。實際上,elementData是個動態數組,咱們能經過構造函數 ArrayList(int initialCapacity)來執行它的初始容量爲initialCapacity;若是經過不含參數的構造函數ArrayList()來建立ArrayList,則elementData的容量默認是10。elementData數組的大小會根據ArrayList容量的增加而動態的增加,具體的增加方式,請參考源碼分析中的ensureCapacity()函數。
二、size 則是動態數組的實際大小。多線程
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { private static final long serialVersionUID = 8683452581122892189L; /************************ 屬性 **********************************/ //默認初始容量 = 10 private static final int DEFAULT_CAPACITY = 10; //用於空實例的共享空數組實例。 private static final Object[] EMPTY_ELEMENTDATA = {}; //存儲ArrayList的元素的數組緩衝區。 //ArrayList的容量是該數組緩衝區的長度。 //任何空的ArrayList與elementData == EMPTY_ELEMENTDATA將被擴展爲添加第一個元素時的DEFAULT_CAPACITY。 //注:被transient關鍵字修飾的變量再也不能被序列化,一個靜態變量不論是否被transient修飾,均不能被序列化。 private transient Object[] elementData; //ArrayList的大小(它包含的元素數量)。 private int size; /************************ 構造函數 ********************************/ /** * 構造具備指定初始容量的空列表 * @param initialCapacity 列表的初始容量 * @throws IllegalArgumentException 若是指定的初始容量是負數 */ public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; } /** * 構造一個初始容量爲10的空列表 */ public ArrayList() { super(); this.elementData = EMPTY_ELEMENTDATA; } /** * 按照集合的迭代器返回的順序構造包含指定集合的元素的列表 * @param c 其元素將被放置到此列表中的集合 * @throws 若是指定的集合爲null,則爲NullPointerException */ public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); size = elementData.length; //判斷是否返回Object[].class,若沒有返回,則使用Arrays.copyOf 進行轉換 if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } /***************************** 方法 ****************************************/ /** *將此 ArrayList 實例的容量修改成列表的當前大小。 *應用程序可使用此操做最小化 ArrayList 實例的存儲。 */ public void trimToSize() { modCount++;//在java.util.AbstractList<E>中定義,用於計算對數組的操做次數 if (size < elementData.length) { elementData = Arrays.copyOf(elementData, size); } } /** * 若有必要,增長此 ArrayList 實例的容量,以確保由最小容量參數指定。 * @param minCapacity 所需的最小容量 */ public void ensureCapacity(int minCapacity) { int minExpand = (elementData != EMPTY_ELEMENTDATA) ? 0 : DEFAULT_CAPACITY; if (minCapacity > minExpand) { ensureExplicitCapacity(minCapacity); } } //確保集合內部的容量 private void ensureCapacityInternal(int minCapacity) { if (elementData == EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { modCount++; if (minCapacity - elementData.length > 0) grow(minCapacity); } /** *一些虛擬機保留數組中的一些標題字。 *嘗試分配較大的數組可能會致使OutOfMemoryError:請求的數組大小超過VM限制 * 注:怕超過VM限制,因此只用 Integer.MAX_VALUE - 8 設置MAX_ARRAY_SIZE的值! */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /** * 增長容量以確保它至少能夠容納由最小容量參數指定的元素數。 * @param minCapacity 所需的最小容量 */ private void grow(int minCapacity) { // overflow-conscious code 溢出-察覺代碼 int oldCapacity = elementData.length; //舊的容量大小 int newCapacity = oldCapacity + (oldCapacity >> 1); //oldCapacity >> 1 : >> 右移 至關於 oldCapacity/2 if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity);//看下面的hugeCapacity()方法,數組的最大容量不會超過MAX_ARRAY_SIZE // minCapacity一般接近於大小,因此這是一個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; } /** * 返回此列表中的元素數。獲取集合的大小 * @return 此列表中的元素數 */ public int size() { return size; } /** * 判斷是否爲空,若是集合爲沒有包含任何元素,返回 true */ public boolean isEmpty() { return size == 0; } /** *若是此列表包含指定的元素,則返回true。 更正式地, *當且僅當這個列表包含至少一個元素e使得(o == null?e == *null:o.equals(e))時, *返回true。 * @param o element whose presence in this list is to be tested * @return <tt>true</tt> if this list contains the specified element */ public boolean contains(Object o) { return indexOf(o) >= 0; } /** *返回此列表中指定元素的第一次出現的索引,若是此列表不包含元素, *則返回-1。 更正式地,返回最低索引i,使得(o == null?get(i)== null:o.equals(get(i))), *或-1,若是沒有這樣的索引。 * *返回:此列表中指定元素的第一次出現的索引,若是此列表不包含元素,則爲-1 */ 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; } /** * 返回此列表中指定元素的最後一次出現的索引,若是此列表不包含元素, *則返回-1。 更正式地,返回最高索引i,使得(o == null?get(i)== null:o.equals(get(i))), *或-1若是沒有這樣的索引。 * *返回:此列表中指定元素的最後一次出現的索引,若是此列表不包含元素,則爲-1 */ 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; } /** * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The * elements themselves are not copied.) * 返回此<tt> ArrayList </ tt>實例的淺拷貝。 (元素自己不被複制。) * @return a clone of this <tt>ArrayList</tt> instance */ public Object clone() { //實現了Cloneable接口,覆蓋了函數clone(),能被克隆。 try { @SuppressWarnings("unchecked") ArrayList<E> v = (ArrayList<E>) 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(); } } /** * 以正確的順序返回包含此列表中全部元素的數組(從第一個元素到最後一個元素)。 * * <p>This method acts as bridge between array-based and collection-based * APIs. * 此方法充當基於陣列和基於集合的API之間的橋樑 * @return an array containing all of the elements in this list in * proper sequence * 一個包含正確順序的列表中全部元素的數組 */ public Object[] toArray() { return Arrays.copyOf(elementData, size);//使用Arrays工具類 } /** * 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); } /** * 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; } /** * 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!! 增長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++; } /** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * 刪除此列表中指定位置的元素。 將任何後續元素向左移(從它們的索引中減去一個)。 * @param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException {@inheritDoc} */ 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, //public static native void arraycopy(Object src, int srcPos, // Object dest, int destPos,int length); //調用了本地的方法 : 將指定源數組的數組從指定位置開始複製到目標數組的指定位置。 elementData[--size] = null; // clear to let GC do its work 設置爲 null ,讓gc去回收 return oldValue; } /** * 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 * 從列表中刪除指定元素的第一次出現(若是存在)。 *若是列表不包含元素,則不會更改。 更正式地,刪除具備最低索引i的元素,使得(若是這樣的元素存在) *(o == null?get(i)== *null:o.equals(get(i)))。 *若是此列表包含指定的元素(或等效地,若是此列表做爲調用的結果更改),則返回true。 * * @param o element to be removed from this list, if present * @return <tt>true</tt> if this list contained the specified element 若是包含返回 true */ 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 remove method that skips bounds checking and does not * return the value removed. * 私有刪除方法,跳過邊界檢查,不返回值刪除。 */ 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 } /** * Removes all of the elements from this list. The list will * be empty after this call returns. *今後列表中刪除全部元素。 此調用返回後,列表將爲空 */ public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } /** * 將指定集合中的全部元素以指定集合的Iterator返回的順序追加到此列表的末尾。 *若是在操做正在進行時修改指定的集合,則此操做的行爲是未定義的。 *(這意味着若是指定的集合是此列表,則此調用的行爲是未定義的,而且此列表不是空的。) * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @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 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; } /** * Removes from this list all of the elements whose index is between * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. * Shifts any succeeding elements to the left (reduces their index). *今後列表中刪除其索引在fromIndex(包含)和toIndex(排除)之間的全部元素。 *將任何後續元素向左移(減小其索引)。 */ protected void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex; 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; } /** * 檢查給定的索引是否在範圍內。 若是沒有,則拋出一個適當的運行時異常。 * 私有方法 */ private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** * A version of rangeCheck used by add and addAll. * 由add和addAll使用的rangeCheck的版本。 * 私有方法 */ private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** * Removes from this list all of its elements that are contained in the * specified collection. * 今後列表中刪除包含在指定集合中的全部元素。 * @param c collection containing elements to be removed from this list * @return {@code true} if this list changed as a result of the call * 若是此列表因爲調用而更改 則返回true */ public boolean removeAll(Collection<?> c) { return batchRemove(c, false); } /** * Retains only the elements in this list that are contained in the * specified collection. In other words, removes from this list all * of its elements that are not contained in the specified collection. *僅保留此列表中包含在指定集合中的元素。 換句話說, *今後列表中刪除未包含在指定集合中的全部元素。 * @param c collection containing elements to be retained in this list * @return {@code true} if this list changed as a result of the call * 若是此列表因爲調用而更改 則返回true */ public boolean retainAll(Collection<?> 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) elementData[w++] = elementData[r]; } finally { // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. //保留與AbstractCollection的行爲兼容性,即便c.contains()拋出。 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; } /** * 將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(); } } /** * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is, * deserialize it). *從流重構 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(); } } } /** *對列表中的元素返回一個列表迭代器(以正確的順序), *從列表中指定的位置開始。 指定的索引指示由初始調用返回到next的第一個元素。 *對上一個的初始調用將返回具備指定索引減1的元素。 * *返回的列表迭代器是fail-fast的。 * @throws IndexOutOfBoundsException {@inheritDoc} */ public ListIterator<E> listIterator(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); } /** * Returns a list iterator over the elements in this list (in proper * sequence). *返回此列表中的元素(按正確順序)的列表迭代器。 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. *返回的列表迭代器是fail-fast的。 * @see #listIterator(int) */ public ListIterator<E> listIterator() { return new ListItr(0); } /** * Returns an iterator over the elements in this list in proper sequence. *以正確的順序返回此列表中的元素的迭代器。 * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>. *返回的列表迭代器是fail-fast的。 * @return an iterator over the elements in this list in proper sequence */ public Iterator<E> iterator() { return new Itr(); } /** * An optimized version of AbstractList.Itr * AbstractList.Itr的優化版本 */ 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(); } } /** * An optimized version of AbstractList.ListItr * AbstractList.ListItr的優化版本 */ private class ListItr extends Itr implements ListIterator<E> { ListItr(int index) { super(); cursor = index; } public boolean hasPrevious() { return cursor != 0; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } @SuppressWarnings("unchecked") public E previous() { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; return (E) elementData[lastRet = i]; } public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.set(lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void add(E e) { checkForComodification(); try { int i = cursor; ArrayList.this.add(i, e); cursor = i + 1; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } //subList 以及後面的代碼不在作分析,實際狀況中不多用到,須要的時候,請自行看源碼分析 }
一、ArrayList 本質實現方法是用數組!是非同步的,即多線程非安全
二、初始化容量 = 10 ,最大容量不會超過 MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8
三、indexOf和lastIndexOf 查找元素,若元素不存在,則返回-1
四、當ArrayList容量不足以容納所有元素時,ArrayList會從新設置容量:新的容量=(原始容量x3)/2
五、ArrayList的克隆函數,便是將所有元素克隆到一個數組中
六、ArrayList實現java.io.Serializable的方式。當寫入到輸出流時,先寫入「容量」,再依次寫入「每個元素」;當讀出輸入流時,先讀取「容量」,再依次讀取「每個元素」
七、從代碼中能夠看出,當容量不夠時,每次增長元素,都要將原來的元素拷貝到一個新的數組中,很是之耗時,也所以建議在事先能肯定元素數量的狀況下,才使用ArrayList,不然建議使用LinkedList
八、ArrayList基於數組實現,能夠經過下標索引直接查找到指定位置的元素,所以查找效率高,但每次插入或刪除元素,就要大量地移動元素,插入刪除元素的效率低
九、在查找給定元素索引值等的方法中,源碼都將該元素的值分爲null和不爲null兩種狀況處理,ArrayList中容許元素爲nullapp
import java.util.*; import java.util.concurrent.*; /* * @desc ArrayList遍歷方式和效率的測試程序。 * * @author skywang */ public class ArrayListRandomAccessTest { public static void main(String[] args) { List list = new ArrayList(); for (int i=0; i<100000; i++) list.add(i); //isRandomAccessSupported(list); iteratorThroughRandomAccess(list) ; iteratorThroughIterator(list) ; iteratorThroughFor2(list) ; } private static void isRandomAccessSupported(List list) { if (list instanceof RandomAccess) { System.out.println("RandomAccess implemented!"); } else { System.out.println("RandomAccess not implemented!"); } } //經過索引值去遍歷 效率最快 public static void iteratorThroughRandomAccess(List list) { long startTime; long endTime; startTime = System.currentTimeMillis(); for (int i=0; i<list.size(); i++) { list.get(i); } endTime = System.currentTimeMillis(); long interval = endTime - startTime; System.out.println("iteratorThroughRandomAccess:" + interval+" ms"); //輸出 3 ms } //迭代器遍歷 效率最慢 public static void iteratorThroughIterator(List list) { long startTime; long endTime; startTime = System.currentTimeMillis(); for(Iterator iter = list.iterator(); iter.hasNext(); ) { iter.next(); } endTime = System.currentTimeMillis(); long interval = endTime - startTime; System.out.println("iteratorThroughIterator:" + interval+" ms"); // 輸出 8 ms } //for循環遍歷 效率低於索引遍歷 高於迭代器 public static void iteratorThroughFor2(List list) { long startTime; long endTime; startTime = System.currentTimeMillis(); for(Object obj:list) ; endTime = System.currentTimeMillis(); long interval = endTime - startTime; System.out.println("iteratorThroughFor2:" + interval+" ms"); //輸出 5 ms } }
遍歷ArrayList時,經過索引序號訪問效率最高,而使用迭代器的效率最低。dom
ArrayList提供了2個toArray()函數函數
Object[] toArray() <T> T[] toArray(T[] contents)
調用 toArray() 函數會拋出「java.lang.ClassCastException」異常,可是調用 toArray(T[] contents) 能正常返回 T[]。
toArray() 會拋出異常是由於 toArray() 返回的是 Object[] 數組,將 Object[] 轉換爲其它類型(如如,將Object[]轉換爲的Integer[])則會拋出「java.lang.ClassCastException」異常,由於Java不支持向下轉型。具體的能夠參考前面ArrayList.java的源碼介紹部分的toArray()。
解決該問題的辦法是調用 <T> T[] toArray(T[] contents) , 而不是 Object[] toArray()。工具
// toArray(T[] contents)調用方式一 public static Integer[] vectorToArray1(ArrayList<Integer> v) { Integer[] newText = new Integer[v.size()]; v.toArray(newText); return newText; } // toArray(T[] contents)調用方式二。最經常使用! public static Integer[] vectorToArray2(ArrayList<Integer> v) { Integer[] newText = (Integer[])v.toArray(new Integer[0]); return newText; } // toArray(T[] contents)調用方式三 public static Integer[] vectorToArray3(ArrayList<Integer> v) { Integer[] newText = new Integer[v.size()]; Integer[] newStrings = (Integer[])v.toArray(newText); return newStrings; }
若是內容對你有幫助但願點贊收藏謝謝!!!