Java集合源碼解析(易於理解版)

前文:
首先你要耐心,最好有一定源碼基礎,沒有也行下面也會教你怎麼有效閱讀源碼。
其次爲什麼先講List。因爲建立再這個基礎上去理解其他的東西,事半功倍。
原文件:
原文件鏈接,覺得有用下載
正文:
JAVA集合實現原理及其優化。
背景介紹:
這是基於jdk1.8分析的,主要是對java集合的實現源碼分析。
Java集合框架:
在這裏插入圖片描述
注:上圖參考百度結果。
除了上面的集合類型。我們還會將Stack(棧)、Node(樹)、Quene(隊列)、HashTable的源碼實現和優化點。
1 List集合
該接口:

 public interface List<E> extends Collection<E> {
    int size();
    boolean isEmpty();
    boolean contains(Object o);
    Object[] toArray();
    <T> T[] toArray(T[] a);
    boolean containsAll(Collection<?> c);
    boolean addAll(Collection<? extends E> c);
    boolean addAll(int index, Collection<? extends E> c);
    boolean removeAll(Collection<?> c);
    boolean retainAll(Collection<?> c);
    default void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        final ListIterator<E> li = this.listIterator();
        while (li.hasNext()) {
            li.set(operator.apply(li.next()));
        }
    }
    @SuppressWarnings({"unchecked", "rawtypes"})
    default void sort(Comparator<? super E> c) {
        Object[] a = this.toArray();
        Arrays.sort(a, (Comparator) c);
        ListIterator<E> i = this.listIterator();
        for (Object e : a) {
            i.next();
            i.set((E) e);
        }
    }
    void clear();
    int hashCode();
    E get(int index);
    E set(int index, E element);
    void add(int index, E element);
    E remove(int index);
    int indexOf(Object o);
    int lastIndexOf(Object o);
    ListIterator<E> listIterator();
    ListIterator<E> listIterator(int index);
    List<E> subList(int fromIndex, int toIndex);
}

逐一來看看它的實現類。

逐一來看看它的實現類。
1.2 ArrayList

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

由於該類方法太多,我們之分析關鍵的方法。
該類的說明:
1、無序不唯一

上面可知ArrayList的繼承和實現關係。
基礎的默認創建、指定大小創建,是很基礎的東西。來看看由該類的三個構造器
創建的List。

//默認創建一個ArrayList集合 
List<String> list = new ArrayList<>();
//創建一個初始化長度爲100的ArrayList集合 
List<String> initlist = new ArrayList<>(100);
//將其他類型的集合轉爲ArrayList 
List<String> setList = new ArrayList<>(new HashSet());

前兩個構造器:

/**
 * 純空數組,但是指定長度
 */
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
 * 純空數組,默認長度
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
 * 對象數組
 */
transient Object[] elementData; 
/**
 * 構造得到一個有指定長度的數組
 */
public ArrayList(int initialCapacity) {
    if (initialCapacity > 0) {
        this.elementData = new Object[initialCapacity];
    } else if (initialCapacity == 0) {
        this.elementData = EMPTY_ELEMENTDATA;
    } else {
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    }
}

/**
 * 構造得到一個初始長度爲10的數組.
 */
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

由於ArrayList之上多重繼承中有實現了Collection。也就是提供了將Collection下的LinkedList、HashSet、LinkedHashSet、TreeSet轉爲ArrayList。

public ArrayList(Collection<? extends E> c) {
    elementData = c.toArray();
    if ((size = elementData.length) != 0) {
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    } else {
        // replace with empty array.
        this.elementData = EMPTY_ELEMENTDATA;
    }
}

上面的實現其實不難,是Arrays.copyOf方法的利用。
比如:

List<String> linklist = new ArrayList<>(new LinkedList<>());
List<String> treelist = new ArrayList<>(new TreeSet<>());
List<String> linktreelist = new ArrayList<>(new LinkedHashSet<String>());

這樣的實現大大方便了我們的集合轉換。

1.2.1 ArrayList的擴容機制。
總體來說,分爲兩步擴容和添加元素。
擴容:擴大數組的長度(這是核心)。就是把原來的數組複製到空間更大的數組中去。
添加元素:將新元素添加到擴容後的數組。

每次添加新元素將調用:

public boolean add(E e) {
// 確保添加容量
    ensureCapacityInternal(size + 1);  // Increments modCount!!
// 將新元素加入數組
    elementData[size++] = e;
    return true;
}
private void ensureCapacityInternal(int minCapacity) {
// 確保容量
    ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
// 計算最小容量
private static int calculateCapacity(Object[] elementData, int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    return minCapacity;
}

private void ensureExplicitCapacity(int minCapacity) {
    modCount++;

    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}
// 擴容的實現
private void grow(int minCapacity) {
    int oldCapacity = elementData.length;
//  oldCapacity >> 1 右移運算符 擴容爲原來的1.5倍
    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);
}
// 該方法決定了ArrayList的最大長度 MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8
private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}

到此ArrayList擴容的擴容就看完了。其實不難發現,ArrayList本質就是一個可以動態變法的數組。

對ArrayList的維護:
其實就如數組的更新刪除插入獲取的操作邏輯一樣。這個沒什麼可說的。需要考慮插更新刪除插入獲取index是否越界。

ArrayList優化:
其實ArrayList幾乎完美,我們所說的優化,只是從項目的角度來看。我們唯一能做到的就是減少ArrayList擴容。

我們來做個測試:

package com.design.cor;


import java.util.*;

public class Main {
    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>();
        long time1 = System.currentTimeMillis();
        for (int i = 1; i < 1000000; i++) {
            list.add(i);
        }
        long time2 = System.currentTimeMillis();
        System.out.println("放任擴容: " + (time2 - time1));

        List<Integer> list1 = new ArrayList<>(1000000);
        long time21 = System.currentTimeMillis();
        for (int i = 1; i < 1000000; i++) {
            list1.add(i);
        }
        long time22 = System.currentTimeMillis();
        System.out.println("指定容量: " + (time22 - time21));
    }
}

結果如下:
在這裏插入圖片描述
原因顯而易見:初始10要經歷10*(1.5)^29 ≈ 1278430 次擴容才能達到需求。而第二個我們就指定了大小。結論顯而易見,處於系統性能考慮大數據量下,需要預估大小,並指定。

這裏還有個值得說的點。你會發現所有集合都有求集合差集和並集的操作:

package com.design.cor;


import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

public class Main {
    public static void main(String[] args){
        List<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        list1.add(4);
        List<Integer> list2 = new ArrayList<>();
        list2.add(1);
        list2.add(4);
        list2.add(7);
        list2.add(10);
        // 求並集
        List<Integer> listAll = new ArrayList<>();
        listAll.addAll(list1);
        listAll.addAll(list2);
        // 有序去重
        listAll = new ArrayList<Integer> (new LinkedHashSet<>(listAll));
        System.out.println("並集爲: " + listAll);
        // 差集
        listAll.removeAll(list1);
        System.out.println("差集爲: " + listAll);
    }

}

運行結果:
在這裏插入圖片描述
其他的集合也是類似的。不一一再舉例子。

