HashSet源码解析

前言

HashSet ,基于 HashMap 的 Set 实现类。在业务中,如果我们有排重的需求,一般会考虑使用 HashSet 。

hashset类图
在这里插入图片描述

实现 java.util.Set 接口,并继承 java.util.AbstractSet 抽像类。
实现 java.io.Serializable 接口。
实现 java.lang.Cloneable 接口

HashSet内部属性
在这里插入图片描述
HashSet内部属性就两个

private transient HashMap<E,Object> map;

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

map 的 key ,存储 HashSet 的每个 key 。
map 的 value ,因为 HashSet 没有 value 的需要,所以使用一个统一的 PRESENT 即可。代码如下:

构造方法

    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * default initial capacity (16) and load factor (0.75).
     */
    public HashSet() {
        map = new HashMap<>();
    }

    /**
     * Constructs a new set containing the elements in the specified
     * collection.  The <tt>HashMap</tt> is created with default load factor
     * (0.75) and an initial capacity sufficient to contain the elements in
     * the specified collection.
     *
     * @param c the collection whose elements are to be placed into this set
     * @throws NullPointerException if the specified collection is null
     */
    public HashSet(Collection<? extends E> c) {
        map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
        addAll(c);
    }

    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * the specified initial capacity and the specified load factor.
     *
     * @param      initialCapacity   the initial capacity of the hash map
     * @param      loadFactor        the load factor of the hash map
     * @throws     IllegalArgumentException if the initial capacity is less
     *             than zero, or if the load factor is nonpositive
     */
    public HashSet(int initialCapacity, float loadFactor) {
        map = new HashMap<>(initialCapacity, loadFactor);
    }

    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * the specified initial capacity and default load factor (0.75).
     *
     * @param      initialCapacity   the initial capacity of the hash table
     * @throws     IllegalArgumentException if the initial capacity is less
     *             than zero
     */
    public HashSet(int initialCapacity) {
        map = new HashMap<>(initialCapacity);
    }

    /**
     * Constructs a new, empty linked hash set.  (This package private
     * constructor is only used by LinkedHashSet.) The backing
     * HashMap instance is a LinkedHashMap with the specified initial
     * capacity and the specified load factor.
     *
     * @param      initialCapacity   the initial capacity of the hash map
     * @param      loadFactor        the load factor of the hash map
     * @param      dummy             ignored (distinguishes this
     *             constructor from other int, float constructor.)
     * @throws     IllegalArgumentException if the initial capacity is less
     *             than zero, or if the load factor is nonpositive
     */
    HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }

在构造方法中,会创建 HashMap 或 LinkedHashMap 对象。

添加单个元素

#add(E e) 方法,添加单个元素。代码如下:

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

map 的 value 值,就是我们看到的 PRESENT
private static final Object PRESENT = new Object();

而添加多个元素,继承自 AbstractCollection 抽象类,通过 #addAll(Collection<? extends E> c) 方法,代码如下:

public boolean addAll(Collection<? extends E> c) {
    boolean modified = false;
    // 遍历 c 集合,逐个添加
    for (E e : c)
        if (add(e))
            modified = true;
    return modified;
}

在方法内部,会逐个调用 #add(E e) 方法,逐个添加单个元素。

移除单个元素

#remove(Object key) 方法,移除 key 对应的 value ,并返回该 value 。代码如下:


public boolean remove(Object o) {
    return map.remove(o) == PRESENT;
}

查找单个元素

public boolean contains(Object o) {
    return map.containsKey(o);
}

清空


public void clear() {
    map.clear();
}

总结

HashSet 是基于 HashMap 的 Set 实现类。

hashmap源码分析:https://blog.csdn.net/qq_42600094/article/details/130556792

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值