HashSet的add的实现原理深入刨析[jdk8]

实例

代码

Set<String> set = Sets.newHashSet();
boolean flag1 = set.add("111");
boolean flag2 = set.add("222");
boolean flag3 = set.add("333");
boolean flag4 = set.add("222");
boolean flag5 = set.add("555");

执行跟踪

可以发现在add 第二个“222”时,返回了false;未重复时,返回true

原理分析

step1:进入HashSet.java类

#HashSet.java

private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

......省略无关代码

public boolean add(E e) {

       return map.put(e, PRESENT)==null;#通过map.put方法返回值是否为null来确定

 }

step2:进入HashMap类

#HashMap.java

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
	
static final int hash(Object key) {#hash并不等同hashCode方法,而是根据hashCode计算出来的,二者结果线性相关
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); #key的hashcode异或其无符号右移16位
    }
	
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;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))#这是代码里判断的语句,可以看出,这里用hash和equals都比较了,需要两个都返回true才可以
                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;
    }

其中Node代码如下

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;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

如果我们没有实现hashCode或者equals,二者都会调用Object上的方法,Object上hashCode方法是一个本地方法,返回的值应该是对象在内存中地址,而equals方法内是通过==判断地址是否一致.

#Object.java

public native int hashCode();
public boolean equals(Object obj) {
    return (this == obj);
}
所以,这一问的结论就有了,hashCode和equals方法都会用来判断相等,根据hashCode计算出的hash相等(这和直接要求hashCode相等有些区别),而且equals返回true时,才断定二者相等.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FeelTouch Labs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值