1.3 LinkedList
以雙向鏈表實現的List,它除了作爲List使用,還可以作爲隊列或者堆棧使用。(怎麼突然就是鏈表了呢)

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable

該類的說明:
1、有序,不唯一。

如上,對比下ArrayList

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

很明顯差距就在繼承類上和實現類上。由於方法非常的多,以下我們只列出我麼所關心的方法。

我們來看看在LinkedList中雙向鏈表的定義。
內部內實現的雙向鏈表:

private static class Node<E> {
    E item;
    Node<E> next;
    Node<E> prev;

    Node(Node<E> prev, E element, Node<E> next) {
        this.item = element;
        this.next = next;
        this.prev = prev;
    }
}

如果不出我們所料,LinkedList就是在維護這個對象。

/**
 * Constructs an empty list.
 */
public LinkedList() {
}
// 完成collection下list之間的轉換
public LinkedList(Collection<? extends E> c) {
// 得到當前對象
    this();
// 將所有的值添加進去
    addAll(c);
}

在作如下解釋前,我發現

/**
 * Pointer to first node.
 * Invariant: (first == null && last == null) ||
 *            (first.prev == null && first.item != null)
 */
transient Node<E> first;

/**
 * Pointer to last node.
 * Invariant: (first == null && last == null) ||
 *            (last.next == null && last.item != null)
 */
transient Node<E> last;

transient修飾符如下解釋:
1)transient修飾的變量不能被序列化;
2)transient只作用於實現 Serializable 接口;
3)transient只能用來修飾普通成員變量字段;
4)不管有沒有 transient 修飾,靜態變量都不能被序列化;

回到正文,爲什麼我們要將上面的frist和last對象拿出來說,他們是雙向鏈表的頭尾,很多的LinkenList方法就是基於他們來實現。
如果對鏈表的操作不清除。建議看數據結構的書。這裏簡單說明下,鏈表的維護就是節點維護,比如刪除一個元素,將後元素的頭節點指向前元素的。

先分析下加入一個元素。
這裏我不得不吐槽下IDEA對源碼很不友好。測試代碼我們就在eclispe來分析。

/**
 * Appends the specified element to the end of this list.
 */
public boolean add(E e) {
    linkLast(e);
    return true;
}
/**
 * Links e as last element.
 */
void linkLast(E e) {
    final Node<E> l = last;
    final Node<E> newNode = new Node<>(l, e, null);
    last = newNode;
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
    size++;
    modCount++;
}

測試程序:

package zy.stu.com;

import java.util.LinkedList;
import java.util.List;

public class MapIt {

    public static void main(String[] args) {
        List<Integer> list = new LinkedList<>();
        list.add(111);
        list.add(123);
    }
}

添加測試截圖:
在這裏插入圖片描述
首先這個E e是什麼,debug下不難發現它的類型居然是個LinkedList,這就導致了最後的結果看起來怪怪的?
在這裏插入圖片描述
在這裏插入圖片描述
上面的結果你覺得怪嗎?其中確實只有兩個,但這是個雙向鏈表,無限可循環。但是你可以id發現42-33-42-33-42-33。所以這是正常的。
在這裏插入圖片描述

鏈表的插入,懶得畫了借用百度圖片。
在這裏插入圖片描述

如上,剩下的刪除、插入指定位置、更新、獲取操作,其實都是在對Node進行維護處理。

移除一個元素:

public E remove(int index) {
    checkElementIndex(index);
    return unlink(node(index));
}
/**
 * Returns the (non-null) Node at the specified element index.
* 返回要刪除節點
 */
Node<E> node(int index) {
    // assert isElementIndex(index);

    if (index < (size >> 1)) {
        Node<E> x = first;
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else {
        Node<E> x = last;
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}
/**
 * Unlinks non-null node x.
* 刪除節點、修改節點指向
 */
E unlink(Node<E> x) {
    // assert x != null;
    final E element = x.item;
    final Node<E> next = x.next;
    final Node<E> prev = x.prev;

    if (prev == null) {
        first = next;
    } else {
        prev.next = next;
        x.prev = null;
    }

    if (next == null) {
        last = prev;
    } else {
        next.prev = prev;
        x.next = null;
    }

    x.item = null;
    size--;
    modCount++;
    return element;
}

看上面代碼很簡單對!就是對鏈表的刪除節點維護。
獲取元素:就能簡單了,這就是刪除元素的查找結點。

public E get(int index) {
    checkElementIndex(index);
    return node(index).item;
}

總結:
1、鏈表不存初始大小、也沒有擴容機制。
2、鏈表的實現,註定了獲取效率不高,適合大數據量下的插入和刪除且不關注查詢。(因爲查詢一個要從頭開始查找)。
3、額外補充,它實現了queue的方法,你也用queue的方法操作該list

2 Set集合
2.1 HashSet

public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable

沒什麼可說。說說源碼中對該類的介紹:
1、由hash表實現,但實際上是個HashMap,允許null值、無序、不重複。
我們來看看它是怎麼維護的list。

// 這個是關鍵,它維護就是這個HashHap
private transient HashMap<E,Object> map;

// 關聯回溯的值
private static final Object PRESENT = new Object();

/**
 構造一個新的空集; 支持<tt> HashMap </ tt>實例具有
  默認初始容量(16)和負載係數(0.75)。
 */
public HashSet() {
    map = new HashMap<>();
}

/**
 * 構建一個傳入Collection下的結合得到新的集合,默認加載因子0.75,其實就是空map加入元素
 * @param c 其他Collection下的集合
 */
public HashSet(Collection<? extends E> c) {
    map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
    addAll(c);
}

/**
 自己指定初始容量和加載因子創建
 */
public HashSet(int initialCapacity, float loadFactor) {
    map = new HashMap<>(initialCapacity, loadFactor);
}

/**
 * 指定初始容量構建
 */
public HashSet(int initialCapacity) {
    map = new HashMap<>(initialCapacity);
}

/**
 * 構造LinkedHashMap,專門爲LinkedHashMap提供
 */
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    map = new LinkedHashMap<>(initialCapacity, loadFactor);
}

由此可見它的原理還得看HashMap才能知道,詳細參考HashMap解釋。
再說一次,原理這裏不做詳細說明。

既然如此這裏我們就關注map,如何對這個map進行維護的就行。
添加:

// 添加元素無則添加、有則不變返回。元素爲key,value爲空對象PRESENT爲value
public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

移除一個元素:

// object,其實就是根據o爲key移除
public boolean remove(Object o) {
    return map.remove(o)==PRESENT;
}

其實看上了上面添加和刪除,我想包含你就能想到它是怎麼實現的了。
這個不用看吧?就是在維護這個HashMap的key
包含:

// 判斷map中是否含這個key
public boolean contains(Object o) {
    return map.containsKey(o);
}

大小size:就更簡單了,就是map的大小嘛。

public int size() {
    return map.size();
}
// 判空
public boolean isEmpty() {
    return map.isEmpty();
}
// 清空map中的元素。
public void clear() {
    map.clear();
}

2.2 LinkedHashSet

public class LinkedHashSet<E>
    extends HashSet<E>
    implements Set<E>, Cloneable, java.io.Serializable {

看看對該類說明:
1、數據唯一,還有序。

如果還有對上面HashSet有印象,LinkedHashSet在HashSet是已提供?實際就是如此,看如下該類就這麼點內容:

public class LinkedHashSet<E>
    extends HashSet<E>
    implements Set<E>, Cloneable, java.io.Serializable {

    private static final long serialVersionUID = -2851667679971038690L;

    /**
     * 指定初始容量和加載因子,其實是父類的
     */
    public LinkedHashSet(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor, true);
    }

    /**
     * 構造指定初始容量,默認加載因子0.75
     */
    public LinkedHashSet(int initialCapacity) {
        super(initialCapacity, .75f, true);
    }

    /**
     * 默認初始容量16,默認加載因子0.75
     */
    public LinkedHashSet() {
        super(16, .75f, true);
    }

    /**
     * 傳入Collection下集合構造LinkedHashSet,初始容量爲原先的2倍,0.75加載因子
     */
    public LinkedHashSet(Collection<? extends E> c) {
        super(Math.max(2*c.size(), 11), .75f, true);
        addAll(c);
    }
    @Override
    public Spliterator<E> spliterator() {
        return Spliterators.spliterator(this, Spliterator.DISTINCT | Spliterator.ORDERED);
    }
}

所以上面的本質實現是LinkedHashMap如下:
在HashSet類中,返回LinkedHashMap。

HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    map = new LinkedHashMap<>(initialCapacity, loadFactor);
}

