Java集合之HashSet集合


前言

HashSet集合继承了AbstractSet类,实现了Set接口。其框架图如下:
在这里插入图片描述

一、HashSet集合特点

  • 存放单列元素,无序而且不重复。
  • 线程不安全,效率高。
  • 集合元素可以为null。
  • 没有下标,不可以通过索引获取到集合元素。

二、HashSet集合的初始化

  • HashSet():无参构造,创建一个默认大小为16,负载因子为0.75的集合。源码如下:
  /**
     * 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<>();
    }

通过源码可看出,HashSet集合的底层是使用HashMap实现的。具体HashMap的内容将在后面讲到。

  • HashSet(Collection<? extends E> c):有参构造,参数可以是List、Set接口的所有实现类。注意,Map接口的实现类不可以作为参数。源码如下:
   /**
     * 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
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值