JAVA集合源码攻坚战(13)—— HashSet
前言
前面介绍了Set这一分支的接口和抽奖类,今天来看看它的一个具体实现类——HashSet。
正文
HashSet层次结构
java.util
Class HashSet<E>
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractSet<E>
java.util.HashSet<E>
参数类型
E - 由此集合维护的元素的类型
All Implemented Interfaces:
Serializable , Cloneable , Iterable <E>, Collection <E>, Set <E>
已知直接子类:
JobStateReasons , LinkedHashSet
什么是HashSet
HashSet是java集合框架的一部分,继承了AbstractSet,实现了Set接口。
底层依赖于HashMap,数据存储在内部map的键上,每个键值对的值都是同一个静态object对象。展示了一种无序,不可重复的数据结构。
HashSet如何存储数据
HashSet底层依赖于HashMap,每次存储数据,都是以存储的数据为键,默认的object对象为值,来存储进内部map中,以此来实现set集合的不可重复性。根据HashMap的底层机制,我们可以知道,hashmap在获取key的时候,利用keyset来获取,确实是无序的。
属性解析
// 底层结构实现
private transient HashMap<E,Object> map;
// 与支持的Map中的对象相关联的虚拟值
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
方法解析
构造方法
/**
* 创建一个新的、空的set。
* 支持的HashMap实例采用默认容量和默认负载因子。
* 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<>();
}
/**
* 创建一个新的set集合,包含了指定集合中的元素。
* 创建的HashMap采用默认负载因子,元素初始大小,需要通过指定集合的元素除以负载因子后
* 再加上1,去和HashMap的默认大小进行比较,采取大的那个。
* 至于这里为什么要除以0.75f,再加上1,是因为HashMap有自动扩容机制,如果直接以指定集合
* 的元素个数大小和16去比较,就很可能出现一创建,后面第一次操作就要扩容的情况。
* 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));
// 将元素添加到map中,先调用继承的addAll方法,但在里面有回调了自己实现的add方法。
addAll(c);
}
/**
* 构造一个新的、空的set集合,指定了初始容量和负载因子。
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* the specified initial capacity and the specified load factor.
*
* @param initialCapacity the initial capacity of the hash map
* @param loadFactor the load factor of the hash map
* @throws IllegalArgumentException if the initial capacity is less
* than zero, or if the load factor is nonpositive
*/
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
/**
* 构造一个新的、空的set,指定了初始容量,负载因子采用默认值
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* the specified initial capacity and default load factor (0.75).
*
* @param initialCapacity the initial capacity of the hash table
* @throws IllegalArgumentException if the initial capacity is less
* than zero
*/
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
/**构造一个新的、空的链式的哈希集合。(该方法仅用于LinkedHashSet类)
* 指定了初始容量和负载因子。
* Constructs a new, empty linked hash set. (This package private
* constructor is only used by LinkedHashSet.) The backing
* HashMap instance is a LinkedHashMap with the specified initial
* capacity and the specified load factor.
*
* @param initialCapacity the initial capacity of the hash map
* @param loadFactor the load factor of the hash map
* @param dummy ignored (distinguishes this
* constructor from other int, float constructor.)
* @throws IllegalArgumentException if the initial capacity is less
* than zero, or if the load factor is nonpositive
*/
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
迭代器
/**
* 返回了一个该set元素的一个迭代器。元素无序返回。
* Returns an iterator over the elements in this set. The elements
* are returned in no particular order.
*
* @return an Iterator over the elements in this set
* @see ConcurrentModificationException
*/
public Iterator<E> iterator() {
// 实际返回的是map的key的迭代器。
return map.keySet().iterator();
}
从这里我们就可以很清晰的看出,HashSet的元素实际上是存储在map的key中的,所以迭代器也是从keySet()来获取的。
基础操作
/**
* 返回set中元素的数目
* Returns the number of elements in this set (its cardinality).
*
* @return the number of elements in this set (its cardinality)
*/
public int size() {
return map.size();
}
/**
* 返回set是否为空
* Returns <tt>true</tt> if this set contains no elements.
*
* @return <tt>true</tt> if this set contains no elements
*/
public boolean isEmpty() {
return map.isEmpty();
}
/**
* 判断set集合是否包含指定对象元素。
* 依赖于equals方法。
* 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增加一个键值对,增加的值作为键。
* 因为map的键是不重复的,所以应用到set中,就相当于set集合不可能有重复元素。
* 而值是采用静态变量PRESENT,其实没什么用,只是一个虚拟值。
* 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;
}
/**
* 移除指定元素。
* 这里调用map的remove方法,之后需要判断移除的元素是否为PRESENT,因为这样才能
* 判断到底原来的set中是否真的有这个元素。如果set中没有o这个元素,那么就是说map
* 中没有以o为键的键值对,那么调用remove方法,会返回null。只有返回了PRESENT,才
* 说明确实有这个元素。
* Removes the specified element from this set if it is present.
* More formally, removes an element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>,
* if this set contains such an element. Returns <tt>true</tt> if
* this set contained the element (or equivalently, if this set
* changed as a result of the call). (This set will not contain the
* element once the call returns.)
*
* @param o object to be removed from this set, if present
* @return <tt>true</tt> if the set contained the specified element
*/
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
从上面的基础操作代码中,我们可以看出,基本HashSet的操作,都是基于HashMap来实现的。