java集合08--List總結

轉載地址:http://blog.csdn.net/wangxiaotongfan/article/details/51332950

概要

前面,我們學完了List的全部內容,詳細內容請看前面的幾篇博客,

現在,我們再回頭看看總結一下List。內容包括:
第1部分 List概括
第2部分 List使用場景
3部分 LinkedList和ArrayList性能差異分析
第4部分 Vector和ArrayList比較

第1部分 List概括

先回顧一下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)。

第2部分 List使用場景

學東西的最終目的是爲了能夠理解、使用它。下面先概括的說明一下各個List的使用場景後面再分析原因

如果涉及到“棧”、“隊列”、“鏈表”等操作,應該考慮用List,具體的選擇哪個List,根據下面的標準來取捨。
(01) 對於需要快速插入,刪除元素,應該使用LinkedList。
(02) 對於需要快速隨機訪問元素,應該使用ArrayList。
(03) 對於“單線程環境” 或者 “多線程環境,但List僅僅只會被單個線程操作”,此時應該使用非同步的類(如ArrayList)。
       對於“多線程環境,且List可能同時被多個線程操作”,此時,應該使用同步的類(如Vector)。

通過下面的測試程序,我們來驗證上面的(01)和(02)結論。參考代碼如下:

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. import java.util.*;  
  2. import java.lang.Class;  
  3.   
  4. /* 
  5.  * @desc 對比ArrayList和LinkedList的插入、隨機讀取效率、刪除的效率 
  6.  * 
  7.  * @author skywang 
  8.  */  
  9. public class ListCompareTest {  
  10.   
  11.     private static final int COUNT = 100000;  
  12.   
  13.     private static LinkedList linkedList = new LinkedList();  
  14.     private static ArrayList arrayList = new ArrayList();  
  15.     private static Vector vector = new Vector();  
  16.     private static Stack stack = new Stack();  
  17.   
  18.     public static void main(String[] args) {  
  19.         // 換行符  
  20.         System.out.println();  
  21.         // 插入  
  22.         insertByPosition(stack) ;  
  23.         insertByPosition(vector) ;  
  24.         insertByPosition(linkedList) ;  
  25.         insertByPosition(arrayList) ;  
  26.   
  27.         // 換行符  
  28.         System.out.println();  
  29.         // 隨機讀取  
  30.         readByPosition(stack);  
  31.         readByPosition(vector);  
  32.         readByPosition(linkedList);  
  33.         readByPosition(arrayList);  
  34.   
  35.         // 換行符  
  36.         System.out.println();  
  37.         // 刪除   
  38.         deleteByPosition(stack);  
  39.         deleteByPosition(vector);  
  40.         deleteByPosition(linkedList);  
  41.         deleteByPosition(arrayList);  
  42.     }  
  43.   
  44.     // 獲取list的名稱  
  45.     private static String getListName(List list) {  
  46.         if (list instanceof LinkedList) {  
  47.             return "LinkedList";  
  48.         } else if (list instanceof ArrayList) {  
  49.             return "ArrayList";  
  50.         } else if (list instanceof Stack) {  
  51.             return "Stack";  
  52.         } else if (list instanceof Vector) {  
  53.             return "Vector";  
  54.         } else {  
  55.             return "List";  
  56.         }  
  57.     }  
  58.   
  59.     // 向list的指定位置插入COUNT個元素,並統計時間  
  60.     private static void insertByPosition(List list) {  
  61.         long startTime = System.currentTimeMillis();  
  62.   
  63.         // 向list的位置0插入COUNT個數  
  64.         for (int i=0; i<COUNT; i++)  
  65.             list.add(0, i);  
  66.   
  67.         long endTime = System.currentTimeMillis();  
  68.         long interval = endTime - startTime;  
  69.         System.out.println(getListName(list) + " : insert "+COUNT+" elements into the 1st position use time:" + interval+" ms");  
  70.     }  
  71.   
  72.     // 從list的指定位置刪除COUNT個元素,並統計時間  
  73.     private static void deleteByPosition(List list) {  
  74.         long startTime = System.currentTimeMillis();  
  75.   
  76.         // 刪除list第一個位置元素  
  77.         for (int i=0; i<COUNT; i++)  
  78.             list.remove(0);  
  79.   
  80.         long endTime = System.currentTimeMillis();  
  81.         long interval = endTime - startTime;  
  82.         System.out.println(getListName(list) + " : delete "+COUNT+" elements from the 1st position use time:" + interval+" ms");  
  83.     }  
  84.   
  85.     // 根據position,不斷從list中讀取元素,並統計時間  
  86.     private static void readByPosition(List list) {  
  87.         long startTime = System.currentTimeMillis();  
  88.   
  89.         // 讀取list元素  
  90.         for (int i=0; i<COUNT; i++)  
  91.             list.get(i);  
  92.   
  93.         long endTime = System.currentTimeMillis();  
  94.         long interval = endTime - startTime;  
  95.         System.out.println(getListName(list) + " : read "+COUNT+" elements by position use time:" + interval+" ms");  
  96.     }  
  97. }  