他如何做到有序,不唯一。這裏暫時不分析。
對該類而言,重點就來,你發現和上面沒什麼區別了,還是在那個map進行維護。
到此不再累述。

2.3 TreeSet

public class TreeSet<E> extends AbstractSet<E>
    implements NavigableSet<E>, Cloneable, java.io.Serializable

首先,你聯想下上面的,你是不是已經get了?我們猜一下,其實是對TreeMap的key維護。
該類的說明:
1、基礎類型自然排序,存時儲對象時需要指定排序Comparable,否則異常。這個比較算法沒什麼可說把,就像二維數組的排序一樣。在方法內定義比較算法, 根據大小關係, 返回正數負數或零。
2、利用實現NavigableMap、TreeMap實現;

然而他出乎我們的預料。

/**
 * The backing map. 具有了針對給定搜索目標返回最接近匹配項的導航
 */
private transient NavigableMap<E,Object> m;
private static final Object PRESENT = new Object();
他所維護的對象是NavigableMap<E, Object>。
來看看他的構造器:
/**
 * 構造得到 navigable map.
 */
TreeSet(NavigableMap<E,Object> m) {
    this.m = m;
}

/**
 * 構造一個空樹
 */
public TreeSet() {
    this(new TreeMap<E,Object>());
}

/**
 * 構造一個我們按照規則排序的集合
 */
public TreeSet(Comparator<? super E> comparator) {
    this(new TreeMap<>(comparator));
}

/**
 * 將Collection下其他類型轉爲TreeSet
 */
public TreeSet(Collection<? extends E> c) {
    this();
    addAll(c);
}

/**
 * Constructs a new tree set containing the same elements and
 * using the same ordering as the specified sorted set.
 */
public TreeSet(SortedSet<E> s) {
    this(s.comparator());
    addAll(s);
}

方法上而言,和上面的LinkedHashSet一樣。都是對map的key的維護,就不需要再累述。

2 map
map是key、value的集合,下有HashMap、ConcurrentHashMap、LinkedHashMap、TreeMap。
有了List的種種引子。你是否發現map顯得是那麼那麼的重要。

public interface Map<K,V> {

Map的接口沒什麼可看的,接口嘛,就是定義一些方法。主要還得看實現類。

2.1 HashMap

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

該類說明:
1、通常是hash表實現,但存儲過大,將轉爲TreeNode實現。通常是先使用hash表,再合適時轉爲TreeNode。

也還有treeNode的說明,下面看代碼說明問題。需要說明一點由於map的重要性,敘述的內容應該很多也很重要。

該類的屬性:

/**
 * 初始容量16 這個容量爲2的倍數
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

/**
 * 最大容量 2^30
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * 默認負載因子.
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
 * 界限值大於8時hash錶轉爲紅黑樹。至少是8
 */
static final int TREEIFY_THRESHOLD = 8;
/**
 * 當小於6時,紅黑樹轉爲hash表
 */
static final int UNTREEIFY_THRESHOLD = 6;

/**
 * 最小樹形化閾值:至少4 * TREEIFY_THRESHOLD = 64。爲了避免hash碰撞。
 */
static final int MIN_TREEIFY_CAPACITY = 64;

上面的屬性哪裏用,先放一放。接下來屬性,需要知道內部靜態類Node<K,V>的實現:
首先要看下Map.Entry<K,V>接口:(具體還得看實現類)
主要看其中的排序方法:

interface Entry<K,V> {
    K getKey();
    V getValue();
    V setValue(V value);
    boolean equals(Object o);
    int hashCode();
    // 按key默認排序
    public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
        return (Comparator<Map.Entry<K, V>> & Serializable)
            (c1, c2) -> c1.getKey().compareTo(c2.getKey());
    }
// 按value默認排序
    public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {
        return (Comparator<Map.Entry<K, V>> & Serializable)
            (c1, c2) -> c1.getValue().compareTo(c2.getValue());
    }
   // 按key的指定算法排序
    public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
        Objects.requireNonNull(cmp);
        return (Comparator<Map.Entry<K, V>> & Serializable)
            (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
    }
   // 按value的指定算法排序
    public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {
        Objects.requireNonNull(cmp);
        return (Comparator<Map.Entry<K, V>> & Serializable)
            (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());
    }
}

內部靜態類Node<K,V>:作用想一個元素,一個元素四個值key、value、hash、Node<K,V>對象。
這裏裏面的東西都很重,着重理解。

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

    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }
   //將實現的方法final了以及屬性final,這很好理解,爲了保證當前Node的key和hash值唯一
    public final K getKey()        { return key; }
    public final V getValue()      { return value; }
    public final String toString() { return key + "=" + value; }
   // hash值計算 key得hash值和valuehash值得次方
    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

    public final V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }
    // 經典處理呀,hashcode和equals方法重寫。
// 這裏的重寫充分利用final的性質
    public final boolean equals(Object o) {
        if (o == this)
            return true;
        if (o instanceof Map.Entry) {
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            if (Objects.equals(key, e.getKey()) &&
                Objects.equals(value, e.getValue()))
                return true;
        }
        return false;
    }
}

關於Objects下:

public static int hashCode(Object o) {
    return o != null ? o.hashCode() : 0;

}
object下:

public native int hashCode();

看到這裏,發揮你的想象力。猜測一下,它是在維護一個什麼樣的東西。
我大膽猜下。
一、維護Node<K,V>數組,用Node<K,V> next來鏈表法解決hash碰撞,數組的每個項又是一個鏈表。
二、閾值超過8呢?是不是Node<K,V>直接構成一個紅黑樹呢。

/**
 * 首次初始Node<K,V>[]數組,長度爲2的倍數,也就是如我們猜想,要維護的對象了啦
 */
transient Node<K,V>[] table;
// 也有一些是我想不到的,不如下面的緩存
/**
 * entrySet緩存key和value
 */
transient Set<Map.Entry<K,V>> entrySet;
/**
 * map的大小
 */
