前面,咱們學完了List的所有內容(ArrayList, LinkedList, Vector, Stack)。html
Java 集合系列03之 ArrayList詳細介紹(源碼解析)和使用示例 java
Java 集合系列04之 fail-fast總結(經過ArrayList來講明fail-fast的原理、解決辦法) 數組
Java 集合系列05之 LinkedList詳細介紹(源碼解析)和使用示例安全
Java 集合系列06之 Vector詳細介紹(源碼解析)和使用示例多線程
Java 集合系列07之 Stack詳細介紹(源碼解析)和使用示例框架
如今,咱們再回頭看看總結一下List。內容包括:
第1部分 List歸納
第2部分 List使用場景
第3部分 LinkedList和ArrayList性能差別分析
第4部分 Vector和ArrayList比較
dom
轉載請註明出處:http://www.cnblogs.com/skywang12345/p/3308900.html函數
先回顧一下List的框架圖源碼分析
(01) List 是一個接口,它繼承於Collection的接口。它表明着有序的隊列。
(02) AbstractList 是一個抽象類,它繼承於AbstractCollection。AbstractList實現List接口中除size()、get(int location)以外的函數。
(03) AbstractSequentialList 是一個抽象類,它繼承於AbstractList。AbstractSequentialList 實現了「鏈表中,根據index索引值操做鏈表的所有函數」。性能
(04) ArrayList, LinkedList, Vector, Stack是List的4個實現類。
ArrayList 是一個數組隊列,至關於動態數組。它由數組實現,隨機訪問效率高,隨機插入、隨機刪除效率低。
LinkedList 是一個雙向鏈表。它也能夠被看成堆棧、隊列或雙端隊列進行操做。LinkedList隨機訪問效率低,但隨機插入、隨機刪除效率低。
Vector 是矢量隊列,和ArrayList同樣,它也是一個動態數組,由數組實現。可是ArrayList是非線程安全的,而Vector是線程安全的。
Stack 是棧,它繼承於Vector。它的特性是:先進後出(FILO, First In Last Out)。
學東西的最終目的是爲了可以理解、使用它。下面先歸納的說明一下各個List的使用場景,後面再分析緣由。
若是涉及到「棧」、「隊列」、「鏈表」等操做,應該考慮用List,具體的選擇哪一個List,根據下面的標準來取捨。
(01) 對於須要快速插入,刪除元素,應該使用LinkedList。
(02) 對於須要快速隨機訪問元素,應該使用ArrayList。
(03) 對於「單線程環境」 或者 「多線程環境,但List僅僅只會被單個線程操做」,此時應該使用非同步的類(如ArrayList)。
對於「多線程環境,且List可能同時被多個線程操做」,此時,應該使用同步的類(如Vector)。
經過下面的測試程序,咱們來驗證上面的(01)和(02)結論。參考代碼以下:
運行結果以下:
Stack : insert 100000 elements into the 1st position use time:1640 ms Vector : insert 100000 elements into the 1st position use time:1607 ms LinkedList : insert 100000 elements into the 1st position use time:29 ms ArrayList : insert 100000 elements into the 1st position use time:1617 ms Stack : read 100000 elements by position use time:9 ms Vector : read 100000 elements by position use time:6 ms LinkedList : read 100000 elements by position use time:10809 ms ArrayList : read 100000 elements by position use time:5 ms Stack : delete 100000 elements from the 1st position use time:1916 ms Vector : delete 100000 elements from the 1st position use time:1910 ms LinkedList : delete 100000 elements from the 1st position use time:15 ms ArrayList : delete 100000 elements from the 1st position use time:1909 ms
從中,咱們能夠發現:
插入10萬個元素,LinkedList所花時間最短:29ms。
刪除10萬個元素,LinkedList所花時間最短:15ms。
遍歷10萬個元素,LinkedList所花時間最長:10809 ms;而ArrayList、Stack和Vector則相差很少,都只用了幾秒。
考慮到Vector是支持同步的,而Stack又是繼承於Vector的;所以,得出結論:
(01) 對於須要快速插入,刪除元素,應該使用LinkedList。
(02) 對於須要快速隨機訪問元素,應該使用ArrayList。
(03) 對於「單線程環境」 或者 「多線程環境,但List僅僅只會被單個線程操做」,此時應該使用非同步的類。
下面咱們看看爲何LinkedList中插入元素很快,而ArrayList中插入元素很慢!
LinkedList.java中向指定位置插入元素的代碼以下:
// 在index前添加節點,且節點的值爲element public void add(int index, E element) { addBefore(element, (index==size ? header : entry(index))); } // 獲取雙向鏈表中指定位置的節點 private Entry<E> entry(int index) { if (index < 0 || index >= size) throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+size); Entry<E> e = header; // 獲取index處的節點。 // 若index < 雙向鏈表長度的1/2,則從前向後查找; // 不然,從後向前查找。 if (index < (size >> 1)) { for (int i = 0; i <= index; i++) e = e.next; } else { for (int i = size; i > index; i--) e = e.previous; } return e; } // 將節點(節點數據是e)添加到entry節點以前。 private Entry<E> addBefore(E e, Entry<E> entry) { // 新建節點newEntry,將newEntry插入到節點e以前;而且設置newEntry的數據是e Entry<E> newEntry = new Entry<E>(e, entry, entry.previous); // 插入newEntry到鏈表中 newEntry.previous.next = newEntry; newEntry.next.previous = newEntry; size++; modCount++; return newEntry; }
從中,咱們能夠看出:經過add(int index, E element)向LinkedList插入元素時。先是在雙向鏈表中找到要插入節點的位置index;找到以後,再插入一個新節點。
雙向鏈表查找index位置的節點時,有一個加速動做:若index < 雙向鏈表長度的1/2,則從前向後查找; 不然,從後向前查找。
接着,咱們看看ArrayList.java中向指定位置插入元素的代碼。以下:
// 將e添加到ArrayList的指定位置 public void add(int index, E element) { if (index > size || index < 0) throw new IndexOutOfBoundsException( "Index: "+index+", Size: "+size); ensureCapacity(size+1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; }
ensureCapacity(size+1) 的做用是「確認ArrayList的容量,若容量不夠,則增長容量。」
真正耗時的操做是 System.arraycopy(elementData, index, elementData, index + 1, size - index);
Sun JDK包的java/lang/System.java中的arraycopy()聲明以下:
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
arraycopy()是個JNI函數,它是在JVM中實現的。sunJDK中看不到源碼,不過能夠在OpenJDK包中看到的源碼。網上有對arraycopy()的分析說明,請參考:System.arraycopy源碼分析
實際上,咱們只須要了解: System.arraycopy(elementData, index, elementData, index + 1, size - index); 會移動index以後全部元素便可。這就意味着,ArrayList的add(int index, E element)函數,會引發index以後全部元素的改變!
經過上面的分析,咱們就能理解爲何LinkedList中插入元素很快,而ArrayList中插入元素很慢。
「刪除元素」與「插入元素」的原理相似,這裏就再也不過多說明。
接下來,咱們看看 「爲何LinkedList中隨機訪問很慢,而ArrayList中隨機訪問很快」。
先看看LinkedList隨機訪問的代碼
// 返回LinkedList指定位置的元素 public E get(int index) { return entry(index).element; } // 獲取雙向鏈表中指定位置的節點 private Entry<E> entry(int index) { if (index < 0 || index >= size) throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+size); Entry<E> e = header; // 獲取index處的節點。 // 若index < 雙向鏈表長度的1/2,則從前前後查找; // 不然,從後向前查找。 if (index < (size >> 1)) { for (int i = 0; i <= index; i++) e = e.next; } else { for (int i = size; i > index; i--) e = e.previous; } return e; }
從中,咱們能夠看出:經過get(int index)獲取LinkedList第index個元素時。先是在雙向鏈表中找到要index位置的元素;找到以後再返回。
雙向鏈表查找index位置的節點時,有一個加速動做:若index < 雙向鏈表長度的1/2,則從前向後查找; 不然,從後向前查找。
下面看看ArrayList隨機訪問的代碼
// 獲取index位置的元素值 public E get(int index) { RangeCheck(index); return (E) elementData[index]; } private void RangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException( "Index: "+index+", Size: "+size); }
從中,咱們能夠看出:經過get(int index)獲取ArrayList第index個元素時。直接返回數組中index位置的元素,而不須要像LinkedList同樣進行查找。
相同之處
1 它們都是List
它們都繼承於AbstractList,而且實現List接口。
ArrayList和Vector的類定義以下:
// ArrayList的定義 public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable // Vector的定義 public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {}
2 它們都實現了RandomAccess和Cloneable接口
實現RandomAccess接口,意味着它們都支持快速隨機訪問;
實現Cloneable接口,意味着它們能克隆本身。
3 它們都是經過數組實現的,本質上都是動態數組
ArrayList.java中定義數組elementData用於保存元素
// 保存ArrayList中數據的數組 private transient Object[] elementData;
Vector.java中也定義了數組elementData用於保存元素
// 保存Vector中數據的數組 protected Object[] elementData;
4 它們的默認數組容量是10
若建立ArrayList或Vector時,沒指定容量大小;則使用默認容量大小10。
ArrayList的默認構造函數以下:
// ArrayList構造函數。默認容量是10。 public ArrayList() { this(10); }
Vector的默認構造函數以下:
// Vector構造函數。默認容量是10。 public Vector() { this(10); }
5 它們都支持Iterator和listIterator遍歷
它們都繼承於AbstractList,而AbstractList中分別實現了 「iterator()接口返回Iterator迭代器」 和 「listIterator()返回ListIterator迭代器」。
不一樣之處
1 線程安全性不同
ArrayList是非線程安全;
而Vector是線程安全的,它的函數都是synchronized的,即都是支持同步的。
ArrayList適用於單線程,Vector適用於多線程。
2 對序列化支持不一樣
ArrayList支持序列化,而Vector不支持;即ArrayList有實現java.io.Serializable接口,而Vector沒有實現該接口。
3 構造函數個數不一樣
ArrayList有3個構造函數,而Vector有4個構造函數。Vector除了包括和ArrayList相似的3個構造函數以外,另外的一個構造函數能夠指定容量增長係數。
ArrayList的構造函數以下:
// 默認構造函數 ArrayList() // capacity是ArrayList的默認容量大小。當因爲增長數據致使容量不足時,容量會添加上一次容量大小的一半。 ArrayList(int capacity) // 建立一個包含collection的ArrayList ArrayList(Collection<? extends E> collection)
Vector的構造函數以下:
// 默認構造函數 Vector() // capacity是Vector的默認容量大小。當因爲增長數據致使容量增長時,每次容量會增長一倍。 Vector(int capacity) // 建立一個包含collection的Vector Vector(Collection<? extends E> collection) // capacity是Vector的默認容量大小,capacityIncrement是每次Vector容量增長時的增量值。 Vector(int capacity, int capacityIncrement)
4 容量增長方式不一樣
逐個添加元素時,若ArrayList容量不足時,「新的容量」=「(原始容量x3)/2 + 1」。
而Vector的容量增加與「增加係數有關」,若指定了「增加係數」,且「增加係數有效(即,大於0)」;那麼,每次容量不足時,「新的容量」=「原始容量+增加係數」。若增加係數無效(即,小於/等於0),則「新的容量」=「原始容量 x 2」。
ArrayList中容量增加的主要函數以下:
public void ensureCapacity(int minCapacity) { // 將「修改統計數」+1 modCount++; int oldCapacity = elementData.length; // 若當前容量不足以容納當前的元素個數,設置 新的容量=「(原始容量x3)/2 + 1」 if (minCapacity > oldCapacity) { Object oldData[] = elementData; int newCapacity = (oldCapacity * 3)/2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; elementData = Arrays.copyOf(elementData, newCapacity); } }
Vector中容量增加的主要函數以下:
private void ensureCapacityHelper(int minCapacity) { int oldCapacity = elementData.length; // 當Vector的容量不足以容納當前的所有元素,增長容量大小。 // 若 容量增量係數>0(即capacityIncrement>0),則將容量增大當capacityIncrement // 不然,將容量增大一倍。 if (minCapacity > oldCapacity) { Object[] oldData = elementData; int newCapacity = (capacityIncrement > 0) ? (oldCapacity + capacityIncrement) : (oldCapacity * 2); if (newCapacity < minCapacity) { newCapacity = minCapacity; } elementData = Arrays.copyOf(elementData, newCapacity); } }
5 對Enumeration的支持不一樣。Vector支持經過Enumeration去遍歷,而List不支持
Vector中實現Enumeration的代碼以下:
public Enumeration<E> elements() { // 經過匿名類實現Enumeration return new Enumeration<E>() { int count = 0; // 是否存在下一個元素 public boolean hasMoreElements() { return count < elementCount; } // 獲取下一個元素 public E nextElement() { synchronized (Vector.this) { if (count < elementCount) { return (E)elementData[count++]; } } throw new NoSuchElementException("Vector Enumeration"); } }; }