详述HashSet中的add()方法 (上)

本文探讨了HashSet的add()方法为何不允许添加相同内容的String值。通过源码分析,揭示了HashSet在内部使用HashMap存储元素,通过hash()方法确保唯一性。当内容相同的String调用hash()时,返回值相同,导致无法重复添加。

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

一、先来看一段代码

                HashSet<String> set =new HashSet<>();
		set.add("Tom");
		set.add("Tom");
		set.add(new String("Tom"));
		System.out.println(set.size());

其输入结果为

1

二、通过上述结果,我们发现HashSet中的add()方法不能重复添加内容相同的String类型的值,那它的原因是什么呢?我们来看看它的源代码。

1、HashSet对象创建时会创建一个HashMap对象。

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

2、HashSet对象在调用add()方法时会将参数存入HashMap的key中。

    //下面为HashSet的add()方法   
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

    //下面为HashMap的put方法
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

3、HashMap中的hash()方法

    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

4、我们来看一下hash()方法的作用

public class Hash {
	
	static final int hash(Object key) {
	    int h;
	    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
	}
	public static void main(String[] args) {
		HashSet<String> set =new HashSet<>();
		set.add("Tom");
		int hash =hash("Tom");
		System.out.println(hash);
		hash=hash(new String("Tom"));
		System.out.println(hash);
		hash=hash("Lucy");
		System.out.println(hash);

		
	}
}	

5、从上图可以看出:对于String类型来说,内容相同的变量它们调用hash()方法的返回值是相同的。

三、HashMap怎么存的?

1、我们来看一下HashMap中的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;
        
        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 {
        //第二次传入“Tom”时,执行以下代码
            Node<K,V> e; K k;
        // p.hash为第一次"Tom"的hash,与此时的hash一样,同时k=key.
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
        //给e赋值
                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;
                }
            }
            //e不为null,返回第一次传入"Tom"时的数组。
            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;
    }

2、当HashMap对象创建后,table全局变量为null。

3、tab随后被赋值一个长度为16的数组,故n=16。

4、由于是第一次传值,p=null, 所以就向tab对应位置存入了值。

5、第二次传入“Tom”时,tab不等于null,p也不为null。因为n为第一次传入“Tom”的n,hash与第一次传入“Tom”的hash一样,故tab对应位置不为null,p也就不为null。

6、第二次传入“Tom”操作在上图标明。

7、当传入“Lucy”时,此时的hash与前面的hash不同,故tab对应位置为null,p也为null。

8、随后在tab数组新的位置存入“Lucy”。

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值