【jdk源码解析四】java.uti.HashSet源码解析

HashSet与ArrayList的最主要区别在于,在HashSet中的元素不会出现重复的。其内部实现机制如下:

为了保证在HashSet中出现重复元素,实际上,HashSet是通过一个内部的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();

    /**
     * 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);
    }

在上面代码中可以看出,在HashSet初始化时,如果初始化集合为空,则会初始化一个空的HashMap,也就是初始容量为16,初始装载因子为0.75的HashMap。

如果初始化集合不为空,则会初始化一个初始装载因子为0.75的HashMap。



HashSet中的所有的元素都被作为key值,以一个初始化的变量PRESENT作为值来构建它内部的HashMap。


HashSet继承自AbstractSet抽象类和Set接口。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值