transient int size;
/**
 * 此map的修改次數,用於hashmap故障快速定位
 */
transient int modCount;
/**
 * 調整大小時的下一個大小值(容量*負載係數)
 */
int threshold;
/**
 * hash表的負載因子.
 */
final float loadFactor;

到此我們要用的屬性,基本介紹完了。如上的猜想。有對也有不對。
這裏記錄下個人想法:邏輯一定要先行,猜也好,推也好。邊看邊推也好。一定是思維先行,而不是像機器一樣被動接受。
接着看看構造器:

/**
 * 構造指定初始容量和負載因子的HashMap
 */
public HashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " +
                                           initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                                           loadFactor);
    this.loadFactor = loadFactor;
// 對於給定容量返回兩倍大小
    this.threshold = tableSizeFor(initialCapacity);
}

/**
 * 構造指定初始容量和默認負載因子0.75
 */
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

/**
 * 構建初始容量16和負載因子爲0.75的HashMap
 */
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
}

/**
 * map下相互轉化的構造器
 */
public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
// 上面先構造,下面放入
    putMapEntries(m, false);
}

就從構造方法總體而言。
1、爲什麼所有集合都是有指定大小的構造?
答:這是一種常見的優化手段,指定容量可以防止不停擴容導致的效率問題。這也是爲什麼編碼建議上給出:初始化集合時,如果已知集合的數量,那麼一定要在初始化時設置集合的容量大小,這樣就可以有效的提高集合的性能。
2、集合大小隨便指定的嗎?
這個問題先留着?帶着這個問題,先將剩下集合分析完。

我們來看看是如何維護。
在這裏插入圖片描述
添加:

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
    int h;
// 由此可知key爲null
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

