详述HashSet 的add方法执行过程

详述HashSet 的add方法执行过程

1、思考HashSet中的add方法如何执行
public static void main(String[] args) {
		HashSet<String> set=new HashSet<String>();	
		set.add("张三");
}
public HashSet() {
   map = new HashMap<>();	//map 是 HashSet中的全局变量 此时 当new HashSet时 其实时new了一个HashMap 并且赋值给了HashSet中的map变量
}
2、我们接下进入HashSet中的add方法
public boolean add(E e) {
  	 return map.put(e, PRESENT)==null; 
    //注意 此时 map变量 指向的是 HashMap类
    //当我们调用HashSet中的add方法时 实际上调用的却是HashMap类中的put方法
}
3、此时我们进入add方法中出现的put方法
public V put(K key, V value) {	//此时的key 是调用add 方法是传入进来的参数 ,value 是在HashSet 中的常量
        return putVal(hash(key), key, value, false, true);
}
4、在HashMap中被调用的hash方法
static final int hash(Object key) {	//此时的key 是我们上面调用add方法中传进来的值
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    //三目表达式 判断传进来的值 是否为null 如果不为null 便会计算一个hashCode值
    //hashCode方法可以得到一个hashCode值:不同对象的hashCode值一定不相同,相同对象的HashCode的值一定相同。
    //此时key 为上转型对象 运行时指向父类Object中的hashCode方法 运行时会调用子类中的hashCode方法
   	//你传进来的Key值时什么类型的 那么就会调该类型中的重写后的equals方法
    }

5、(重点1)分析put方法中被调用的putVal方法

单击查看二次赋值

​ 重点分析putVal方法 因为 能否添加成功 主要在于这个方法

​ 因为该putVal方法返回null ——> put方法返回null——>add方法返回true

putVal方法中resize方法 可以单击直接进入 单击进入resize()方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
    //int hash 是上面put方法中计算我们上面调用add方法时 传进来的值的hashCode值
    //key 时add 方法传进来的值
    //value 是我们在hashSet类中的变量
    //onlyIfAbsent 是我们在put方法中调用putVal 方法时赋予的false值
    //evict 是我们在put方法中调用putVal 方法时赋予的true值   
    	Node<K,V>[] tab; Node<K,V> p; int n, i;
    //tab,p,n,i 是局部变量 没有初始值
        if ((tab = table) == null || (n = tab.length) == 0)
    //table是HashMap中的全局变量 初始值 是null 传给当前方法中的局部变量tab 此时他俩指向的是同一个地址 目前都null 满足条件(||短路或 只需满足一个条件 便可进入)        
            n = (tab = resize()).length;
    //此时 调用resize()方法 赋值给tab后获取长度再赋值给n
    //resize()的返回值与table指向同一个地址。并且给返回值默认长度16。
        if ((p = tab[i = (n - 1) & hash]) == null)
   //n为16,i的值跟hash有关,即不同的hash对应不同的i值。因为此时tab为null,所以tab[i]为null,则该if一定执行            
            tab[i] = newNode(hash, key, value, null);
   //将key为我们调用add方法里面参数张三,value为一个HashSte的常量,即相对应的hash赋值给tab[i]。
   //tab 是由 table 赋值的 所以他俩指向的都是同一个地址 
    
        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;//执行完上个if,直接到这里,该putVal方法返回null,结束该方法。
}

(重点)二次赋值

两次相同的值或两次不同的值

因为 我们上面有讲过第一次赋值时putVal方法会如何执行 所以我们在此 只解释当我们二次赋值或第二次赋相同值 putVal方法方式的情况

如果需要看第一次赋值时 putVal方法会如何进行 请单击第一次赋值时putVal方法运行的

