编程语言
首页 > 编程语言> > HashSet集合保证元素唯一性的源码分析(睡起来再看一遍

HashSet集合保证元素唯一性的源码分析(睡起来再看一遍

作者:互联网

//创建集合对象
HashSet<String> hs = new HashSet<>();

//添加元素
hs.add("hello");
hs.add("world");
hs.add("java");

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

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

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

//hash值和元素的hasCode()方法相关
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,// 4
                   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;
            /*
            ★
            存入的元素和以前的元素比较哈希值 //①
                如果哈希值不同,会继续向下执行,把元素添加到集合//②
                如果哈希值相同,会调用对象的equals()方法比较//③
                    如果返回false,会继续向下执行,把元素添加到集合//④
                    如果返回true,说明元素重复,不存储//⑤
            */
            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;
}

 

标签:唯一性,hash,tab,HashSet,元素,value,源码,key,null
来源: https://www.cnblogs.com/dayangchongyang/p/15866736.html