HashSet源码分析

HashSet的全面说明

1.实现了Set接口
2.实际上是一个HashMap,源码
3.可以存放null,只能有一个
4.不保证元素是有序的(取出顺序固定 ),取出hash后,在确定索引的结果
5.不能有重复对象

模拟底层存储结构(数组+链表)
在这里插入图片描述
基础使用

public class HashSet01 {
    public static void main(String[] args) {
        HashSet<Object> set = new HashSet<>();


        //add,加入成功返回true
        System.out.println(set.add("aaa"));//true
        System.out.println(set.add("bbb"));//true
        System.out.println(set.add("aaa"));//flase
        System.out.println(set.add(null));//true
        System.out.println(set.add(null));//flase
        System.out.println(set);

        set = new HashSet<>();
        
        Dog d1 = new Dog("sdf");
        Dog d2 = new Dog("sdf");
        
        set.add(d1);//true
        set.add(d2);//true
        
        System.out.println(set.add(new String("asd")));
        System.out.println(set.add(new String("asd")));
    }
}

HashSet底层存储机制
底层是HashMap,HashMap底层是(数组+链表+红黑树)

public HashSet() {
 map = new HashMap<>(); 
}

模拟底层数据结构

public class HashSetStructure {
public static void main(String[] args) {
//模拟HashSet底层(HashMap底层)
//存放数据的数组。
Node[] table = new Node[16];
Node john = new Node("john",new Node("jack",new Node("rose",null)));
table[2]=john;


Node luck = new Node("luck",null);
table[3]=luck;
}
//模拟底层
}
class Node{
Object item;
Node next;
public Node(Object item, Node next) {
this.item = item;
this.next = next;
}
}

底层机制说明

1.底层是HashMap
2.添加一个元素的时候,先得到hash值,转化为索引
3.找到数据表table,根据索引找位置,看这个位置是否存在元素
4.如果没有,直接加入
5.如果有,调用equals比较,相同则放弃加入,不同则添加到最后
6.java8中,一条链表的元素个数到8,并且table的大小大于等于64,就会转化为红黑树
(如果链表个数到8,table不到64,会扩容table)

来段代码分析底层

public class HashSetSource {
    public static void main(String[] args) {
        HashSet<Object> set = new HashSet<>();
        set.add("java");
        set.add("php");
        set.add("java");
        System.out.println("set"+set);


    }
}

执行第一次add(“java”):

源码解读
1.执行HashSet()构造器
在这里插入图片描述
2.执行add(“java”)

PRESENT:new Object();(占位使用) static,所以是共享的
e : “java”
在这里插入图片描述
在这里插入图片描述

3.执行put
在这里插入图片描述

4.hash(key)
得到key对应的hash值
hash值**不是hashCode值
算法:h = key.hashCode()^(h>>16)
在这里插入图片描述
5.执行putVal方法

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就是HashMap的一个数组,类型为Node
    //if语句表示如果当前table为null,或者大小=0
    //就是第一次扩容,到达16个空间
    if ((tab = table) == null || (n = tab.length) == 0)
       //第一次扩容,调用这个方法。源码在下面
        n = (tab = resize()).length;

    // (1)根据key得到hash,去计算key应该存放的索引位置,并且把这个位置的对象赋给p
    // (2)判断是否为空
    //  (2.1)如果p为空,表示还没有存放元素,就创建一个Node(key="java" value="PRESENT")
    //  (2.2)就放在该位置tab[i]=newNode(hash,key,value,null)
    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))))
            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;
   //如果大于12,就扩容
    if (++size > threshold)
        resize();
   //这是一个空的方法,留给子类实现
    afterNodeInsertion(evict);
   //成功就返回空
    return null;
}

resize()源码

final Node<K,V>[] resize() {
      // 新建一个Node   ,oldTab指向table(这时候table为null)
    Node<K,V>[] oldTab = table;
    
   //如果为空,oldCap=0;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    
    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)
            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;//  默认为16
          //加载因子0.75,  newThr =12
         // 就是表中加入的元素到12个的时候,就考虑扩容了
         
        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);
    }
    
    //把临界值12记录下来
    threshold = newThr;
    
    @SuppressWarnings({"rawtypes","unchecked"})
    
    // 新建一个16个空间的Node给newTab
    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;
                    }
                }
            }
        }
    }
    
    //这里newTab的大小是16
    return newTab;
}

执行第二次add

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;
        
       //走这个
       //根据hash得到的索引中没有其他元素。直接把值给i处索引的位置
    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))))
            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;
}

执行第三个add
add(“java”)

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;

    //之前加入了一个java了,所以这里不为空,所以也不进入
    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  和  p指向的key是同一个对象
             //       不是同一个对象,但是equals相同
            //  就不能加入了
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;

        //再判断p是不是一颗红黑树,
        //如果是红黑树,就调用putTreeVal,来进行添加
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);


        //如果table对应的索引位置已经是一个链表,就使用for循环比较
        //依次和该链表的每一个元素比较后,都不相同,则加入到该链表的最后
        // 依次比较的过程中,如果有相同的情况,直接退出
        else {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    //立即判断,是否达到8个结点、
                    //就调用。。。方法,对当前链表进行树化
                    //进行树化的时候,进行判断,如果table<64,先扩容table,
                    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;
}

总结:
1.先获取元素的hash值
2.对hash值进行运算**,得到哈希表中的位置索引**
3.如果索引处没有元素,直接插入如果有元素,需要进行equals判断。如果相等,就不添加。如果不同,就用链表的方式添加

分析HashSet的扩容,和转化红黑树机制

  1. HashSet底层是HashMap.第一次添加时,table数组扩容到16,临界值(threshold)是16*加载因子5 = 12
    (loadFactor)是0.7

2.如果table数组使用**到了临界值12,就会扩容到162= 32,**新的临界值就是320.75 = 24,依次类推

3.在Java8中,如果一条链表的元素个数到达TREEIFY_THRESHOLD(默认是8).并且table的大小>=MIN TREEIFY CAPACITY(默认64),就会进行树化(红黑树),否则仍然采用数组扩容机制

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值