Java HashSet 如何避免重複值

  • 657
  • 0

最近好奇 Java 中 Set 到底是怎麼實作出判斷集合內部的元素有無重複的部分,所以看了一下 HashSet 原始碼的部分內容

原本看之前,猜測會是在 add 前,先檢查集合內是否已經有同樣的元素,來達成目的

看了原始碼發現 HashSet 內部是用 HashMap 在儲存資料,所以資料重複問題是透過 Map 來處理的

private transient HashMap<E,Object> map;

...

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

所以 HashSet 會將資料當作 HashMap 的 Key 值來儲存,而 HashMap 中會在將元素加入集合前會檢查 key 值,如果有相同的 key 值,就會覆蓋原有的資料,而藉此行為,HashSet 就可以達到資料不重複的效果

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, 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;
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    // 如果 hashtable 中沒有就直接建立新的
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        // 如果 key 值相同,就先將舊資料儲存到 e 變數
        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 {
            // 如果 key 值不同,就從 hashtable 部分的 link 繼續往下找
            for (int binCount = 0; ; ++binCount) {
                // 全部走遍後,確定沒有相同 key 值的資料後,直接建立新資料並儲存
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                // 如果 key 值相同,代表找到集合內部有相同 key 值的資料
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        // 若 e 有值,代表集合中已經有該 key 值的資料
        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;
}