【Java集合】HashSet

平时关注比较多的都是HashMap,没怎么关注过HashSet,今天仔细看了一遍HashSet的源码,解决了困扰了比较久的几个问题,分别是:
1.HashSet的底层结构是什么?
2.HashSet如何实现去重?

1、HashSet的底层结构

这个问题在打开源码的一瞬间就找到了答案,注释里面作了清楚的说明:This class implements the Set interface, backed by a hash table (actually a HashMap instance) ,HashSet内部包含了一个HashMap的实例,对HashSet的操作实际都是对HashMap实例的操作。比较有意思的地方在于HashSet还定义了一个成员变量PRESENT作为所有添加到HashSet中元素的值,即以添加到HashSet中的元素为Key,以此处定义的成员变量PRESENT为Value,组成Key-Value键值对,然后添加到HashMap实例中。

//用于储存对象
private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

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

2、HashSet如何实现去重

这个问题的答案也在add方法中,不过具体得看HashMap的put()方法,源码如下:
HashMap#put

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

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

对于该方法中有关添加元素的逻辑判断等不作展开,此处需要关注的是下面这段代码:

//省略其他代码。。。
//p为HashMap中key索引位置原来存在的元素
if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;

//省略其他代码,在满足上面条件的情况下,会跳转到下面的代码块
 if (e != null) { // existing mapping for key
                V oldValue = e.value;
                //@param onlyIfAbsent if true, don't change existing value
                if (!onlyIfAbsent || oldValue == null)  
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }

从上面代码可以看出,在HashMap中,当添加元素的Key已经存在时,HashMap会替换key所对应的value,同时返回oldvalue。而当添加元素的Key不存在时,则正常添加,最后返回null。
回到HashSet中,由于添加到HashSet中的元素在其内部HasMap的实例中充当的角色是Key,所以当重复添加时map.put(e,PRSENT)==null值为false,表示添加失败。

3、迭代器问题

在HashSet的类注释中有这么一段话:

Iterating over this set requires time proportional to the sum of
 the <tt>HashSet</tt> instance's size (the number of elements) plus the
"capacity" of the backing <tt>HashMap</tt> instance (the number of
 buckets).  Thus, it's very important not to set the initial capacity too
 high (or the load factor too low) if iteration performance is important.

遍历该集合的时间取决于HashSet实例的规模和HashMap实例规模的和,如果对迭代性能要求较高,不要设置太高的初始容量或太低的装载因子。

  • 6
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java集合类中的HashSet是一种基于哈希表实现的集合,它继承自AbstractSet类并实现了Set接口。HashSet类提供了高效的查找、插入和删除操作,可以存储不重复的元素。HashSet类的构造方法有四种形式:HashSet()、HashSet(int initialCapacity)、HashSet(int initialCapacity, float loadFactor)和HashSet(Collection<? extends E> c)。 你可以使用以下代码来创建一个HashSet集合: 1. 使用无参构造方法: HashSet<Integer> set = new HashSet<>(); 2. 使用指定初始容量的构造方法: HashSet<Integer> set1 = new HashSet<>(20); 3. 使用指定初始容量和负载因子的构造方法: HashSet<Integer> set2 = new HashSet<Integer>(20, 0.8f); 4. 使用指定集合的构造方法: HashSet<Integer> set3 = new HashSet<>(new ArrayList<Integer>()); 使用HashSet集合时,需要注意元素的唯一性和哈希值的计算,HashSet类内部使用哈希函数来计算元素的哈希值,并根据哈希值来存储和查找元素。当两个元素的哈希值相同时,HashSet会通过equals()方法来判断它们是否相等。在使用HashSet时,建议重写equals()和hashCode()方法,以确保元素的唯一性和正确的哈希值计算。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Java中的集合类:HashSet](https://blog.csdn.net/friend_X/article/details/113755564)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值