文章目录
前言
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