運行結果如下

  1. Stack : insert 100000 elements into the 1st position use time:1640 ms  
  2. Vector : insert 100000 elements into the 1st position use time:1607 ms  
  3. LinkedList : insert 100000 elements into the 1st position use time:29 ms  
  4. ArrayList : insert 100000 elements into the 1st position use time:1617 ms  
  5.   
  6. Stack : read 100000 elements by position use time:9 ms  
  7. Vector : read 100000 elements by position use time:6 ms  
  8. LinkedList : read 100000 elements by position use time:10809 ms  
  9. ArrayList : read 100000 elements by position use time:5 ms  
  10.   
  11. Stack : delete 100000 elements from the 1st position use time:1916 ms  
  12. Vector : delete 100000 elements from the 1st position use time:1910 ms  
  13. LinkedList : delete 100000 elements from the 1st position use time:15 ms  
  14. 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僅僅只會被單個線程操作”,此時應該使用非同步的類。

第3部分 LinkedList和ArrayList性能差異分析

下面我們看看爲什麼LinkedList中插入元素很快,而ArrayList中插入元素很慢

LinkedList.java中向指定位置插入元素的代碼如下

  1. // 在index前添加節點,且節點的值爲element  
  2. public void add(int index, E element) {  
  3.     addBefore(element, (index==size ? header : entry(index)));  
  4. }  
  5.   
  6. // 獲取雙向鏈表中指定位置的節點  
  7. private Entry<E> entry(int index) {  
  8.     if (index < 0 || index >= size)  
  9.         throw new IndexOutOfBoundsException("Index: "+index+  
  10.                                             ", Size: "+size);  
  11.     Entry<E> e = header;  
  12.     // 獲取index處的節點。  
  13.     // 若index < 雙向鏈表長度的1/2,則從前向後查找;  
  14.     // 否則,從後向前查找。  
  15.     if (index < (size >> 1)) {  
  16.         for (int i = 0; i <= index; i++)  
  17.             e = e.next;  
  18.     } else {  
  19.         for (int i = size; i > index; i--)  
  20.             e = e.previous;  
  21.     }  
  22.     return e;  
  23. }  
  24.   
  25. // 將節點(節點數據是e)添加到entry節點之前。  
  26. private Entry<E> addBefore(E e, Entry<E> entry) {  
  27.     // 新建節點newEntry,將newEntry插入到節點e之前;並且設置newEntry的數據是e  
  28.     Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);  
  29.     // 插入newEntry到鏈表中  
  30.     newEntry.previous.next = newEntry;  
  31.     newEntry.next.previous = newEntry;  
  32.     size++;  
  33.     modCount++;  
  34.     return newEntry;  
  35. }  

