1. 程式人生 > >thinking in java (十七) ----- 集合之List總結

thinking in java (十七) ----- 集合之List總結

List概括

首先回顧一下關係圖

  1. Lsit是一個介面,繼承與Collection介面,它代表的是有序的佇列
  2. AbstractList是一個抽象類,它繼承於AbstractCollection,AbstractList實現List介面中除了size(),get(index)之外的函式
  3. AbstractSequentialList是一個抽象類,繼承於Abstract。AbstractSequentialList實現了“連結串列中根據index索引操作連結串列的全部函式”
  4. ArrayList,LinkedList,Vector,Stack是List的4個實現類

ArrayList是陣列佇列,相當於是動態陣列。他由陣列實現,隨機訪問效率極高,隨機插入,刪除,尤其是中間部分的地方,效率低,執行緒不安全

LinkedList是一個雙向連結串列,他可以被當做堆疊佇列,雙端佇列進行操作,LinkedList隨機訪問效率低,但是隨機插入隨機刪除的效率高,執行緒不安全

Vector是向量佇列,和ArrayList一樣是動態陣列。但是是執行緒安全

Stack是棧,繼承與Vector,廷行事先進後出

List使用場景

如果涉及到“棧”“佇列”“連結串列”,應該考慮使用List,具體使用哪個List根據下面的標準來決定

  1. 對於需要快速插入,刪除元素,使用LinkedList
  2. 需要快速隨機訪問,使用ArrayList
  3. 對於單執行緒 或者多執行緒,但是List只會被單個執行緒操作,就應該使用非同步類,如ArrayList,對於多執行緒環境,且List可能被多個執行緒操作,就使用同步的的類,如Vector

通過下面的測試程式,我們來驗證1,2的結論

public class Main {

    private static final int COUNT = 100000;

    private static LinkedList linkedList = new LinkedList();
    private static ArrayList arrayList = new ArrayList();
    private static Vector vector = new Vector();
    private static Stack stack = new Stack();

    public static void main(String[] args) {
        // 換行符
        System.out.println();
        // 插入
        insertByPosition(stack) ;
        insertByPosition(vector) ;
        insertByPosition(linkedList) ;
        insertByPosition(arrayList) ;

        // 換行符
        System.out.println();
        // 隨機讀取
        readByPosition(stack);
        readByPosition(vector);
        readByPosition(linkedList);
        readByPosition(arrayList);

        // 換行符
        System.out.println();
        // 刪除 
        deleteByPosition(stack);
        deleteByPosition(vector);
        deleteByPosition(linkedList);
        deleteByPosition(arrayList);
    }

    // 獲取list的名稱
    private static String getListName(List list) {
        if (list instanceof LinkedList) {
            return "LinkedList";
        } else if (list instanceof ArrayList) {
            return "ArrayList";
        } else if (list instanceof Stack) {
            return "Stack";
        } else if (list instanceof Vector) {
            return "Vector";
        } else {
            return "List";
        }
    }

    // 向list的指定位置插入COUNT個元素,並統計時間
    private static void insertByPosition(List list) {
        long startTime = System.currentTimeMillis();

        // 向list的位置0插入COUNT個數
        for (int i=0; i<COUNT; i++)
            list.add(0, i);

        long endTime = System.currentTimeMillis();
        long interval = endTime - startTime;
        System.out.println(getListName(list) + " : insert "+COUNT+" elements into the 1st position use time:" + interval+" ms");
    }

    // 從list的指定位置刪除COUNT個元素,並統計時間
    private static void deleteByPosition(List list) {
        long startTime = System.currentTimeMillis();

        // 刪除list第一個位置元素
        for (int i=0; i<COUNT; i++)
            list.remove(0);

        long endTime = System.currentTimeMillis();
        long interval = endTime - startTime;
        System.out.println(getListName(list) + " : delete "+COUNT+" elements from the 1st position use time:" + interval+" ms");
    }

    // 根據position,不斷從list中讀取元素,並統計時間
    private static void readByPosition(List list) {
        long startTime = System.currentTimeMillis();

        // 讀取list元素
        for (int i=0; i<COUNT; i++)
            list.get(i);

        long endTime = System.currentTimeMillis();
        long interval = endTime - startTime;
        System.out.println(getListName(list) + " : read "+COUNT+" elements by position use time:" + interval+" ms");
    }
}