String类型的equals方法的解释点击进入

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)
            //当我们第二次赋值时,table不等于null,所以跳过该if语句内容。
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
             //第二次赋相同的值时,n还是16。因为此时第二个Tom的hash与第一个一样,所以i一样,所以该if内容不执行,进入else。但此时第一个tab[i]已经赋值给p。
            tab[i] = newNode(hash, key, value, null);
    
     // 因为只要 我们两次都是赋相同的值的时候 就会进入下面的else块
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
    //p.hash 是我们第一次赋值的hash值 跟后面的我们第二赋值的hash值进行比较 (&& 逻辑与  两个条件必须全部满足)
   //p.key 是我们第一次的值 先赋值给k 再让k跟第二次赋的key值进行地址上的比较 
   //如果 前面那个 判断不满足 走后面
   //传进来的key值 不为空 并且当前key为上转型对象 编译时指向父类 Object 但是 运行时 执行子类中 重写的equals方法
   //你传进来的Key值时什么类型的 
                
   //那么就会调该类中的重写后的equals方法 下面有以String类型作为示例来讲解
                
                
   //(|| 逻辑或 满足一个条件即可)因为我们已满足前面的条件所以直接进入if块
                e = p;
             // 我们把p的值传e  if块走完
            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 //因为我们前面把p的值赋给e 所以此时e不为null
                V oldValue = e.value;	//将e的value赋值给oldValue
                if (!onlyIfAbsent || oldValue == null)	//onlyIfAbsent为put方法传进来的参数false,(||逻辑或 满足一个条件 )所以执行该if内容。
                    e.value = value;//第二个value的值把第一个值的value覆盖,但HashSet的value没有意义,所以对此无影响。
                afterNodeAccess(e);
                return oldValue;	//返回值oldValue,结束该方法。
            }
        }
           
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

String类中 equals比较时的代码

因为此时时putVal方法中的Key值是String类型的 那么我们此时便会调用String中重写后的equals方法

   public boolean equals(Object anObject) { //注意 注意 注意 重要的事情 说三遍
       //equals 是上面这个 pubVal方法中变量key调用的但是  equals方法中的行参是当前key调用时传入的参数    
       
        if (this == anObject) {  //this代表当前 谁调用便会 指向谁 此时this指向调用equals 方法的Key   anObject 是equals方法的形参 Key调用方法传入的参数
            return true;
        }
        if (anObject instanceof String) { //判断equals 方法的形参是否为String类型
            String aString = (String)anObject;  //如果上面判断成功 便会把equals方法的形参转为String类型 并赋值给aString变量
            if (!COMPACT_STRINGS || this.coder == aString.coder) {  //COMPACT_STRINGS 是String 类中定义的实参 值为false (|| 短路与 满足一个条件即可) COMPACT_STRINGS取反为true 进入          
                return StringLatin1.equals(value, aString.value); //
               // 调用StringLatin1类中的equals方法 里面的两个参数是 你要比较的两个值 并且会把这两个值 拆分为一个一个放入到byte类型的数组中
            }
        }
        return false;
    }
StringLatin1类中的equals方法
 public static boolean equals(byte[] value, byte[] other) { //里面两个形参 是上面String类中equals 调用该类中equals 方法传入的值
        if (value.length == other.length) {  //先比较两个数组的长度 如果长度不同 就不会进入 
            for (int i = 0; i < value.length; i++) {  //循环比较
                if (value[i] != other[i]) {  //分别比较两个数组中的每一位元素
                    return false;  //只要 有一位不用便会返回false
                }
            }
            return true;  //如果两个数组里面所存储的每一位元素都相同 便会返回true  
        }
        return false;  //如果没进if判断 便会直接返回false
    }

自定义类型赋值

​ 1、自定义类型的添加值 跟上面分析添加值时一样的流程 不过 得在自定义类中重写equals和hashCode 方法

public static void main(String[] args) {
		HashSet<Student> set=new HashSet<Student>();
		set.add(new Student("10"));//添加自定义类型的数据
}

重写equals方法

String类中eqluas方法单击查看

public boolean equals(Object anObject) {
	if(anObject instanceof Student) { //此时我们以 Student 来举例    判断equals 方法的形参是否为Student类型
		Student stu=(Student)anObject;	//如果上面判断成功 便会把equals方法的形参转为Student类型 并赋值给stu变量
		return this.id.equals(stu.id);	////this代表当前 谁调用便会 指向谁 此时this指向调用equals方法的这个自定义类   那么此时我们用这个类中id 跟 传进来的stu变量里的id 进行比较 比较方式 和上面的讲解的String类型一样
	} 
    return false;
}

重写hashCode方法

@Override
public int hashCode() {	
	return this.id.hashCode();//this代表当前 谁调用便会 指向谁 此时this指向调用hashCode方法的这个自定义类   那么此时我们将会获取这个类中id的hashCode值
}
(重点2)resize()方法
        Node<K,V>[] oldTab = table;
        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;
            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"})
        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;
 }
posted @ 2021-05-12 21:35  鹤唳。  阅读(161)  评论(0)    收藏  举报