/**
 * @param hash 由key計算的hash值
 * @param key key
 * @param value vlaue
 * @param onlyIfAbsent 如果爲true則不改變已有的value值
 * @param evict 如果爲true表處於創建模式
 */
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
// 這n的複用。學到了。
// 爲空或不存在則初始化容器,並拿到容器的大小
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
// 這i的複用也恐怖。
// tab數組hash規則下爲null,這將這個null賦值
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
// 該位置不爲null
    else {
        Node<K,V> e; K k;
// 當前元素key是一致,將value替換即可
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
// 是紅黑樹,則添加
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 那麼就是鏈表
        else {
// 循環查找 e的複用
            for (int binCount = 0; ; ++binCount) {
// 找到末尾還沒有,再尾部插入。
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
// 循環鏈表有hash值和key值相同的,賦值value
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
// existing mapping for key
        if (e != null) { 
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
// 如果當前HashMap的容量超過threshold則進行擴容
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
// 初始化或兩倍增加容量   是擴容機制核心方法
// 上面的邏輯很清楚:HashMap初始化後首次插入數據時,先發生resize擴容再插入數據,之後每當插入的數據個數達到// threshold時就會發生resize,此時是先插入數據再resize。
final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
// 是否已擴容過
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    if (oldCap > 0) {// 擴容過
        if (oldCap >= MAXIMUM_CAPACITY) {// 超過最大容量
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
// 大於初始容量,不超過最大容量,table的容量乘以2。這裏複用了
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY) 
// threshold的值也乘以2 
            newThr = oldThr << 1; // double threshold
    }
// 默認構造器下進行擴容
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
// 使用帶有初始容量的構造器在此處進行擴容 
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    threshold = newThr;
    @SuppressWarnings({"rawtypes","unchecked"})
// 擴容2倍
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
// 將oldTab賦值給newTab
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
// 這個賦值和上面基本一樣的。
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;
                else if (e instanceof TreeNode)
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                else { // preserve order
// 鏈表處理:爲了提高效率,分成兩個鏈表
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        else {
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

上面這些方法一定要懂
–核心:
1、resize方法,擴容都是按2的冪次方擴容的。

再來看看get方法:理解了添加,獲取我想不難理解。

public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
// 始終從第一個開始匹配,第一個匹配返回
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
// 是紅黑樹,從根結點查詢是否匹配,匹配則返回
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {// 鏈表,循環查找匹配結果
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

瞭解了添加和獲取。移除就很容易了。就是找到它,移除。
移除:如果你細心發現移除是有返回值的喲。

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
                           boolean matchValue, boolean movable) {
    Node<K,V>[] tab; Node<K,V> p; int n, index;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (p = tab[index = (n - 1) & hash]) != null) {
        Node<K,V> node = null, e; K k; V v;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            node = p;
        else if ((e = p.next) != null) {
            if (p instanceof TreeNode) // 紅黑樹的查找
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            else {
                do {
// 鏈表的查找
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
// 刪除操作
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            if (node instanceof TreeNode) // 紅黑樹的刪除
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            else if (node == p)
                tab[index] = node.next; // 數組刪除
            else
                p.next = node.next; // 鏈表的刪除
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

其他的方法,都是類似的處理了。這裏舉個例子containsKey方法:

public boolean containsKey(Object key) {
    return getNode(hash(key), key) != null;
}

他就是去獲取,獲取不到就是沒有了。
其他的方法,我想用用上面邏輯,就可以想得通。

上面的代碼你看了,它是如何解決hash碰撞的是否有了一個概念?
在JDK7中有再hash、死循環、死鎖的問題,在jdk8已經優化,都是利用數組+鏈表+紅黑樹避免的,邏輯如上。
大致邏輯:先查看數組—是否爲紅黑樹—鏈表的處理。
1、hash的處理。
上面有個方法,這個hash值是通過hash方法算出來。p = tab[i = (n - 1) & hash]) == null這是有沒有hash碰撞,沒有就直接創建newNode。
2、出現了hash碰撞:
是紅黑樹,從根結點查找,有則賦值,沒有則在尾部添加。
是鏈表,從迭代查找,有則賦值,沒有則添加,添加需要判定鏈表轉紅黑樹的契機。
爲什麼避免了死循環。上面的添加,查找都有明顯結束標誌。

備註:裏面紅黑樹的轉化,這裏是沒講的。

final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        resize();
    else if ((e = tab[index = (n - 1) & hash]) != null) {
        TreeNode<K,V> hd = null, tl = null;
        do {
            TreeNode<K,V> p = replacementTreeNode(e, null);
            if (tl == null)
                hd = p;
            else {
                p.prev = tl;
                tl.next = p;
            }
            tl = p;
        } while ((e = e.next) != null);
        if ((tab[index] = hd) != null)
            hd.treeify(tab);
    }
}

2 LinkedHashMap

public class LinkedHashMap<K,V>
    extends HashMap<K,V>
    implements Map<K,V>
{

你這一看大概就知道了。你可以大膽猜測構造器都是調的父類構造器。甚至裏面的很多方法實現應該都是。但我們是知道的LinkedHashMap是有序的。所以將方法過一眼,重點開下如何保證有序的。
看看屬性:

/**
 * 該雙鏈表的頭
 */
transient LinkedHashMap.Entry<K,V> head;

/**
 * 雙鏈表的尾
 */
transient LinkedHashMap.Entry<K,V> tail;
構造方法:(舉個例子說明問題)其他來自父類的構造器類似處理
/**
 * 默認初始容量16和負載因子0.75.並指定accessOrder = false有序
 */
public LinkedHashMap() {
    super();
    accessOrder = false;
}

方法:
1、該類中,你根本找不到get、put、remove。都是父類的。這就不再累述。
2、如何保證有序的。
這個靜態內部內類中,加了兩個屬性來保證有序。

/**
 * HashMap.Node subclass for normal LinkedHashMap entries.
 */
static class Entry<K,V> extends HashMap.Node<K,V> {
    Entry<K,V> before, after;
    Entry(int hash, K key, V value, Node<K,V> next) {
        super(hash, key, value, next);
    }
}
// 新加一個元素放在末尾
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
    LinkedHashMap.Entry<K,V> p =
        new LinkedHashMap.Entry<K,V>(hash, key, value, e);
    linkNodeLast(p);
    return p;
}

private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {
    LinkedHashMap.Entry<K,V> last = tail;
    tail = p;
    if (last == null)
        head = p;
    else {
        p.before = last;
        last.after = p;
    }
}

上面的是數組的操作,裏面同樣有類似的方法去處理紅黑樹和鏈表。
比如:

TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) {
    TreeNode<K,V> p = new TreeNode<K,V>(hash, key, value, next);
    linkNodeLast(p);
    return p;
}

不再累述,都是類似的邏輯。

3 TreeMap

public class TreeMap<K,V>
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable

NavigableMap<K,V>這個眼熟吧。前面TreeSet的時候說過在這裏來分析。
來看看這個接口的說明:

public interface NavigableMap<K,V> extends SortedMap<K,V> 

說明:
1、繼承了SortedMap,重點在裏面的排序方法。
2、是由紅黑樹實現。來自於Map.Entry<K,V>

回到TreeMap,來看看屬性:

// 用於維護樹形圖中的順序
private final Comparator<? super K> comparator;
// 根結點
private transient Entry<K,V> root;

/**
 * 元素數量
 */
private transient int size = 0;

/**
 * 該樹被修改的次數
 */
private transient int modCount = 0;

看看構造方法:

// 構造默認自然排序
public TreeMap() {
    comparator = null;
}

/**
 * 構造指定按key的排序規則
 */
public TreeMap(Comparator<? super K> comparator) {
    this.comparator = comparator;
}

/**
 * map接口下其他的轉爲TreeMap,按key自然排序
 */
public TreeMap(Map<? extends K, ? extends V> m) {
    comparator = null;
    putAll(m);
}

/**
 * 構造一個指定排序的TreeMap
 */
public TreeMap(SortedMap<K, ? extends V> m) {
    comparator = m.comparator();
    try {
        buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
    } catch (java.io.IOException cannotHappen) {
    } catch (ClassNotFoundException cannotHappen) {
    }
}

這個TreeMap到底在維護這個東東啊?上面的屬性上而言只剩一個東西了?
難道就是在維護這個Entry<K,V> root.就是紅黑樹。
該樹的結構:
1、你需要理解的一個點是該類爲 static final

static final class Entry<K,V> implements Map.Entry<K,V> {
    K key;
    V value;
    Entry<K,V> left; // 左子樹
    Entry<K,V> right; // 右子樹
    Entry<K,V> parent;
    boolean color = BLACK; // 不是黑就是紅

    /**
     * 唯一設置K-V,和父節點
     */
    Entry(K key, V value, Entry<K,V> parent) {
        this.key = key;
        this.value = value;
        this.parent = parent;
    }

    /**
     * Returns the key.
     */
    public K getKey() {
        return key;
    }

    /**
     * Returns the value associated with the key.
     */
    public V getValue() {
        return value;
    }

    /**
     * Replaces the value currently associated with the key with the given
     * value.
     */
    public V setValue(V value) {
        V oldValue = this.value;
        this.value = value;
        return oldValue;
    }
   // 重寫equals和hashCode
    public boolean equals(Object o) {
        if (!(o instanceof Map.Entry))
            return false;
        Map.Entry<?,?> e = (Map.Entry<?,?>)o;

        return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
    }

    public int hashCode() {
        int keyHash = (key==null ? 0 : key.hashCode());
        int valueHash = (value==null ? 0 : value.hashCode());
        return keyHash ^ valueHash;
    }

    public String toString() {
        return key + "=" + value;
    }
}

看看添加方法:

public V put(K key, V value) {
    Entry<K,V> t = root;
    if (t == null) {
// 爲null 情況下,檢查key
        compare(key, key); // type (and possibly null) check
// 該結點保存K-V,以及父節點對象Entry<>
        root = new Entry<>(key, value, null);
        size = 1;
        modCount++;
        return null;
    }
// 不爲null
    int cmp;
// 父節點
    Entry<K,V> parent;
    Comparator<? super K> cpr = comparator;
// 排序規則有
    if (cpr != null) {
        do {
            parent = t;
            cmp = cpr.compare(key, t.key);
            if (cmp < 0)
                t = t.left;
            else if (cmp > 0)
                t = t.right;
            else
                return t.setValue(value);
        } while (t != null);
    } // 排序規則無
    else {
        if (key == null)
            throw new NullPointerException();
        @SuppressWarnings("unchecked")
            Comparable<? super K> k = (Comparable<? super K>) key;
        do {
            parent = t;
            cmp = k.compareTo(t.key);
// 當前變量的左右子樹,爲什麼可以這樣寫?是因爲TreeMap的key是有序的。
            if (cmp < 0)
                t = t.left;
            else if (cmp > 0)
                t = t.right;
            else
// 找到相同key,修改值
                return t.setValue(value);
        } while (t != null);
    }
// 走到了左或右子樹的末尾,創建節點,並設值給prrent左或右節點設值
    Entry<K,V> e = new Entry<>(key, value, parent);
    if (cmp < 0)
        parent.left = e;
    else
        parent.right = e;
// 紅黑設置
    fixAfterInsertion(e);
    size++;
    modCount++;
    return null;
}

// 這方法不想看,一堆旋轉處理,太難理解了。我認爲真的沒有必要看。

private void fixAfterInsertion(Entry<K,V> x) {
    x.color = RED;

    while (x != null && x != root && x.parent.color == RED) {
        if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
            Entry<K,V> y = rightOf(parentOf(parentOf(x)));
            if (colorOf(y) == RED) {
                setColor(parentOf(x), BLACK);
                setColor(y, BLACK);
                setColor(parentOf(parentOf(x)), RED);
                x = parentOf(parentOf(x));
            } else {
                if (x == rightOf(parentOf(x))) {
                    x = parentOf(x);
                    rotateLeft(x);
                }
                setColor(parentOf(x), BLACK);
                setColor(parentOf(parentOf(x)), RED);
                rotateRight(parentOf(parentOf(x)));
            }
        } else {
            Entry<K,V> y = leftOf(parentOf(parentOf(x)));
            if (colorOf(y) == RED) {
                setColor(parentOf(x), BLACK);
                setColor(y, BLACK);
                setColor(parentOf(parentOf(x)), RED);
                x = parentOf(parentOf(x));
            } else {
                if (x == leftOf(parentOf(x))) {
                    x = parentOf(x);
                    rotateRight(x);
                }
                setColor(parentOf(x), BLACK);
                setColor(parentOf(parentOf(x)), RED);
                rotateLeft(parentOf(parentOf(x)));
            }
        }
    }
    root.color = BLACK;
}

所有它所維護就是這棵樹。
get方法: 懂了上面的添加,查找就很容易理解。就是樹查找。

public V get(Object key) {
    Entry<K,V> p = getEntry(key);
    return (p==null ? null : p.value);
}
final Entry<K,V> getEntry(Object key) {
    // Offload comparator-based version for sake of performance
    if (comparator != null)
        return getEntryUsingComparator(key);
    if (key == null)
        throw new NullPointerException();
    @SuppressWarnings("unchecked")
        Comparable<? super K> k = (Comparable<? super K>) key;
    Entry<K,V> p = root;
    while (p != null) {
// 因爲key有序,才能這麼寫
        int cmp = k.compareTo(p.key);
        if (cmp < 0)
            p = p.left;
        else if (cmp > 0)
            p = p.right;
        else
            return p;
    }
    return null;
}

remove方法:就是在get方法上多了刪除的操作:

public V remove(Object key) {
    Entry<K,V> p = getEntry(key);
    if (p == null)
        return null;

    V oldValue = p.value;
    deleteEntry(p);
    return oldValue;
}

//刪除 註釋的很全面,不多說。如果你知曉二叉樹是如何刪除一個節點的,下面的過程你可以不用看了

private void deleteEntry(Entry<K,V> p) {
    modCount++;
    size--;

    // If strictly internal, copy successor's element to p and then make p
    // point to successor.
    if (p.left != null && p.right != null) {
        Entry<K,V> s = successor(p);
        p.key = s.key;
        p.value = s.value;
        p = s;
    } // p has 2 children

    // Start fixup at replacement node, if it exists.
    Entry<K,V> replacement = (p.left != null ? p.left : p.right);

    if (replacement != null) {
        // Link replacement to parent
        replacement.parent = p.parent;
        if (p.parent == null)
            root = replacement;
        else if (p == p.parent.left)
            p.parent.left  = replacement;
        else
            p.parent.right = replacement;

        // Null out links so they are OK to use by fixAfterDeletion.
        p.left = p.right = p.parent = null;

        // Fix replacement
        if (p.color == BLACK)
            fixAfterDeletion(replacement);
    } else if (p.parent == null) { // return if we are the only node.
        root = null;
    } else { //  No children. Use self as phantom replacement and unlink.
        if (p.color == BLACK)
            fixAfterDeletion(p);

        if (p.parent != null) {
            if (p == p.parent.left)
                p.parent.left = null;
            else if (p == p.parent.right)
                p.parent.right = null;
            p.parent = null;
        }
    }
}

當然裏面還有很多方法。但是基本元素的操作,都是基於上面三種方法實現的。不想累述。

3 ConcurrentHashMap

public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
    implements ConcurrentMap<K,V>, Serializable {

類說明:
由hash表實現,支持並行和併發,和HashTable類似。它是如何做到。這要從屬性和方法去分析。
它的很多都和HashMap類似。我們主要關注的是如何做到的支持並行併發的,以及多的屬性和方法。

// 三個原子操作
// 獲取tab數組的第i個node 
static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
    return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}
// 利用CAS算法設置i位置上的node節點。
static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
                                    Node<K,V> c, Node<K,V> v) {
    return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
}
// 利用volatile方法設置第i個節點的值,
static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
    U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
}

屬性volatile:

/**
 * volatile的桶數組
 */
transient volatile Node<K,V>[] table;

/**
 * 非空調整大小時使用,volatile的桶數組
 */
private transient volatile Node<K,V>[] nextTable;

/**
 * 基礎計數器,主要無競爭時使用,它通過CAS更新
 */
private transient volatile long baseCount;

/**
 * 表初始化和大小調整判斷 -1:初始化,其他大小調整
 */
private transient volatile int sizeCtl;

/**
 * 調整大小拆分的索引.
 */
private transient volatile int transferIndex;

/**
 * 調整大小和創建CounterCells使用CAS鎖
 */
private transient volatile int cellsBusy;

/**
 * 計數器細胞表,大小始終爲2的冪次方法
 */
private transient volatile CounterCell[] counterCells;

構造方法:
和HashMap中的構造方法基本一樣,不累述。
put方法:

public V put(K key, V value) {
    return putVal(key, value, false);
}

/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
// 這裏可以看到key和value都不能爲null
    if (key == null || value == null) throw new NullPointerException();
    int hash = spread(key.hashCode());
    int binCount = 0;
    for (Node<K,V>[] tab = table;;) {
        Node<K,V> f; int n, i, fh;
// 沒有,則初始化
        if (tab == null || (n = tab.length) == 0)
            tab = initTable();
// 查找hash對應沒有值,加CAS鎖並設值
        else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
            if (casTabAt(tab, i, null,
                         new Node<K,V>(hash, key, value, null)))
                break;                   // no lock when adding to empty bin
        }
        else if ((fh = f.hash) == MOVED)
            tab = helpTransfer(tab, f);
        else {
            V oldVal = null;
// 加synchronized 鎖保證對樹的操作
            synchronized (f) {
                if (tabAt(tab, i) == f) {
                    if (fh >= 0) {
                        binCount = 1;
                        for (Node<K,V> e = f;; ++binCount) {
                            K ek;
                            if (e.hash == hash &&
                                ((ek = e.key) == key ||
                                 (ek != null && key.equals(ek)))) {
                                oldVal = e.val;
                                if (!onlyIfAbsent)
                                    e.val = value;
                                break;
                            }
                            Node<K,V> pred = e;
                            if ((e = e.next) == null) {
                                pred.next = new Node<K,V>(hash, key,
                                                          value, null);
                                break;
                            }
                        }
                    }
                    else if (f instanceof TreeBin) {
                        Node<K,V> p;
                        binCount = 2;
                        if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
                                                       value)) != null) {
                            oldVal = p.val;
                            if (!onlyIfAbsent)
                                p.val = value;
                        }
                    }
                }
            }
            if (binCount != 0) {
                if (binCount >= TREEIFY_THRESHOLD)
                    treeifyBin(tab, i);
                if (oldVal != null)
                    return oldVal;
                break;
            }
        }
    }
    addCount(1L, binCount);
    return null;
}

