java容器學習總結(超讚!!!)

我是技術搬運工,好東西當然要和大家分享啦.原文地址

概覽

容器主要包括 Collection 和 Map 兩種,Collection 又包含了 List、Set 以及 Queue。

1. List

  • ArrayList:基於動態數組實現,支持隨機訪問;

  • LinkedList:基於雙向循環鏈表實現,只能順序訪問,但是可以快速地在鏈表中間插入和刪除元素。不僅如此,LinkedList 還可以用作棧、隊列和雙端隊列。

2. Set

  • HashSet:基於 Hash 實現,支持快速查找,但是失去有序性;

  • TreeSet:基於紅黑樹實現,保持有序,但是查找效率不如 HashSet;

  • LinkedListHashSet:具有 HashSet 的查找效率,且內部使用鏈表維護元素的插入順序,因此具有有序性。

3. Queue

只有兩個實現:LinkedList 和 PriorityQueue,其中 LinkedList 支持雙向隊列,PriorityQueue 是基於堆結構實現。

4. Map

  • HashMap:基於 Hash 實現

  • LinkedHashMap:使用鏈表來維護元素的順序,順序爲插入順序或者最近最少使用(LRU)順序

  • TreeMap:基於紅黑樹實現

  • ConcurrentHashMap:線程安全 Map,不涉及類似於 HashTable 的同步加鎖

5. Java 1.0/1.1 容器

對於舊的容器,我們決不應該使用它們,只需要對它們進行了解。

  • Vector:和 ArrayList 類似,但它是線程安全的

  • HashTable:和 HashMap 類似,但它是線程安全的

容器中的設計模式

1. 迭代器模式

從概覽圖可以看到,每個集合類都有一個 Iterator 對象,可以通過這個迭代器對象來遍歷集合中的元素。

Java 中的迭代器模式

2. 適配器模式

java.util.Arrays#asList() 可以把數組類型轉換爲 List 類型。

 List list = Arrays.asList(1, 2, 3);
 int[] arr = {1, 2, 3};
 list = Arrays.asList(arr);

散列

使用 hasCode() 來返回散列值,使用的是對象的地址。

而 equals() 是用來判斷兩個對象是否相等的,相等的兩個對象散列值一定要相同,但是散列值相同的兩個對象不一定相等。

相等必須滿足以下五個性質:

  1. 自反性
  2. 對稱性
  3. 傳遞性
  4. 一致性(多次調用 x.equals(y),結果不變)
  5. 對任何不是 null 的對象 x 調用 x.equals(nul) 結果都爲 false

源碼分析

建議先閱讀 算法 - 查找 部分,對集合類源碼的理解有很大幫助。

源碼下載:OpenJDK 1.7

1. ArraList

ArraList.java

實現了 RandomAccess 接口,因此支持隨機訪問,這是理所當然的,因爲 ArrayList 是基於數組實現的。

public class ArrayList<E> extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable

基於數組實現,保存元素的數組使用 transient 修飾,這是因爲該數組不一定所有位置都佔滿元素,因此也就沒必要全部都進行序列化。需要重寫 writeObject() 和 readObject()。

private transient Object[] elementData;

數組的默認大小爲 10

public ArrayList(int initialCapacity) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
    this.elementData = new Object[initialCapacity];
}

public ArrayList() {
    this(10);
}

刪除元素時調用 System.arraycopy() 對元素進行復制,因此刪除操作成本很高,最好在創建時就指定大概的容量大小,減少複製操作的執行次數。

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, numMoved);
    elementData[--size] = null; // Let gc do its work

    return oldValue;
}

添加元素時使用 ensureCapacity() 方法來保證容量足夠,如果不夠時,需要進行擴容,使得新容量爲舊容量的 1.5 倍。

modCount 用來記錄 ArrayList 發生變化的次數,因爲每次在進行 add() 和 addAll() 時都需要調用 ensureCapacity(),因此直接在 ensureCapacity() 中對 modCount 進行修改。

public void ensureCapacity(int minCapacity) {
    if (minCapacity > 0)
        ensureCapacityInternal(minCapacity);
}

