Java源码阅读-HashSet

本文详细解析了HashSet如何通过HashMap实现元素的添加与查找功能,利用HashMap的键唯一特性确保集合内元素不重复。

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

private transient HashMap<E,Object> map; // 维护了一个HashMap的变量

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


添加元素

/**
     * Adds the specified element to this set if it is not already present.
     * More formally, adds the specified element <tt>e</tt> to this set if
     * this set contains no element <tt>e2</tt> such that
     * <tt>(e==null ? e2==null : e.equals(e2))</tt>.
     * If this set already contains the element, the call leaves the set
     * unchanged and returns <tt>false</tt>.
     *
     * @param e element to be added to this set
     * @return <tt>true</tt> if this set did not already contain the specified
     * element
     */
    public boolean add(E e) {
        return map.put(e, PRESENT)==null; // 将值作为key-value的key添加到map中,value为虚设的PRESENT。借助map的key不能重复来保证set中的值不重复
    }

判断元素是否存在

/**
     * Returns <tt>true</tt> if this set contains the specified element.
     * More formally, returns <tt>true</tt> if and only if this set
     * contains an element <tt>e</tt> such that
     * <tt>(o==null ? e==null : o.equals(e))</tt>.
     *
     * @param o element whose presence in this set is to be tested
     * @return <tt>true</tt> if this set contains the specified element
     */
    public boolean contains(Object o) {
        return map.containsKey(o); // 添加到set中的元素都作为map的key,所以直接用map是否包含该key来判断
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值