get方法:

public V get(Object key) {
    Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
    int h = spread(key.hashCode());
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (e = tabAt(tab, (n - 1) & h)) != null) {
        if ((eh = e.hash) == h) {
            if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                return e.val;
        }
        else if (eh < 0)
            return (p = e.find(h, key)) != null ? p.val : null;
        while ((e = e.next) != null) {
            if (e.hash == h &&
                ((ek = e.key) == key || (ek != null && key.equals(ek))))
                return e.val;
        }
    }
    return null;
}

remove方法:

public V remove(Object key) {
    return replaceNode(key, null, null);
}

/**
 * synchronized 鎖實現刪除
 */
final V replaceNode(Object key, V value, Object cv) {
    int hash = spread(key.hashCode());
    for (Node<K,V>[] tab = table;;) {
        Node<K,V> f; int n, i, fh;
        if (tab == null || (n = tab.length) == 0 ||
            (f = tabAt(tab, i = (n - 1) & hash)) == null)
            break;
        else if ((fh = f.hash) == MOVED)
            tab = helpTransfer(tab, f);
        else {
            V oldVal = null;
            boolean validated = false;
            synchronized (f) {
                if (tabAt(tab, i) == f) {
                    if (fh >= 0) {
                        validated = true;
                        for (Node<K,V> e = f, pred = null;;) {
                            K ek;
                            if (e.hash == hash &&
                                ((ek = e.key) == key ||
                                 (ek != null && key.equals(ek)))) {
                                V ev = e.val;
                                if (cv == null || cv == ev ||
                                    (ev != null && cv.equals(ev))) {
                                    oldVal = ev;
                                    if (value != null)
                                        e.val = value;
                                    else if (pred != null)
                                        pred.next = e.next;
                                    else
                                        setTabAt(tab, i, e.next);
                                }
                                break;
                            }
                            pred = e;
                            if ((e = e.next) == null)
                                break;
                        }
                    }
                    else if (f instanceof TreeBin) {
                        validated = true;
                        TreeBin<K,V> t = (TreeBin<K,V>)f;
                        TreeNode<K,V> r, p;
                        if ((r = t.root) != null &&
                            (p = r.findTreeNode(hash, key, null)) != null) {
                            V pv = p.val;
                            if (cv == null || cv == pv ||
                                (pv != null && cv.equals(pv))) {
                                oldVal = pv;
                                if (value != null)
                                    p.val = value;
                                else if (t.removeTreeNode(p))
                                    setTabAt(tab, i, untreeify(t.first));
                            }
                        }
                    }
                }
            }
            if (validated) {
                if (oldVal != null) {
                    if (value == null)
                        addCount(-1L, -1);
                    return oldVal;
                }
                break;
            }
        }
    }
    return null;
}

