栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java HashSet集合保证元素唯一性的源码分析

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java HashSet集合保证元素唯一性的源码分析

HashSet集合的特点:
由于是Set集合,所以不包含重复元素

当用add添加元素时,如果多次添加相同的元素,集合里也只会存在一个,因为只会插入一次

源码添加注释如下:

public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}
//计算对象的哈希值
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//此处的形参key就是要插入的元素e
public V put(K key, V value) {
        //hash(key)就是对象的哈希值
    return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
    Node[] tab; Node 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 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)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()方法会调用put(),ptu()会调用putVal(),并且putVal将对象的哈希值作为第一个参数,对象作为第二个参数传递。

可以总结出HashMap添加集合的过程:

其实HashSet的底层是数组加链表实现的,通过hashcode的值计算出存储位置(比如取余求位置),这个位置就是对应的数组下标,如果该位置有元素了并且判断该位置的所有元素的哈希值和内容都与当前对象不同,那就当前对象接在这个位置存在的链表上,就像邻接表一样。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/305379.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号