天天看點

Java集合架構源碼分析集合架構

集合架構

Collection(單列)

結構圖:

Java集合架構源碼分析集合架構

分析:Collection接口繼承了Iterator,而List又繼承了Collection,是以實作List的類都具有Iterator和Collection的相關方法。

List

特點:有序,可重複

ArrayList

底層:是一個數組

分析源碼

字段
//預設的初始化容量
 	private static final int DEFAULT_CAPACITY = 10;
	//空數組
	private static final Object[] EMPTY_ELEMENTDATA = {};
	//空數組
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
	//arraylist底層維護的數組
    transient Object[] elementData;
	//數組的大小
    private int size;
           
構造器
//指定初始化容量
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);
        }
    }


 public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;//預設給定一個空數組
    }


//傳入一個Collection接口的實作類對象
public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
           
add方法

1.無參構造器

第一次擴容

public class ArrayList_ {
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        for (int i = 1; i <= 10 ; i++) {
            list.add(i);
        }
        list.add(100);
    }
}

//初始化數組,給定一個空數組
public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

//先進行裝箱
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//執行add方法
public boolean add(E e) {
        ensureCapacityInternal(size + 1);  //需要的容量為數組大小加1,即為1
        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);//則容量設為10
        }
        return minCapacity;
    }

//确認最後的容量(Explicit 明确的)
private void ensureExplicitCapacity(int minCapacity) {
        modCount++;//一個計數器,用于并發情況下的

   
        if (minCapacity - elementData.length > 0)//如果最小容量大于此時數組長度,則說明要擴容
            grow(minCapacity);//進行擴容
    }

//擴容操作
private void grow(int minCapacity) {
        int oldCapacity = elementData.length;//得到舊的數組容量(剛開始為0)
        int newCapacity = oldCapacity + (oldCapacity >> 1);//容量進行右移一位再加上原來的容量,即容量變為原來的1.5倍,即還是0
        if (newCapacity - minCapacity < 0)//如果新容量小于最小容量
            newCapacity = minCapacity;//則将最小容量賦給新容量
        if (newCapacity - MAX_ARRAY_SIZE > 0)//若新容量大于數組最大長度 (MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);//進行數組複制操作
    }

//最大容量
private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) //若最小容量認為0,則抛出異常
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;//最小容量大于最大數組長度,則傳回Integer.MAX_VALUE,否則傳回MAX_ARRAY_SIZE
    }


public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;//将元素指派給數組
        return true;
    }

           

第二次擴容

public class ArrayList_ {
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        for (int i = 1; i <= 10 ; i++) {
            list.add(i);
        }
        list.add(100);
    }
}

//先進行裝箱
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//執行add方法
public boolean add(E e) {
        ensureCapacityInternal(size + 1);  //需要的容量為數組大小加1,此時為11
        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;//此時直接傳回11
    }

//确認最後的容量
private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)//最小容量為11大于數組長度10,是以要進行擴容
            grow(minCapacity);
    }

//擴容操作
private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;//得到原來的數組長度為10
        int newCapacity = oldCapacity + (oldCapacity >> 1);//新容量為舊容量乘以1.5倍之後,為15
        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);//進行數組複制操作
    }

public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;//将元素指派給數組
        return true;
    }

           

2.有參構造器

初始化容量

public class ArrayList_ {
    public static void main(String[] args) {
        ArrayList list = new ArrayList(8);//初始化容量為8
        for (int i = 1; i <= 8 ; i++) {
            list.add(i);
        }
        list.add(100);
    }
}

public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {//若容量大于0
            this.elementData = new Object[initialCapacity];//進行初始化容量,即建立一個數組
        } else if (initialCapacity == 0) {//若等于0
            this.elementData = EMPTY_ELEMENTDATA;//則賦給一個數組
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }


public class ArrayList_ {
    public static void main(String[] args) {
        ArrayList list = new ArrayList(8);//初始化容量為8
        for (int i = 1; i <= 8 ; i++) {
            list.add(i);
        }
        list.add(100);
    }
}

