Java8 HashSet原理
概述
在官方文档中是这样描述HashSet的:
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.
Note that this implementation is not synchronized.
HashSet实现了Set集合,内部直接由HashMap进行实现,即通过数组+链表+红黑树来存储数据,允许null,不保证有序(比如插入的顺序)、也不保证顺序不随时间变化,同时,HashSet是线程不安全的。HashSet天生就是为了提高查找效率的。
数据结构
由于HashSet的内部直接由HashMap直接实现的,所以HashSet的数据结构跟HashMap一样,也是通过数组+链表+红黑树来实现的。
源码实现
1.类的继承关系
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
HashSet继承了AbstractSet,并实现了Set,Cloneable,Serializable接口。其中,Set接口,内部不允许出现重复的元素(A collection that contains no duplicate elements)。
2.基本成员变量
static final long serialVersionUID = -5024744406713321676L;
// 用来存放HashSet中的数据
private transient HashMap<E,Object> map;
// 因为使用到的HashMap的key必须唯一,所以我们将数据存到key中,
// 而所有的value我们就可以是一个内部的不可以修改的静态对象PRESENT 即可
private static final Object PRESENT = new Object();
这个时候,我们好奇的一点来了。我们知道HashMap是允许key、value为null的,那么在HashSet里面为什么不用null作为value的值呢?这个时候我们可能要看看相关的源码实现了。以HashSet的remove方法为例:
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
从上面代码我们发现如果PRESENT为null,hashset存储的value也是为null。我们知道HashMap.remove(o)如果找到o并将其删除,则返回value,否则返回null。那么这个时候,map.remove(o)无论删除与否等会返回null,将不能判断是否成功删除了这个key-value对象。
3.构造函数
public HashSet() {
map = new HashMap<>();
}
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
从上面的源代码中,我们可以看见除了最后一个构造函数,其他的构造函数里面实际上是new了一个HashMap对象,最后一个是给HashSet的子类LinkedHashSet的构造函数使用。
4.基本方法实现
public int size() {
return map.size();
}
public boolean isEmpty() {
return map.isEmpty();
}
public boolean contains(Object o) {
return map.containsKey(o);
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
public void clear() {
map.clear();
}
从上面代码中,我们可以知道HashSet的基本方法实现实际上调用的都是HashMap的方法。