從中,我們可以看出:通過add(int index, E element)向LinkedList插入元素時。先是在雙向鏈表中找到要插入節點的位置index;找到之後,再插入一個新節點
雙向鏈表查找index位置的節點時,有一個加速動作若index < 雙向鏈表長度的1/2,則從前向後查找; 否則,從後向前查找

接着,我們看看ArrayList.java中向指定位置插入元素的代碼。如下:

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

ensureCapacity(size+1) 的作用是“確認ArrayList的容量,若容量不夠,則增加容量。
真正耗時的操作是 System.arraycopy(elementData, index, elementData, index + 1, size - index);

Sun JDK包的java/lang/System.java中的arraycopy()聲明如下:

  1. 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隨機訪問的代碼

  1. // 返回LinkedList指定位置的元素  
  2. public E get(int index) {  
  3.     return entry(index).element;  
  4. }  
  5.   
  6. // 獲取雙向鏈表中指定位置的節點  
  7. private Entry<E> entry(int index) {  
  8.     if (index < 0 || index >= size)  
  9.         throw new IndexOutOfBoundsException("Index: "+index+  
  10.                                             ", Size: "+size);  
  11.     Entry<E> e = header;  
  12.     // 獲取index處的節點。  
  13.     // 若index < 雙向鏈表長度的1/2,則從前先後查找;  
  14.     // 否則,從後向前查找。  
  15.     if (index < (size >> 1)) {  
  16.         for (int i = 0; i <= index; i++)  
  17.             e = e.next;  
  18.     } else {  
  19.         for (int i = size; i > index; i--)  
  20.             e = e.previous;  
  21.     }  
  22.     return e;  
  23. }  

從中,我們可以看出:通過get(int index)獲取LinkedList第index個元素時先是在雙向鏈表中找到要index位置的元素;找到之後再返回。
雙向鏈表查找index位置的節點時,有一個加速動作若index < 雙向鏈表長度的1/2,則從前向後查找; 否則,從後向前查找。

下面看看ArrayList隨機訪問的代碼 

  1. // 獲取index位置的元素值  
  2. public E get(int index) {  
  3.     RangeCheck(index);  
  4.   
  5.     return (E) elementData[index];  
  6. }  
  7.   
  8. private void RangeCheck(int index) {  
  9.     if (index >= size)  
  10.         throw new IndexOutOfBoundsException(  
  11.         "Index: "+index+", Size: "+size);  
  12. }  

從中,我們可以看出:通過get(int index)獲取ArrayList第index個元素時。直接返回數組中index位置的元素,而不需要像LinkedList一樣進行查找。

第4部分 Vector和ArrayList比較

相同之處

1 它們都是List

它們都繼承於AbstractList,並且實現List接口。
ArrayList和Vector的類定義如下:

  1. // ArrayList的定義  
  2. public class ArrayList<E> extends AbstractList<E>  
  3.         implements List<E>, RandomAccess, Cloneable, java.io.Serializable  
  4.   
  5. // Vector的定義  
  6. public class Vector<E> extends AbstractList<E>  
  7.     implements List<E>, RandomAccess, Cloneable, java.io.Serializable {}  

2 它們都實現了RandomAccess和Cloneable接口

   實現RandomAccess接口,意味着它們都支持快速隨機訪問;
   實現Cloneable接口,意味着它們能克隆自己。

3 它們都是通過數組實現的,本質上都是動態數組

ArrayList.java中定義數組elementData用於保存元素

  1. // 保存ArrayList中數據的數組  
  2. private transient Object[] elementData;  

Vector.java中也定義了數組elementData用於保存元素

  1. // 保存Vector中數據的數組  
  2. protected Object[] elementData;  

4 它們的默認數組容量是10

   若創建ArrayList或Vector時,沒指定容量大小;則使用默認容量大小10。

ArrayList的默認構造函數如下:

  1. // ArrayList構造函數。默認容量是10。  
  2. public ArrayList() {  
  3.     this(10);  
  4. }  

