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

实例

代码

Set 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");

执行跟踪

HashSet的add的实现原理深入刨析[jdk8]_第1张图片

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

原理分析

step1:进入HashSet.java类

#HashSet.java

private transient HashMap 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[] tab; Node 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 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)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 implements Map.Entry {
        final int hash;
        final K key;
        V value;
        Node next;

        Node(int hash, K key, V value, Node 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时,才断定二者相等.

你可能感兴趣的:(JAVA)