//先進行裝箱
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//執行add方法
public boolean add(E e) {
        ensureCapacityInternal(size + 1);  //需要的容量為數組大小加1,即為1
        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;//直接傳回1
    }

//确認最後的容量(Explicit 明确的)
private void ensureExplicitCapacity(int minCapacity) {
        modCount++;//一個計數器,用于并發情況下的

   
        if (minCapacity - elementData.length > 0)//如果最小容量大于此時數組長度,則說明要擴容
            grow(minCapacity);//此時并不進行擴容
    }


public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;//将元素指派給數組
        return true;
    }
           

進行擴容

public class ArrayList_ {
    public static void main(String[] args) {
        ArrayList list = new ArrayList(8);
        for (int i = 1; i <= 8 ; i++) {
            list.add(i);
        }
        list.add(100);
    }
}

//先進行裝箱
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//執行add方法
public boolean add(E e) {
        ensureCapacityInternal(size + 1);  //需要的容量為數組大小加1,即為9
        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;//直接傳回9
    }

//确認最後的容量(Explicit 明确的)
private void ensureExplicitCapacity(int minCapacity) {
        modCount++;//一個計數器,用于并發情況下的

   
        if (minCapacity - elementData.length > 0)//如果最小容量(9)大于此時數組長度(8),則說明要擴容
            grow(minCapacity);//此時并不進行擴容
    }

//擴容
private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;//舊容量為原數組大小8
        int newCapacity = oldCapacity + (oldCapacity >> 1);//新容量為8*1.5=12
        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);//進行數組複制
    }

public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;//将元素指派給數組
        return true;
    }
           

LinkedList()

底層:是一個雙向連結清單

分析源碼

字段
//連結清單大小
	transient int size = 0;//trasient 短暫的 序列化過程中不會被序列化
	//頭結點
    transient Node<E> first;

  	//尾結點
    transient Node<E> last;
           
構造器
public LinkedList() {
    }


    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }
           
add方法
public class LinkedList_ {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        for (int i = 1; i <= 10; i++) {
            list.add(i);
        }

    }
}

//無參構造器
public LinkedList() {
    }

//裝箱
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//add方法
public boolean add(E e) {
        linkLast(e);//向連結清單後面追加一個元素
        return true;
    }

//連結清單尾部添加元素
void linkLast(E e) {
        final Node<E> l = last;//尾結點指向結點l,此時為null
        final Node<E> newNode = new Node<>(l, e, null);//建立一個新的結點,并且前驅指向l
        last = newNode;//新的結點也指向last即為null
        if (l == null)//如果結點l為null
            first = newNode;//則新節點指向頭結點
        else//如果不為null
            l.next = newNode;//新節點賦給結點l的後繼
        size++;//連結清單長度加1
        modCount++;//修改次數加1
    }



           
remove方法
public class LinkedList_ {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        for (int i = 1; i <= 10; i++) {
            list.add(i);
        }

        list.remove();
    }
}

//remove方法,其實調用的是removefirst方法
public E remove() {
        return removeFirst();
    }

//removeFirst方法
public E removeFirst() {
        final Node<E> f = first;//将頭結點指派給一個結點
        if (f == null)//如果頭結點為null,則抛出異常
            throw new NoSuchElementException();
        return unlinkFirst(f);//進入unlinkFirst方法
    }

//unlinkFirst方法
private E unlinkFirst(Node<E> f) {
        // assert f == first && f != null;
        final E element = f.item;//取出頭結點中的值
        final Node<E> next = f.next;//将頭結點的下一個元素賦給一個結點
        f.item = null;//将頭結點的值賦為null
        f.next = null; //null賦給頭結點的後繼指向,利用GC将其回收( help GC)
        first = next;//将頭結點的後繼結點賦給頭結點
        if (next == null)//若後繼節點為null
            last = null;//則null賦給尾結點
        else
            next.prev = null;//否則将null賦給後繼節點的前驅指向
        size--;//連結清單大小減1
        modCount++;//修改次數+1
        return element;//傳回值
    }
           

