Java集合類HashSet的add方法

Set裏的數據是不會重複的

Set<String> set = new HashSet<>();
set.add("a");
public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

這裏有一個map變量和PRESENT變量

private transient HashMap<E,Object> map;

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

map在構造函數裏初始化,初始化大小爲16,加載因子是0.75

/**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * default initial capacity (16) and load factor (0.75).
     */
    public HashSet() {
        map = new HashMap<>();
    }

add裏調用map的put方法

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

最關鍵的來了

/**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    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等於當前map,若map爲空或大小爲0,直接擴容並獲取大小
        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;
            //如果哈希碼定位的key相同,在下一個if,用新的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 {
                for (int binCount = 0; ; ++binCount) {
                    //e記錄碰撞位置上鍊表下一個節點,如果到了鏈表的尾端
                    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;
                    }
                    //鏈表上hash和key都碰撞了,同樣的直接覆蓋value
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //替換新Value
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);//用於LinkedHashMape
                return oldValue;
            }
        }
        ++modCount;//記錄hash修改次數
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);//用於LinkedHashMape
        return null;
    }

用到的一些變量,table,在Set第一次使用時初始化,合適的時候以兩倍的方式擴容

transient Node<K,V>[] table;

Node類,實現了Map的Entry數組

//map的每個節點
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;
    }

TREEIFY_THRESHOLD,鏈表轉成紅黑樹的閾值

static final int TREEIFY_THRESHOLD = 8;

總結:HashSet用HashMap實現,把要插入的值作爲HashMap的key,保證的Set裏存儲元素的唯一性

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