HashSet判断重复原理

这个知识点完全属于今天的意外收获\(≧▽≦)/

首先会调用Object的hashCode方法判hashCode是否已经存在,如不存在则直接插入元素;

如果已存在则调用Object对象的equals方法判断是否返回true,如果为true则说明元素已经存在,如为false则插入元素。

注:图片是借鉴他人博客,我再上面添加了一些额外标记


首先我们看HashSet的源码中add方法

/**
     * Adds the specified element to this set if it is not already present.
     * More formally, adds the specified element <tt>e</tt> to this set if
     * this set contains no element <tt>e2</tt> such that
     * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>.
     * If this set already contains the element, the call leaves the set
     * unchanged and returns <tt>false</tt>.
     *
     * @param e element to be added to this set
     * @return <tt>true</tt> if this set did not already contain the specified
     * element
     */
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

我们看到它里面调用的是map的put方法,map就是HashSet中定义的一个HashMap

Set的add方法中传入的参数作为map的key,突然间恍然大悟,原来Set存放数据不重复的原理和Map的key不重复是一样的

那我们继续跳进map的put方法

/**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

put方法中调用了同类中的putVal方法,这个方法的第一个参数就是一个hash值,hash值是通过同类中的hash方法来获取的

/**
     * Computes key.hashCode() and spreads (XORs) higher bits of hash
     * to lower.  Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

这个代码我看不太懂,但是可以出来hash方法里获取了key的hashCode并做了相应的处理。

(借鉴)

我上网查了一下,原来这个hash方法叫做“扰动函数”。有人解释说:API的设计者,不能假定用户实现了良好的hashCode方法,所以通常会对hashCode再计算一次。在get和put计算下标时,先对hashCode进行hash操作,然后再通过hash值进一步计算下标。

好,那我们重新回到putVal方法中看看,这里面都做了什么??

    /**
     * Map.put()方法的实际实现
     *
     * @param hash key的hash值
     * @param key 键值对中的key
     * @param value 键值对中的value
     * @param onlyIfAbsent 如果为true,则键值对中的值已经存在则不修改这个值
     * @param evict 如果为false,则是处于创建模式
     * @return 上一次的value,如果上一次的value不存在,则为null
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        //tab用于暂存散列表table。p为散列表中对应索引的链表的头节点的指针。n存储tab的长度。i则为命中的散列表的索引
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //给tab和n赋值
        //当tab为null或者tab的长度n为0时,触发resize()来初始化tab
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //使用(n - 1) & hash(等价于hash%n)计算命中的散列表索引,同时判断散列表对应索引的链表是否存在
        if ((p = tab[i = (n - 1) & hash]) == null)
            //散列表对应索引的链表不存在则创建一个新的链表
            tab[i] = newNode(hash, key, value, null);
        else {//散列表对应索引的链表已存在
            Node<K,V> e; K k;
            // 判断头节点的hash值和key是否与入参的hash值和key一致。需要注意,null的hash值为0
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                // 对应的键值对已经存在,记录下来
                e = p;
            else if (p instanceof TreeNode)//判断对应的链表是否转化为红黑树
                //若是,则直接调用红黑树的putTreeVal()方法
                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开始,所以为阈值-1 
                            // 将链表转化为红黑树
                            treeifyBin(tab, hash);
                        // 中断循环
                        break;
                    }
                    // 判断当前遍历的节点的hash值和key是否与入参的hash值和key一致,即key是否已经存在
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        // key已经存在,中断循环
                        break;
                    // 记录当前遍历的节点
                    p = e;
                }
            }
            if (e != null) { // Map中存在重复的key
                V oldValue = e.value;//记录下旧值
                if (!onlyIfAbsent || oldValue == null)//判断值存在是否可以进行修改以及旧值是否为null
                    e.value = value;//修改该节点的值
                afterNodeAccess(e);// 链表节点的回调方法,此处为空方法
                return oldValue;//返回旧值
            }
        }
        // HashMap发生结构变化,变化次数累加
        ++modCount;
        // 键值对个数自增,同时判断是否达到扩容的阈值
        if (++size > threshold)
            resize();
        // 链表节点的回调方法,此处为空方法
        afterNodeInsertion(evict);
        // 此处返回null是因为链表新增了节点,所以上一次的值必然为null
        return null;
    }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值