ArrayList和LinkedList的對比

  • 增删用LinkedList,查找用ArrayList。

Vector

分析源碼

字段
//數組
	protected Object[] elementData;

	//數組中元素個數
    protected int elementCount;

    //容量每次增加的值
    protected int capacityIncrement;
	
	//數組的最大大小
	private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
           
構造器
//有參構造器(初始化容量,容量增長量)
	public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }

   //有參構造器(初始化容量)
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

    //無參構造器
    public Vector() {
        this(10);
    }

    //可以傳入一個Collection的實作類對象
    public Vector(Collection<? extends E> c) {
        elementData = c.toArray();
        elementCount = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }
           
add方法

1.無參構造

public class Vector_ {
    public static void main(String[] args) {
        Vector vector = new Vector();
        for (int i = 1; i <= 10 ; i++) {
            vector.add(i);
        }
        vector.add(100);//達到10個之後,進行擴容
    }
}

//進入無參構造器
public Vector() {
        this(10);//初始化容量預設為10
    }

public Vector(int initialCapacity) {
        this(initialCapacity, 0);//容量增加量預設為0
    }

public Vector(int initialCapacity, int capacityIncrement) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    this.elementData = new Object[initialCapacity];//在這裡生成一個數組賦給elementData
    this.capacityIncrement = capacityIncrement;//容量增長量為0
}

//裝箱
 public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//add操作,與ArrayList不同的是加上了synchronized關鍵字(是以,vector是線程安全的)
 public synchronized boolean add(E e) {
        modCount++;//修改次數加1
        ensureCapacityHelper(elementCount + 1);//需要容量為目前數組個數+1,即0+1=1
        elementData[elementCount++] = e;
        return true;
    }

private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code()
        if (minCapacity - elementData.length > 0)//如果最小容量(0)大于數組的大小(10),是以并不需要擴容
            grow(minCapacity);//進行擴容
    }


//第二次擴容  vector.add(100);//達到10個之後,進行擴容

 public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }

private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)//此時11>10,是以要進行擴容
            grow(minCapacity);
    }

//擴容
private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;//記錄舊容量
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);//若容量增量大于0,則新容量等于舊容量+容量增量;否則,加上舊容量,即為2倍,此時為20
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);//進行數組複制
    }

public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;//将元素複制給數組
        return true;
    }

           

2.指定初始化容量

public class Vector_ {
    public static void main(String[] args) {
        Vector vector = new Vector(8);
        for (int i = 1; i <= 8 ; i++) {
            vector.add(i);
        }
        vector.add(100);
    }
}

public Vector(int initialCapacity) {
        this(initialCapacity, 0);//此時初始容量為8
    }

public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];//賦一個數組大小為8的數組
        this.capacityIncrement = capacityIncrement;
    }



//add操作相同

//進行擴容操作 vector.add(100);

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);//此時所需最小容量為9,
        elementData[elementCount++] = e;
        return true;
    }

private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)//9>8
            grow(minCapacity);//是以要進行擴容
    }

private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;//記錄舊容量為10
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);//新容量為10*2=20
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);//複制元素
    }

public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;//将元素指派給數組
        return true;
    }

           

ArrayList與Vector對比

  • ArrayList是線程不安全的,而Vector是線程安全的
  • ArrayList比Vector效率更高

Set

特點:無序,不能重複

結構

Java集合架構源碼分析集合架構

HashSet

分析源碼

字段
//維護的map
	private transient HashMap<E,Object> map;
	//值
    private static final Object PRESENT = new Object();
           
構造器
//無參構造器
	public HashSet() {
        map = new HashMap<>();
    }

 	//可以傳入一個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
    HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }
           
add方法
public class HashSet_ {
    public static void main(String[] args) {
        HashSet hashSet = new HashSet();
        for (int i = 1; i <= 12 ; i++) {
            hashSet.add(i);
        }
        hashSet.add(200);
    }
}

//HashSet的底層其實就是HashMap
 public HashSet() {
        map = new HashMap<>();
    }