結果:
Stack : insert 100000 elements into the 1st position use time:1169 ms
Vector : insert 100000 elements into the 1st position use time:1179 ms
LinkedList : insert 100000 elements into the 1st position use time:7 ms
ArrayList : insert 100000 elements into the 1st position use time:1214 ms

Stack : read 100000 elements by position use time:4 ms
Vector : read 100000 elements by position use time:3 ms
LinkedList : read 100000 elements by position use time:4792 ms
ArrayList : read 100000 elements by position use time:1 ms

Stack : delete 100000 elements from the 1st position use time:1085 ms
Vector : delete 100000 elements from the 1st position use time:1067 ms
LinkedList : delete 100000 elements from the 1st position use time:4 ms
ArrayList : delete 100000 elements from the 1st position use time:1088 ms

  • 我們可以發現

插入十萬個元素,LinkedList用時最短

刪除十萬個元素,LinkedList用時最短

遍歷十萬個元素,ArrayList和Stack,Vector用時差不多,LinkedList用時最長,

考慮到Vctor還是同步的,Stack又是繼承Vector,得出結論:

  1. 對於需要快速插入,刪除,應該使用LinkedList
  2. 對於需要快訪問元素,應該使用ArrayList
  3. 對於要求執行緒安全的,在多執行緒環境下的,應該使用Vector 或者Stack

LinkedList和ArrayList效能差異

我們從原始碼中看一下,為什麼LinkedList會插入元素很快,而ArrayList中插入元素很慢,下面是LinkedList的add方法原始碼:

// 在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;

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

ArrayList原始碼

// 將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);System.arraycopy(elementData, index, elementData, index + 1, size - index); 會移動index之後所有元素這就意味著,ArrayList的add(int index, E element)函式,會引起index之後所有元素的改變!

通過上面的分析,我們就能理解為什麼LinkedList中插入元素很快,而ArrayList中插入元素很慢。
“刪除元素”與“插入元素”的原理類似

// 返回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;
}

接下來,我們看看 “為什麼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一樣進行查詢。

Vctor和ArrayList比較

  • 都是繼承List

他們都是繼承自AbstractList,實現List介面。類的定義如下

// 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 {}
  • 都實現了RandomAccess和Cloneable介面

說明支援克隆和隨機快速訪問

  • 都是通過陣列實現

ArrayList定義陣列elementData存放元素

// 儲存ArrayList中資料的陣列
private transient Object[] elementData;

Vctor也定義陣列elementData存放元素

// 儲存Vector中資料的陣列
protected Object[] elementData;

從上面程式碼可以看出,ArrayList使用 transient 修飾了 elementData 陣列。這保證系統序列化ArrayList物件時不會直接序列號elementData陣列,而是通過ArrayList提高的writeObject、readObject方法來實現定製序列化;但對於Vector而言,它沒有使用transient修飾elementData陣列,而且Vector只提供了一個writeObject方法,並未完全實現定製序列化。 

  • 初始容量都是10

預設建構函式

// ArrayList建構函式。預設容量是10。
public ArrayList() {
    this(10);
}
————————————————————————————————
// Vector建構函式。預設容量是10。
public Vector() {
    this(10);
} 
  • 都支援迭代器遍歷

都繼承自AbstractList,實現了Iterator迭代器

  • 不同之處

  • 執行緒安全性

ArrayList非執行緒安全的,Vctor執行緒安全,所有方法都是synchronize。

ArrayList適應於單執行緒,Vector適用於多執行緒

  • 序列化支援

 ArrayList的底層陣列支援序列化,而Vector的底層陣列不支援;上面程式碼也有寫

  • 建構函式個數

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)

 

  • 容量增加方式

逐個新增元素時,若ArrayList容量不足時,“新的容量”=“(原始容量x3)/2 + 1”。(1.5倍)
   而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);
    }
}

 

 

  • 對Enumerition支援

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

 

原文:https://www.cnblogs.com/skywang12345/p/3308900.html