之前对ArrayList和HashMap进行了源码解析,现在来看看HashSet的源码。
创建
Set<String> set = new HashSet<>();
这是常用的创建方法,来看看源码。
/**
* 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来存储元素的。可以看到注释上写着默认下HashSet的容量为16,加载因子为0.75。当然也可以自己设置一个初始容量,源码如下。
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
添加元素
set.add("str");
这是基本的使用方法,和ArrayList不同,HashSet的元素值是不能重复的,看看源码是怎么实现的。
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
实现方法非常简单,add方法传入的value就是HashMap的key,利用key不能重复的特点来实现,非常巧妙。至于HashMap的value用一个Object对象占着就行了。为什么不直接设置为null?后面会讲解。
删除元素
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
它是利用HashMap的remove方法来实现的,这个时候PRESENT就派上用场了。想想看,如果之前没有添加元素A,而现在要移除它,那么map.remove方法返回的就是个空值,通过和PRESENT作对比就能知道A之前并没有添加到这个HashSet中。
如果元素A添加到HashSet里面了,再移除时,map.remove方法返回的就是PRESENT,这就说明之前元素A是在HashSet里面的。