//初始化HashMap
 public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // 加載因子預設為0.75
    }

//裝箱
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//add方法其實就是調用HashMap的put方法
public boolean add(E e) {
        return map.put(e, PRESENT)==null;//傳入鍵e,值是 static final Object PRESENT = new Object();
    }

//put操作
public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);//首先計算Key的hash值
    }

//hash操作
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);//一個對hash值操作的算法
    }


//putVal操作
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)//如果hash表為空
            n = (tab = resize()).length;//則進行初始化,并得到hash表的長度
        if ((p = tab[i = (n - 1) & hash]) == null)//将長度與hash值進行運算得到該元素在hash表中的索引,若此索引處沒有元素
            tab[i] = newNode(hash, key, value, null);//直接new一個新的結點在此位置上
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))//比較數組中的元素與即将放入的元素的hash并且比較key值和equals結果,若相等則不放入,将該元素賦給e
                e = p;
            else if (p instanceof TreeNode)//如果連結清單變成了紅黑樹
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);//進行指派
            else {
                for (int binCount = 0; ; ++binCount) {//将連結清單中的元素逐個取出,進行比較。注意這裡沒有判斷條件,死循環
                    if ((e = p.next) == null) {//若後繼節點為null
                        p.next = newNode(hash, key, value, null);//則直接在後面添加一個結點
                        if (binCount >= TREEIFY_THRESHOLD - 1) //若連結清單元素的個數大于 static final int TREEIFY_THRESHOLD = 8;
                            treeifyBin(tab, hash);//則進行樹化
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))//進行比較該元素和即将放入元素的hash值和key值
                        break;
                    p = e;//将e指向p,一個接一個周遊
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;//修改次數+1
        if (++size > threshold)//當hash表的長度大于門檻值(12)時,會進行擴容
            resize();
        afterNodeInsertion(evict);
        return null;
    }


//resize操作(擴容)
final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;//計算出原來的hash表的長度
        int oldThr = threshold;//得到舊門檻值
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {//若舊容量大于static final int MAXIMUM_CAPACITY = 1 << 30
                threshold = Integer.MAX_VALUE;//則門檻值設定成最大正型
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)//在這裡新的容量賦為原來的2倍
                newThr = oldThr << 1; // 新的門檻值設定成原來的2倍
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;//新容量預設為16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//新門檻值為加載因子*預設容量=0.75*16=12
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;//将新門檻值賦給map的門檻值
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];//初始化一個Node節點的數組,大小為新容量,即為16
        table = newTab;//并将這個新hash表賦給map中的hash表
        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;
    }

//treeifyBin操作
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)//若hash表的長度小于最小樹化大小(64),則不會進行樹化,而是進行hash表的擴容
            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);
        }
    }
           

LinkedHashSet

特點:LinkedHashSet是有序的,其實它就是數組加雙向連結清單,每次加入一個結點,就加入道雙向連結清單中

字段

構造方法
public LinkedHashSet(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor, true);
    }

    public LinkedHashSet(int initialCapacity) {
        super(initialCapacity, .75f, true);
    }

    public LinkedHashSet() {
        super(16, .75f, true);
    }

    public LinkedHashSet(Collection<? extends E> c) {
        super(Math.max(2*c.size(), 11), .75f, true);
        addAll(c);
    }
           
add方法
public class LinkedHashSet_ {
    public static void main(String[] args) {
        LinkedHashSet linkedHashSet = new LinkedHashSet();
        for (int i = 1; i <= 10; i++) {
            linkedHashSet.add(i);
        }
    }
}

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

HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);//LinkedHashSet底層其實就是LinkedHashMap
    }

public LinkedHashMap(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor);
        accessOrder = false;
    }

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


final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            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 {
                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;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);//在這裡将其結點指向
        return null;
    }
           

TreeSet

特點:

  • 其底層是TreeMap
  • 有序
  • 當hash表存入一個結點的同時,會有EntrySet裡面存放指向這個結點的指針,用于快速周遊map

分析源碼

