HashSet原理

95 阅读5分钟

特点说明

  • HashSet 实现了Set接口;
  • HashSet 实际上是HashMap,执行new HashSet()方法的源码:
public HashSet() {
    this.map = new HashMap();
}
  • HashSet线程不安全;
  • 可以存放null值,但是只能有一个null;
  • HashSet不能保证元素的存取顺序一致;
  • 不能有重复的元素;
  • 没有带索引的方法,所以不能通过普通for循环进行遍历;

add()源码分析

先说结论
  • 添加一个元素时,先通过hashCode()方法获取元素的hash值,对hash值进行运算,得到索引值即为要存放在哈希表中的位置号
  • 找到存储数据表table,看这个索引位置是否已经存放了元素
  • 如果没有存放,则直接添加
  • 如果存放了,调用 equals() 比较,如果相同,就放弃添加,如果不相同,则添加到最后
  • 在java8中,如果一条 链表 的元素个数达到TREEIFY_THRESHOLD(默认是8)(链表准备添加第九个的时候) ,并且 table 的大小 >=MIN_TREEIFY_CAPACITY(默认是64),就会进行树化(红黑树)
主要方法
  • 以Demo为例
public class Demo {
    public static void main(String[] args) {
        HashSet hashSet = new HashSet();
        hashSet.add("java");
        hashSet.add("kotlin");
        hashSet.add("java");
        System.out.println("hashSet:"+hashSet);
    }
}
  • add()方法
private static final Object PRESENT = new Object();

public boolean add(E e) {
    //PRESENT的目的是为了占位
    return this.map.put(e, PRESENT) == null;
}
  • this.map.put(e, PRESENT)
//此时key="java" value=PRESENT
public V put(K key, V value) {
    return this.putVal(hash(key), key, value, false, true);
}
  • hash(key)做了什么
//得到对应的hash值
static final int hash(Object key) {
    int h;
    //hashcode和无符号右移16位的hashcode后得到的值做异或运算
    return key == null ? 0 : (h = key.hashCode()) ^ h >>> 16;
}

这里没有直接使用key.hashCode()获取hash值,是为了减少hash的冲突

  • this.putVal(hash(key), key, value, false, true)
//Node数组
transient HashMap.Node<K, V>[] table;

//默认初始容量 (1 << 4 相当于 1*2*2*2*2)。JDK1.8中默认的初始容量是16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
   
//规定负载因子为0.75。 容量负载超过 12 = 16*0.75 ,则需要扩容 
static final float DEFAULT_LOAD_FACTOR = 0.75f;

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    //辅助变量
    Node<K,V>[] tab; Node<K,V> p; int n, i; 
    
    //如果当前table是null或者tab的大小为0,则执行下面的语句
    if ((tab = table) == null || (n = tab.length) == 0)
        //执行 resize(),创建大小为16的table数组
        n = (tab = resize()).length;
    //根据key得到的hash值去计算该key应该存放到tab表的哪个索引位置,并把这个位置的对象,赋给p
    //判断p是否为null
    if ((p = tab[i = (n - 1) & hash]) == null)
        //如果p为null,表示还没有存放元素,就创建一个Node(key="java",value="PRESENT")放在i的位置上
        tab[i] = newNode(hash, key, value, null);
    else {
        //p不为null,
        Node<K,V> e; K k;
        //
        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 {
            //如果table对应的索引位置,已经是一个链表,就使用for循环依次和该链表的每一个元素比较后(从链表的第二个元素开始比较,第一个节点上面已经比较过了),都不相同,则加入到该链表的最后;
            for (int binCount = 0; ; ++binCount) {
                //表示已经到达链表的最后一个元素
                if ((e = p.next) == null) {
                    //都不相同,加入到该链表的最后;
                    p.next = newNode(hash, key, value, null);
                    //在把元素添加到链表后,立即判断该链表是否已经到达(TREEIFY_THRESHOLD = 8;)8个节点
                    //(JDK11直接判断>=7)
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        //已经到达8个节点,调用treeifyBin(tab, hash);方法如果满足该方法中
                        // if (tab == null || (n = tab.length) < 64) 条件则先对table扩容;如果该条件不满足,则对当前这个链表进行树化(转成红黑树)
                        //JDK11 treeifyBin(tab, hash);方法略有变化
                        treeifyBin(tab, hash);
                    break;
                }
                //判断元素已经存在(元素相同)则退出循环
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                //将p更新为下一个元素
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                //
                e.value = value;
            //HashMap 留给子类的实现方法
            afterNodeAccess(e);
            return oldValue;
        }
    }
     //记录 HashSet的修改次数
    ++modCount;
    //判断是否需要扩容
    if (++size > threshold)
        resize();
    //HashMap 留给子类的实现方法
    afterNodeInsertion(evict);
    return null;
}

注意点:无论table数组上还是在链表上加入元素,size(元素的个数)都会加1,只要size的大于临界值后,就会对数组进行扩容

newNode 源码

HashMap.Node<K, V> newNode(int hash, K key, V value, HashMap.Node<K, V> next) {
        return new HashMap.Node(hash, key, value, next);
}
  • resize()扩容源码

1.第一次添加时,table数组扩容到16,临界值(threshold)是16*加载因子(loadFactor)是0.75 = 12
2.如果table数组使用到了临界值12,就会扩容到 16 * 2 = 32,新的临界值就是 32 * 0.75 = 24,依此类推

   //按照第一次扩容的
   final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        //记录当前表长 oldCap=16
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //需要扩容的负载容量大小 oldThr=12
        int oldThr = threshold;
        int newCap, newThr = 0;
        
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                //oldThr左移一位,newThr为 24 = 12*2
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
        //创建新表,容量为32
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        
        //将旧表中的数据转移到扩容后的新表中
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

注意:如果HashSet中存储的是Object类型,需要重写hashCode()和equals()方法,否则会出现HashSet中存在相同元素,违背HashSet()不能有重复的元素的原则;