当前位置:网站首页>HashSet underlying source code

HashSet underlying source code

2022-06-13 00:59:00 -LM-

Conclusion

  1. HashSet The bottom is HashMap
  2. When adding an element , First get hash value , Will be converted to index value
  3. Find the storage table table, Check whether there are existing elements at this index position
  4. without , Directly to join
  5. If there is , call equals Compare , If the same , Just give up adding , If it's not the same , Add to the last
  6. stay Java8 in , If the number of elements in a linked list exceeds TREEIFY_THRESHOLD( The default is 8), also table The size of is greater than or equal to MIN_TREEIFY_CAPACITY( The default is 64), It turns into a red black tree .

Inheritance system

 Insert picture description here

Source code interpretation

1、 Constructors , Bottom use HashMap

public HashSet() {
    
     map = new HashMap<>();
}

2、add Method , Call to HashMap Of put Method

public boolean add(E e) {
    
    return map.put(e, PRESENT)==null;
}

3、 perform put Method ,key It's an incoming parameter ,value It's a Object object , placeholder , Don't put anything , Always the same

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

 Insert picture description here
4、 Calculation hash value , obtain key Corresponding hash value , Not equivalent to hashcode

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

5、 Get into putval Method

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
    
        Node<K,V>[] tab; Node<K,V> p; int n, i;  // Define auxiliary variables 
        // if Statement indicates if the current table yes null, Or the size is 0, For the first time , To 16 Space 
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //  according to key, Got hash value , Calculation key It should be stored in table Which index position of the table , Assign the position of the object to  p
        //  Judge  p  Is it empty , If it is empty, it means that the element has not been placed , Just create one Node
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
      // If p  Not empty , Prove that the element has been placed 
            Node<K,V> e; K k;
            //  If the first element of the linked list corresponding to the current index position and the key Of hash Same value 
            //  And meet the needs of those who are ready to join  key  and  p  Point to the Node Node key Is the same object   perhaps   Same content 
            //  Can't join 
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //  To determine  p  Is it a red black tree 
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);  // If it's a red-black tree , call putTreeVal add to 
            else {
    
                // If table The corresponding index position is a linked list , Traverse the linked list to judge 
                for (int binCount = 0; ; ++binCount) {
    
                    if ((e = p.next) == null) {
     //  It is different from each element of the linked list , Then add to the end of the linked list 
                        p.next = newNode(hash, key, value, null);
                        // Add to the linked list , Immediately judge whether the linked list has reached 8 Nodes , Reached 8 Tree nodes 
                        //  Whether it is really treelized , You also need to determine whether the length of the table exceeds 64, Less than 64 Just expand the capacity of the array 
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //  Compare in turn , If there is the same direct break
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //  If this value exists, the old value will be returned 
            if (e != null) {
     // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //size Every time you add a node ,size I'll add one 
        if (++size > threshold)   // Judge whether to expand capacity 
            resize();
        afterNodeInsertion(evict);  // Subclasses use ,HashMap It's an empty method 
        return null;
    }

Expansion mechanism

HashSet The bottom is HashMap, The first time I added it ,table Expand the array to 16, The critical value is 16* Load factor ( The default is 0.75), Reach the critical value for capacity expansion

原网站

版权声明
本文为[-LM-]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280557174099.html