字段
private transient NavigableMap<E,Object> m;

    private static final Object PRESENT = new Object();
           
構造器
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));
    }

    public TreeSet(Collection<? extends E> c) {
        this();
        addAll(c);
    }

    public TreeSet(SortedSet<E> s) {
        this(s.comparator());
        addAll(s);
    }
           
add操作
public class TreeSet_ {
    public static void main(String[] args) {
        TreeSet treeSet = new TreeSet(new Comparator() {//若沒有構造器,會采用自己的系統預設的構造器
            @Override
            public int compare(Object o1, Object o2) {
                return ((String)o1).compareTo((String)o2);
            }
        });
        treeSet.add("mike");
        treeSet.add("jack");
        treeSet.add("lucy");
        System.out.println("treeSet="+treeSet);
    }
}

public TreeSet(Comparator<? super E> comparator) {
        this(new TreeMap<>(comparator));
    }

 public TreeMap(Comparator<? super K> comparator) {
        this.comparator = comparator;
    }

 public boolean add(E e) {
        return m.put(e, PRESENT)==null;//值預設為object
    }

public V put(K key, V value) {
        Entry<K,V> t = root;
        if (t == null) {
            compare(key, key); // type (and possibly null) check

            root = new Entry<>(key, value, null);
            size = 1;
            modCount++;
            return null;
        }
        int cmp;
        Entry<K,V> parent;
        // split comparator and comparable paths
        Comparator<? super K> cpr = comparator;
        if (cpr != null) {//利用自己的構造器的compare進行比較
            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);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        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;
    }
           

Map(雙列)

結構圖:

Java集合架構源碼分析集合架構

HashMap

分析源碼

字段
//hash表初始化的大小為16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    //hash表的最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;

    //預設的加載因子為0.75
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    //連結清單轉紅黑樹的結點數為8
    static final int TREEIFY_THRESHOLD = 8;

    //紅黑樹轉連結清單的結點數為6(剪枝)
    static final int UNTREEIFY_THRESHOLD = 6;

    //最小的樹化hash表大小為64
    static final int MIN_TREEIFY_CAPACITY = 64;
           
構造器
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);
    }

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }
           
put操作
public class HashMap_ {
    public static void main(String[] args) {
        HashMap hashMap = new HashMap();
        hashMap.put("java",10);
        hashMap.put("php", 10);
        hashMap.put("java", 20);
    }
}