其他的方法都是在這上面的基礎之上。想了解去看源碼。這裏不再大篇幅累述。

3 Stack和Vector

public
class Stack<E> extends Vector<E> {

它繼承了Vector。所以Stack是線程安全的。雖說Stack和Vector已過時,不推薦使用。但是呢,該用還是一樣的用。
它所維護的就是一個動態數組:(和List一樣)

public
class Stack<E> extends Vector<E> {
    /**
     * 唯一構造器
     */
    public Stack() {
    }

    /**
     * push一個元素
     */
    public E push(E item) {
        addElement(item);

        return item;
    }

    /**
     * 移除一個元素,並返回該元素
     */
    public synchronized E pop() {
        E       obj;
        int     len = size();

        obj = peek();
        removeElementAt(len - 1);

        return obj;
    }

    /**
     * 得到棧頂元素
     */
    public synchronized E peek() {
        int     len = size();

        if (len == 0)
            throw new EmptyStackException();
        return elementAt(len - 1);
    }

    /**
     * Tests if this stack is empty.
     */
    public boolean empty() {
        return size() == 0;
    }

    /**
     * 查找元素
     */
    public synchronized int search(Object o) {
        int i = lastIndexOf(o);

        if (i >= 0) {
            return size() - i;
        }
        return -1;
    }

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = 1224463164541339165L;
}

來自父類的方法:
添加:

public synchronized void addElement(E obj) {
    modCount++;
    ensureCapacityHelper(elementCount + 1);
    elementData[elementCount++] = obj;
}

刪除:

public synchronized void removeElementAt(int index) {
    modCount++;
    if (index >= elementCount) {
        throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                 elementCount);
    }
    else if (index < 0) {
        throw new ArrayIndexOutOfBoundsException(index);
    }
    int j = elementCount - index - 1;
    if (j > 0) {
        System.arraycopy(elementData, index + 1, elementData, index, j);
    }
    elementCount--;
    elementData[elementCount] = null; /* to let gc do its work */
}

4 queue
4.1 LinkedBlockingDeque

public class LinkedBlockingDeque<E>
    extends AbstractQueue<E>
    implements BlockingDeque<E>, java.io.Serializable {

這個queue是阻塞雙端隊列。
來看看構造器:

/**
 * 創建初始容量int最大值的queue
 */
public LinkedBlockingDeque() {
    this(Integer.MAX_VALUE);
}

/**
 * 構造指定容量的LinkedBlockingDeque
 */
public LinkedBlockingDeque(int capacity) {
    if (capacity <= 0) throw new IllegalArgumentException();
    this.capacity = capacity;
}

/**
 * 構造Collection下其他集合的轉換
 */
public LinkedBlockingDeque(Collection<? extends E> c) {
    this(Integer.MAX_VALUE);
// 加鎖
    final ReentrantLock lock = this.lock;
    lock.lock(); // Never contended, but necessary for visibility
    try {
        for (E e : c) {
            if (e == null)
                throw new NullPointerException();
            if (!linkLast(new Node<E>(e)))
                throw new IllegalStateException("Deque full");
        }
    } finally {
        lock.unlock();
    }
}

來看看屬性和維護的對象:
/** 靜態雙鏈表對象 */

static final class Node<E> {
    // 值
    E item;
    // 上一個節點
    Node<E> prev;
    // 下一個節點
    Node<E> next;

    Node(E x) {
        item = x;
    }
}

/**
 * 頭節點
 */
transient Node<E> first;

/**
 * 尾節點
 */
transient Node<E> last;

/** 雙端隊列中元素個數 */
private transient int count;

/** 最大容量 */
private final int capacity;

/** 主鎖,保護所有通道 */
final ReentrantLock lock = new ReentrantLock();

/** 等待條件鎖take */
private final Condition notEmpty = lock.newCondition();

/** 等待條件鎖put */
private final Condition notFull = lock.newCondition();

從上面我們可以看出他所維護的就是這個雙鏈表對象。
來看看它是如何維護這個對象的。
add方法:

public boolean add(E e) {
    addLast(e);
    return true;
}
public void addLast(E e) {
    if (!offerLast(e))
        throw new IllegalStateException("Deque full");
}
public boolean offerLast(E e) {
    if (e == null) throw new NullPointerException();
    Node<E> node = new Node<E>(e);
// 添加前加鎖
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return linkLast(node);
    } finally {
// 添加完釋放鎖
        lock.unlock();
    }
}
private boolean linkLast(Node<E> node) {
    // assert lock.isHeldByCurrentThread();
    if (count >= capacity)
        return false;
// 添加到末尾,即是改變鏈表指向
    Node<E> l = last;
    node.prev = l;
    last = node;
    if (first == null)
        first = node;
    else
        l.next = node;
    ++count;
// 消費者喚醒
    notEmpty.signal();
    return true;
}
上面的添加,除了添加加鎖,都是很常規的鏈表操作。
element方法:獲取第一個,但不刪除
public E element() {
    return getFirst();
}
public E getFirst() {
    E x = peekFirst();
    if (x == null) throw new NoSuchElementException();
    return x;
}
public E peekFirst() {
    final ReentrantLock lock = this.lock;
// 獲取操作加鎖
    lock.lock();
    try {
        return (first == null) ? null : first.item;
    } finally {
        lock.unlock();
    }
}
offer方法:
public boolean offer(E e) {
// 這裏是不是和add對比少了一個異常呢
    return offerLast(e);
}
public boolean offerLast(E e) {
    if (e == null) throw new NullPointerException();
    Node<E> node = new Node<E>(e);
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return linkLast(node);
    } finally {
        lock.unlock();
    }
}

