HashSet中add()方法的执行过程

本文深入解析Java中HashMap类的工作机制,包括hash方法的实现细节,如何处理字符串、整数及自定义类对象的哈希计算,以及HashSet如何利用HashMap存储元素。通过具体代码示例,阐述了HashMap的扩容机制和解决哈希冲突的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1HashMap类中的hash(Object key)分析

static int hash(Object key) {    //HashMap方法中的hash方法
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
	public static void main(String[] args) {
	//对象是String类型时
	int hash=hash("Tom");
		System.out.println(hash);
		hash=hash(new String("Tom"));
		System.out.println(hash);
	//对象是int类型和int类型的包装类时	
		hash=hash(1);
		System.out.println(hash);
		hash=hash(new Integer(1));
		System.out.println(hash);
	//对象是自定义类的对象	
		hash=hash(new H());
		System.out.println(hash);
		hash=hash(new H());
		System.out.println(hash);
	}
	class H{}

结果

84275
84275					方法参数	Object key
~~~~~~
1                    // String类型和int类型都是传入的值
1                   //值不为空时进行了h = key.hashCode()) ^ (h >>> 16)操作,值为空返回0,
					//内容相同的返回值一定相同
~~~~~~
5433712          //使用自定义类型时,不同的对象传入不同的地址
2430314

HashSet中add()方法的执行

public static void main(String[] args) {
		HashSet<String> set=new HashSet<>();  //调用HashSet中的无参构造方法
		set.add("tom");  
		set.add("tom");
		set.add("S");
		}

//HashSet存储的实质是存储了HashMap的key;
Ctrl点击代码中的add
进入HashSet类中

  public boolean add(E e) {   //add方法中的变量传入到参数e中,PRESENT是一个常量
        return map.put(e, PRESENT)==null;
    }

点击put
进入HashMao类中,hash方法上文提过

//e, PRESENT分别传入key和value中,
//所以HashSet存储的实质是存储了HashMap的key;
public V put(K key, V value) {  
        return putVal(hash(key), key, value, false, true);
    }

点击putVal
处入HashMao类中 hash(key), key, value, false, true分别传入
int hash, K key, V value, boolean onlyIfAbsent,
boolean evict

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

分析循环体,
点击table,table是hashmap中的一个泛型结合,成员变量,无赋值则默认值为null

transient Node<K,V>[] table;    

分析循环体,tab=table则为null,逻辑或短路,执行则if语句
n = (tab = resize()).length;

 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 {

点击resize();进入方法
可以看出 resize是一个数组

final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;       //没有赋值,则等于table,table为null
        int oldCap = (oldTab == null) ? 0 : oldTab.length;   //oldCap=0,
        int oldThr = threshold;     // int threshold是成员变量,默认值为0
        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;
    }

执行else

 newCap = DEFAULT_INITIAL_CAPACITY;
 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);

点击DEFAULT_INITIAL_CAPACITY

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 常量=16  newCap值为16

点击
DEFAULT_LOAD_FACTOR

static final float DEFAULT_LOAD_FACTOR = 0.75f;

所以前面提到的循环执行的代码为

threshold = newThr;
 @SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];  //newCap=16,所以数组长度为16
table = newTab;          //table=一个长度为16的数组

方法返回newTab

 return newTab;

再回到上述代码,执行下一个if语句

 if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;

联系上下代码,下面是tab出现的位置,可以知道tab是定义在方法中的一个局部变量,[]中的代码得到数组的长度,是个空数组,条件体是成立的,所以执行tab[i] =newNode(hash, key, value, null);此时 key值就存储在了tab[]中,也就是add()方法第一次添加的值

return null;

第一次执行结束

第二次执行时,与第一次添加的String内容相同
table中[null, null, null, tom=java.lang.Object@ccd017, null, null, null, null, null, null, null, null, null, null, null, null]已经有了一个值,则不为空,所以执行else
第二次传入的值为"Tom",hash值相同,key值相同,逻辑或短路,执行内部if,e=p
前文已经提到过Node<K,V> p是一个局部变量,第一次执行时p = tab[i = (n - 1) & hash]是个数组,所以第二次得到的数组结果仍是第一次得到的数组结果

 else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;

可以看到执行了else语句后要执行后文中的if语句,e=p显然不等于空,返回旧值,结束方法table中的值没有变化

    if (e != null) { // existing mapping for key
                    V oldValue = e.value;
                    if (!onlyIfAbsent || oldValue == null)
                        e.value = value;
                    afterNodeAccess(e);
                    return oldValue;
                }
 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;
            }
        }

第三次执行开始 add(“S”)
通过上文分析可以轻易得出table不为空,hash值也不同,key也不同

 if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);

hash值变化,tab[]括号中的值会发生变化,指向数组另外一个位置[null, null, null, tom=java.lang.Object@ccd017, null, null, null, null, null, null, null, null, null, null, null, null]显然为空,所以执行if语句中的内容,添加新的值,if执行,else不执行,程序跳转,return结束;

 ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值