public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

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

 static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            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 {
                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;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { //當連結清單中存在這個相同的結點時
                V oldValue = e.value;//記錄這個結點的值
                if (!onlyIfAbsent || oldValue == null)//如果舊value為null的話
                    e.value = value;//将這個即将加入的結點的value賦給此節點的value
                afterNodeAccess(e);
                return oldValue;//傳回老結點的value,即當put進去同一個key的鍵值對的話,做替換工作,傳回舊的value
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
           

HashTable

特點:hashtable是線程安全的,并且key和value不能為null

分析源碼

字段
private transient Entry<?,?>[] table;

    private transient int count;

    private int threshold;

    private float loadFactor;

    private transient int modCount = 0;
           
構造器
public Hashtable(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal Load: "+loadFactor);

        if (initialCapacity==0)
            initialCapacity = 1;
        this.loadFactor = loadFactor;
        table = new Entry<?,?>[initialCapacity];
        threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    }

    public Hashtable(int initialCapacity) {
        this(initialCapacity, 0.75f);
    }

    public Hashtable() {
        this(11, 0.75f);
    }

    public Hashtable(Map<? extends K, ? extends V> t) {
        this(Math.max(2*t.size(), 11), 0.75f);
        putAll(t);
    }
           
put操作
public class HashTable_ {
    public static void main(String[] args) {
        Hashtable hashtable = new Hashtable();
        for (int i = 1; i <= 12 ; i++) {
            hashtable.put(i, i);
        }
    }
}

public Hashtable() {
        this(11, 0.75f);//初始化容量為11,加載因子為0.75
    }

public Hashtable(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal Load: "+loadFactor);

        if (initialCapacity==0)
            initialCapacity = 1;
        this.loadFactor = loadFactor;
        table = new Entry<?,?>[initialCapacity];
        threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    }

 public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//put操作,由于加上了synchronized關鍵字,是以hashtable是線程安全的
public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {//若value為null,則會抛出空指針異常
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }

        addEntry(hash, key, value, index);
        return null;
    }

private void addEntry(int hash, K key, V value, int index) {
        modCount++;

        Entry<?,?> tab[] = table;
        if (count >= threshold) {//門檻值為11*0.75=8
            // Rehash the table if the threshold is exceeded
            rehash();//在這裡會進行hash擴容

            tab = table;
            hash = key.hashCode();
            index = (hash & 0x7FFFFFFF) % tab.length;
        }

        // Creates the new entry.
        @SuppressWarnings("unchecked")
        Entry<K,V> e = (Entry<K,V>) tab[index];
        tab[index] = new Entry<>(hash, key, value, e);
        count++;
    }


protected void rehash() {
        int oldCapacity = table.length;
        Entry<?,?>[] oldMap = table;

        // overflow-conscious code
        int newCapacity = (oldCapacity << 1) + 1;//新容量為舊容量*2+1
        if (newCapacity - MAX_ARRAY_SIZE > 0) {
            if (oldCapacity == MAX_ARRAY_SIZE)
                // Keep running with MAX_ARRAY_SIZE buckets
                return;
            newCapacity = MAX_ARRAY_SIZE;
        }
        Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];

        modCount++;
        threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
        table = newMap;

        for (int i = oldCapacity ; i-- > 0 ;) {
            for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
                Entry<K,V> e = old;
                old = old.next;

                int index = (e.hash & 0x7FFFFFFF) % newCapacity;
                e.next = (Entry<K,V>)newMap[index];
                newMap[index] = e;
            }
        }
    }
           

Properties

特點:其底層是hashtable

字段
構造方法
public Properties() {
        this(null);
    }

    public Properties(Properties defaults) {
        this.defaults = defaults;
    }
           
put方法
public class Properties_ {
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put("jack", "傑克");
        properties.put("mike", "邁克");
        System.out.println(properties);
    }
}

public Properties() {
        this(null);
    }

 public Properties(Properties defaults) {
        this.defaults = defaults;
    }

 public Hashtable() {
        this(11, 0.75f);
    }


//下面與hashtable相同
           

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;//compartor會設定為null
    }

	//有參構造(傳入一個comparator的實作類)
    public TreeMap(Comparator<? super K> comparator) {
        this.comparator = comparator;
    }

    public TreeMap(Map<? extends K, ? extends V> m) {
        comparator = null;
        putAll(m);
    }

    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) {
        }
    }
           
put操作
public class TreeMap_ {
    public static void main(String[] args) {
        TreeMap treeMap = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((String)o1).compareTo((String)o2);
            }
        });
        treeMap.put("jack", "傑克");
        treeMap.put("mike", "邁克");
        treeMap.put("lucy", "露西");
        System.out.println("treeMap"+treeMap);

    }
}

public TreeMap(Comparator<? super K> comparator) {
        this.comparator = comparator;
    }

public V put(K key, V value) {
        Entry<K,V> t = root;
        if (t == null) {
            compare(key, key); // type (and possibly null) check

            root = new Entry<>(key, value, null);
            size = 1;
            modCount++;
            return null;
        }
        int cmp;
        Entry<K,V> parent;
        // split comparator and comparable paths
        Comparator<? super K> cpr = comparator;//在這裡擷取構造器中的comparator
        if (cpr != null) {
            do {
                parent = t;
                cmp = cpr.compare(key, t.key);//利用比較器裡面的compare方法進行比較
                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);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else//在這裡,如果比較器為0,則說明相等
                    return t.setValue(value);//新的值替換掉舊的值
            } while (t != null);
        }
        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;
    }


 TreeMap treeMap = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((String)o1).compareTo((String)o2);
            }
        });