和add方法一對比,不是一樣的邏輯嘛。仔細看就少了個異常。
因此:
Queue 中 add() 和 offer()都是用來向隊列添加一個元素。
在容量已滿的情況下,add() 方法會拋出IllegalStateException異常,offer() 方法只會返回 false 。
先入先出。我們來看看‘出’:
peek方法:只彈出,不刪除。它和element差距彈出null不會報異常。

public E peek() {
    return peekFirst();
}
public E peekFirst() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return (first == null) ? null : first.item;
    } finally {
        lock.unlock();
    }
}

pop方法:

public E pop() {
    return removeFirst();
}
public E removeFirst() {
    E x = pollFirst();
    if (x == null) throw new NoSuchElementException();
    return x;
}
public E pollFirst() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return unlinkFirst();
    } finally {
        lock.unlock();
    }
}
// 改變鏈表指向
private E unlinkFirst() {
    // assert lock.isHeldByCurrentThread();
    Node<E> f = first;
    if (f == null)
        return null;
    Node<E> n = f.next;
    E item = f.item;
    f.item = null;
    f.next = f; // help GC
    first = n;
    if (n == null)
        last = null;
    else
        n.prev = null;
    --count;
    notFull.signal();
    return item;
}

還可以移除指定對象:

public boolean remove(Object o) {
    return removeFirstOccurrence(o);
}
public boolean removeFirstOccurrence(Object o) {
    if (o == null) return false;
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        for (Node<E> p = first; p != null; p = p.next) {
            if (o.equals(p.item)) {
                unlink(p);
                return true;
            }
        }
        return false;
    } finally {
        lock.unlock();
    }
}
void unlink(Node<E> x) {
    // assert lock.isHeldByCurrentThread();
    Node<E> p = x.prev;
    Node<E> n = x.next;
    if (p == null) {
        unlinkFirst();
    } else if (n == null) {
        unlinkLast();
    } else {
        p.next = n;
        n.prev = p;
        x.item = null;
        // Don't mess with x's links.  They may still be in use by
        // an iterator.
        --count;
        notFull.signal();
    }
}

除了上面來自queue的方法。由雙鏈表的隊列。有很多雙向的操作。
比如:
addFirst、addLast、offerFirst、offerLast、removeFirst、removeLast、pollFirst、pollLast。都是對該隊列頭和尾操作。

關於queue這是項大工程:
分爲實現了阻塞隊列BlockingQueue 和沒有實現阻塞隊列BlockingQueue 兩種:
Queue的實現
1、 PriorityQueue 有序優先列表
ConcurrentLinkedQueue 線程安全
2、 ArrayBlockingQueue :一個由數組支持的有界隊列。
  LinkedBlockingQueue :一個由鏈接節點支持的可選有界隊列。(前面已講)
  PriorityBlockingQueue :一個由優先級堆支持的無界優先級隊列。
  DelayQueue :一個由優先級堆支持的、基於時間的調度隊列。
  SynchronousQueue :一個利用 BlockingQueue 接口的簡單聚集(rendezvous)機制。

來看看無界隊列PriorityBlockingQueue :

public class PriorityBlockingQueue<E> extends AbstractQueue<E>
    implements BlockingQueue<E>, java.io.Serializable {

該類說明:
1、實現了阻塞隊列。
2、無界,不可插入不可比較元素,不能爲null。
看看屬性:

/**
 * 默認數組初始容量 11
 */
private static final int DEFAULT_INITIAL_CAPACITY = 11;

/**
 * 爲數組申請的最大大小。超過該值報錯OutOfMemoryError
 */
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

/**
 * 優先隊列表示爲平衡的二進制堆:兩個子孩子queue[2*n+1] and queue[2*(n+1)]
 * 有指定排序或者自然排序 
 */
private transient Object[] queue;

/**
 * 元素個數
 */
private transient int size;

/**
 * 比較器
 */
private transient Comparator<? super E> comparator;

/**
 * 公共加鎖
 */
private final ReentrantLock lock;

/**
 * 爲空時條件阻塞
 */
private final Condition notEmpty;

/**
 * 自旋鎖進行分配,通過CAS獲取。
 */
private transient volatile int allocationSpinLock;

/**
 * 僅僅序列化考慮
 */
private PriorityQueue<E> q;

再看看構造方法:

// 構造初始容量11 ,自然排序
public PriorityBlockingQueue() {
    this(DEFAULT_INITIAL_CAPACITY, null);
}

/**
 * 構造指定容量,自然排序
 */
public PriorityBlockingQueue(int initialCapacity) {
    this(initialCapacity, null);
}

/**
 * 構造指定初始容量,指定排序
 */
public PriorityBlockingQueue(int initialCapacity,
                             Comparator<? super E> comparator) {
    if (initialCapacity < 1)
        throw new IllegalArgumentException();
    this.lock = new ReentrantLock();
    this.notEmpty = lock.newCondition();
    this.comparator = comparator;
    this.queue = new Object[initialCapacity];
}

/**
 * Collection下其他的集合的轉化
 */
public PriorityBlockingQueue(Collection<? extends E> c) {
    this.lock = new ReentrantLock();
    this.notEmpty = lock.newCondition();
    boolean heapify = true; // true if not known to be in heap order
    boolean screen = true;  // true if must screen for nulls
    if (c instanceof SortedSet<?>) {
        SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
        this.comparator = (Comparator<? super E>) ss.comparator();
        heapify = false;
    }
    else if (c instanceof PriorityBlockingQueue<?>) {
        PriorityBlockingQueue<? extends E> pq =
            (PriorityBlockingQueue<? extends E>) c;
        this.comparator = (Comparator<? super E>) pq.comparator();
        screen = false;
        if (pq.getClass() == PriorityBlockingQueue.class) // exact match
            heapify = false;
    }
    Object[] a = c.toArray();
    int n = a.length;
    // If c.toArray incorrectly doesn't return Object[], copy it.
    if (a.getClass() != Object[].class)
        a = Arrays.copyOf(a, n, Object[].class);
    if (screen && (n == 1 || this.comparator != null)) {
        for (int i = 0; i < n; ++i)
            if (a[i] == null)
                throw new NullPointerException();
    }
    this.queue = a;
    this.size = n;
    if (heapify)
        heapify();
}

分析類這麼多你會發現其他的queue,他也肯定是在維護某個對象。或數組或鏈表或樹。
我就來看看分別維護的是什麼。具體的操作方法,你用到時詳細去了解。

PriorityQueue transient Object[] queue; 數組
ConcurrentLinkedQueue Node 鏈表
ArrayBlockingQueue final Object[] items;數組
DelayQueue private final PriorityQueue q = new PriorityQueue(); 優先隊列
SynchronousQueue 還沒看懂

上面的具體細節。這裏我不講了。之後會將多線程,併發並行一起拿出來分。其實之前已經在多線程中講過上面的這些集合。但是都是從實際中應用,什麼場景下用什麼。沒有分析源碼,到底是怎麼做到的。
詳細參考:
併發容器

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