private void ensureCapacityInternal(int minCapacity) {
    modCount++;
    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    // 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;
}

在進行序列化或者迭代等操作時,需要比較操作前後 modCount 是否改變,如果改變了需要拋出 ConcurrentModificationException。

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 array length
    s.writeInt(elementData.length);

    // 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();
    }

}

和 Vector 的區別

  1. Vector 和 ArrayList 幾乎是完全相同的,唯一的區別在於 Vector 是同步的,因此開銷就比 ArrayList 要大,訪問要慢。最好使用 ArrayList 而不是 Vector,因爲同步完全可以由程序員自己來控制;
  2. Vector 每次擴容請求其大小的 2 倍空間,而 ArrayList 是 1.5 倍。

爲了使用線程安全的 ArrayList,可以使用 Collections.synchronizedList(new ArrayList<>()); 返回一個線程安全的 ArrayList,也可以使用 concurrent 併發包下的 CopyOnWriteArrayList 類;

和 LinkedList 的區別

  1. ArrayList 基於動態數組實現,LinkedList 基於雙向循環鏈表實現;
  2. ArrayList 支持隨機訪問,LinkedList 不支持;
  3. LinkedList 在任意位置添加刪除元素更快。

2. Vector 與 Stack

Vector.java

3. LinkedList

LinkedList.java

4. TreeMap

TreeMap.java

5. HashMap

HashMap.java

使用拉鍊法來解決衝突。

默認容量 capacity 爲 16,需要注意的是容量必須保證爲 2 的次方。容量就是 Entry[] table 數組的長度,size 是數組的實際使用量。

threshold 規定了一個 size 的臨界值,size 必須小於 threshold,如果大於等於,就必須進行擴容操作。

threshold = capacity * load_factor,其中 load_factor 爲 table 數組能夠使用的比例,load_factor 過大會導致聚簇的出現,從而影響查詢和插入的效率,詳見算法筆記。

static final int DEFAULT_INITIAL_CAPACITY = 16;

static final int MAXIMUM_CAPACITY = 1 << 30;

static final float DEFAULT_LOAD_FACTOR = 0.75f;

transient Entry[] table;

transient int size;

int threshold;

final float loadFactor;

transient int modCount;

從下面的添加元素代碼中可以看出,當需要擴容時,令 capacity 爲原來的兩倍。

void addEntry(int hash, K key, V value, int bucketIndex) {
    Entry<K,V> e = table[bucketIndex];
    table[bucketIndex] = new Entry<>(hash, key, value, e);
    if (size++ >= threshold)
        resize(2 * table.length);
}

Entry 用來表示一個鍵值對元素,其中的 next 指針在序列化時會使用。

static class Entry<K,V> implements Map.Entry<K,V> {
    final K key;
    V value;
    Entry<K,V> next;
    final int hash;
}

get() 操作需要分成兩種情況,key 爲 null 和 不爲 null,從中可以看出 HashMap 允許插入 null 作爲鍵。

public V get(Object key) {
    if (key == null)
        return getForNullKey();
    int hash = hash(key.hashCode());
    for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
            return e.value;
    }
    return null;
}

put() 操作也需要根據 key 是否爲 null 做不同的處理,需要注意的是如果本來沒有 key 爲 null 的鍵值對,新插入一個 key 爲 null 的鍵值對時默認是放在數組的 0 位置,這是因爲 null 不能計算 hash 值,也就無法知道應該放在哪個鏈表上。

public V put(K key, V value) {
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key.hashCode());
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    addEntry(hash, key, value, i);
    return null;
}
private V putForNullKey(V value) {
    for (Entry<K,V> e = table[0]; e != null; e = e.next) {
        if (e.key == null) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }
    modCount++;
    addEntry(0, null, value, 0);
    return null;
}

6. LinkedHashMap

LinkedHashMap.java

7. ConcurrentHashMap

ConcurrentHashMap.java

探索 ConcurrentHashMap 高併發性的實現機制

參考資料

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