Java集合之HashSet集合

文章目录

  • 前言
  • 一、HashSet集合特点
  • 二、HashSet集合的初始化
  • 三、HashSet集合中的成员方法
    • 1.添加集合元素
    • 2.删除集合元素
    • 3.查询集合元素
    • 4.修改集合元素
    • 5、其他成员方法
  • 四、集合的遍历
  • 总结


前言

HashSet集合继承了AbstractSet类,实现了Set接口。其框架图如下:
Java集合之HashSet集合_第1张图片

一、HashSet集合特点

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

二、HashSet集合的初始化

  • HashSet():无参构造,创建一个默认大小为16,负载因子为0.75的集合。源码如下:
  /**
     * Constructs a new, empty set; the backing HashMap instance has
     * default initial capacity (16) and load factor (0.75).
     */
    public HashSet() {
   
        map = new HashMap<>();
    }

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

  • HashSet(Collection c):有参构造,参数可以是List、Set接口的所有实现类。注意,Map接口的实现类不可以作为参数。源码如下:
   /**
     * Constructs a new set containing the elements in the specified
     * collection.  The HashMap 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

你可能感兴趣的:(java,java)