Vector的默認構造函數如下:

  1. // Vector構造函數。默認容量是10。  
  2. public Vector() {  
  3.     this(10);  
  4. }   

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的構造函數如下

  1. // 默認構造函數  
  2. ArrayList()  
  3.   
  4. // capacity是ArrayList的默認容量大小。當由於增加數據導致容量不足時,容量會添加上一次容量大小的一半。  
  5. ArrayList(int capacity)  
  6.   
  7. // 創建一個包含collection的ArrayList  
  8. ArrayList(Collection<? extends E> collection)  

Vector的構造函數如下

  1. // 默認構造函數  
  2. Vector()  
  3.   
  4. // capacity是Vector的默認容量大小。當由於增加數據導致容量增加時,每次容量會增加一倍。  
  5. Vector(int capacity)  
  6.   
  7. // 創建一個包含collection的Vector  
  8. Vector(Collection<? extends E> collection)  
  9.   
  10. // capacity是Vector的默認容量大小,capacityIncrement是每次Vector容量增加時的增量值。  
  11. Vector(int capacity, int capacityIncrement)  

4 容量增加方式不同

   逐個添加元素時,若ArrayList容量不足時,“新的容量”=“(原始容量x3)/2 + 1”。
   而Vector的容量增長與“增長係數有關”,若指定了“增長係數”,且“增長係數有效(即,大於0)”;那麼,每次容量不足時,“新的容量”=“原始容量+增長係數”。若增長係數無效(即,小於/等於0),則“新的容量”=“原始容量 x 2”。

ArrayList中容量增長的主要函數如下:

  1. public void ensureCapacity(int minCapacity) {  
  2.     // 將“修改統計數”+1  
  3.     modCount++;  
  4.     int oldCapacity = elementData.length;  
  5.     // 若當前容量不足以容納當前的元素個數,設置 新的容量=“(原始容量x3)/2 + 1”  
  6.     if (minCapacity > oldCapacity) {  
  7.         Object oldData[] = elementData;  
  8.         int newCapacity = (oldCapacity * 3)/2 + 1;  
  9.         if (newCapacity < minCapacity)  
  10.             newCapacity = minCapacity;  
  11.         elementData = Arrays.copyOf(elementData, newCapacity);  
  12.     }  
  13. }  

Vector中容量增長的主要函數如下:

  1. private void ensureCapacityHelper(int minCapacity) {  
  2.     int oldCapacity = elementData.length;  
  3.     // 當Vector的容量不足以容納當前的全部元素,增加容量大小。  
  4.     // 若 容量增量係數>0(即capacityIncrement>0),則將容量增大當capacityIncrement  
  5.     // 否則,將容量增大一倍。  
  6.     if (minCapacity > oldCapacity) {  
  7.         Object[] oldData = elementData;  
  8.         int newCapacity = (capacityIncrement > 0) ?  
  9.             (oldCapacity + capacityIncrement) : (oldCapacity * 2);  
  10.         if (newCapacity < minCapacity) {  
  11.             newCapacity = minCapacity;  
  12.         }  
  13.         elementData = Arrays.copyOf(elementData, newCapacity);  
  14.     }  
  15. }  

5 對Enumeration的支持不同。Vector支持通過Enumeration去遍歷,而List不支持

Vector中實現Enumeration的代碼如下:

  1. public Enumeration<E> elements() {  
  2.     // 通過匿名類實現Enumeration  
  3.     return new Enumeration<E>() {  
  4.         int count = 0;  
  5.   
  6.         // 是否存在下一個元素  
  7.         public boolean hasMoreElements() {  
  8.             return count < elementCount;  
  9.         }  
  10.   
  11.         // 獲取下一個元素  
  12.         public E nextElement() {  
  13.             synchronized (Vector.this) {  
  14.                 if (count < elementCount) {  
  15.                     return (E)elementData[count++];  
  16.                 }  
  17.             }  
  18.             throw new NoSuchElementException("Vector Enumeration");  
  19.         }  
  20.     };  
  21. }  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章