Java集合類原始碼

Liang2003發表於2024-06-16

Java集合類原始碼(粒度:方法層面)

ArrayList

構造方法,有三種

public ArrayList(int initialCapacity) 
/*
初始化容量>0,分配空間
初始化容量=0,賦值空陣列
否則拋IllegalArgumentException異常
*/
public ArrayList() //直接賦值空陣列
public ArrayList(Collection<? extends E> c)  
/*
對於集合C,若集合不為空,將C賦給底層陣列,否則賦值空陣列。
*/

其他方法

public void trimToSize() //將陣列的空餘位置全剪掉
public void ensureCapacity(int minCapacity)
//判斷是否容量是否大於等於minCapacity,否則擴容  

private static int calculateCapacity(Object[] elementData, int minCapacity)
//計算陣列的容量(預設為10),返回max(10,minCapacity)
   
private void ensureCapacityInternal(int minCapacity)
private void ensureExplicitCapacity(int minCapacity)
//以上三個函式配套,判斷當前陣列容量>=minCapacity,否則擴容
    
private void grow(int minCapacity)
//擴容,將原來容量擴到1.5倍,取與minCapacity的較大值,不超過INT.MAX_VALUE
    
private static int hugeCapacity(int minCapacity) 
/*
判斷minCapacity<0,小於0證明溢位了,報錯。
比較minCapacity與MAX_ARRAY_SIZE的大小,
如果比MAX_ARRAY_SIZE大,則返回int的最大值,否則返回MAX_ARRAY_SIZE
*/
    
public int size() //返回當前陣列包含的元素個數

public boolean isEmpty()//判空

public boolean contains(Object o)//判斷list是否存在元素o

public int indexOf(Object o) //返回元素o出現的第一個位置,沒出現返回-1

public int lastIndexOf(Object o)返回元素o出現的最後一個位置,沒出現返回-1

public Object clone()//返回陣列的淺複製

public Object[] toArray()//返回list的靜態陣列

其他的,增刪有操作一個元素,有操作多個元素。
刪除具有快速失敗機制,發現modCount和之前不對,就返回刪除失敗,

清空陣列,

實現迭代器Iterator功能,

序列化。

HashMap

成員變數

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 預設容量
static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量
static final float DEFAULT_LOAD_FACTOR = 0.75f;//負載因子,當佔用空間超過容量的這個比例就會擴容
static final int TREEIFY_THRESHOLD = 8;//節點樹化閾值,(插入後)連結串列節點數大於這個值則樹化
static final int UNTREEIFY_THRESHOLD = 6;//退化成連結串列的閾值
static final int MIN_TREEIFY_CAPACITY = 64;//節點樹化的條件之一:要滿足整體容量>=64

transient Node<K,V>[] table;//底層陣列
transient Set<Map.Entry<K,V>> entrySet;
final float loadFactor;//負載因子
transient int modCount;
transient int size;
int threshold;//當map元素個數達到threshold個,發生擴容

重點方法

  1. 新增元素putval
//所有的新增,最後都是走這裡
/*
hash:key的hash值
onlyIfAbsent :true的話,不替代原有元素,false替換
evict:false表示剛建立map時新增初始元素,true表示建map後新增新元素
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
    	//判斷tab為空
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;//擴容
        //i儲存在tab陣列下標位置,下面判斷到該位置沒有被佔
    	if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
         
            Node<K,V> e; K k;
            //如果當前位置的key相同,替換
            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);
                        //如果該條鏈已經大於等於8個了,樹化
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //找到相同key的鍵值對
                    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;
    }
  1. 擴容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) {
            //達到最大,擴不了,將threshold調到最大,能裝多少就裝多少
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                //擴容到原來的兩倍
                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"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = 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. 樹節點的Split方法,用來擴容時重新分位置。可以看到和上面連結串列的分鏈一模一樣。
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
            TreeNode<K,V> b = this;
            // Relink into lo and hi lists, preserving order
            TreeNode<K,V> loHead = null, loTail = null;
            TreeNode<K,V> hiHead = null, hiTail = null;
            int lc = 0, hc = 0;
            for (TreeNode<K,V> e = b, next; e != null; e = next) {
                next = (TreeNode<K,V>)e.next;
                e.next = null;
                if ((e.hash & bit) == 0) {
                    if ((e.prev = loTail) == null)
                        loHead = e;
                    else
                        loTail.next = e;
                    loTail = e;
                    ++lc;
                }
                else {
                    if ((e.prev = hiTail) == null)
                        hiHead = e;
                    else
                        hiTail.next = e;
                    hiTail = e;
                    ++hc;
                }
            }
			/*
			和連結串列分鏈的唯一區別是判斷是否要樹化或反樹化
			*/
            if (loHead != null) {
                if (lc <= UNTREEIFY_THRESHOLD)
                    tab[index] = loHead.untreeify(map);
                else {
                    tab[index] = loHead;
                    if (hiHead != null) // (else is already treeified)
                        loHead.treeify(tab);
                }
            }
            if (hiHead != null) {
                if (hc <= UNTREEIFY_THRESHOLD)
                    tab[index + bit] = hiHead.untreeify(map);
                else {
                    tab[index + bit] = hiHead;
                    if (loHead != null)
                        hiHead.treeify(tab);
                }
            }
        }
  1. 節點樹化 treeify,將連結串列建成紅黑樹
final void treeify(Node<K,V>[] tab) {
            TreeNode<K,V> root = null;
            for (TreeNode<K,V> x = this, next; x != null; x = next) {
                next = (TreeNode<K,V>)x.next;
                x.left = x.right = null;
                
                if (root == null) {
                    x.parent = null;
                    x.red = false;//根節點是黑色的
                    root = x;
                }
                else {
                    K k = x.key;
                    int h = x.hash;
                    Class<?> kc = null;
                    for (TreeNode<K,V> p = root;;) {
                        int dir, ph;
                        K pk = p.key;
                        if ((ph = p.hash) > h)
                            dir = -1;
                        else if (ph < h)
                            dir = 1;
                        else if ((kc == null &&
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            dir = tieBreakOrder(k, pk);

                        TreeNode<K,V> xp = p;
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
                            x.parent = xp;
                            if (dir <= 0)
                                xp.left = x;
                            else
                                xp.right = x;
                            root = balanceInsertion(root, x);
                            break;
                        }
                    }
                }
            }
            moveRootToFront(tab, root);
        }
  1. 反樹化untreeify,就是將treeNode變回Node,化鏈。
 final Node<K,V> untreeify(HashMap<K,V> map) {
            Node<K,V> hd = null, tl = null;
            for (Node<K,V> q = this; q != null; q = q.next) {
                Node<K,V> p = map.replacementNode(q, null);
                if (tl == null)
                    hd = p;
                else
                    tl.next = p;
                tl = p;
            }
            return hd;
        }

相關文章