HashSet的底层是HashMap
原码:
/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* default initial capacity (16) and load factor (0.75).
* 创建一个新的HashSet时,默认初始容量(16)和负载系数(0.75)。
*/
public HashSet() {
map = new HashMap<>();
}
为什么add方法只添加一个参数?
原码:
private static final Object PRESENT = new Object();
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
add进去的是Map的Key值,Set不关心value值,value值是一个PRESENT的常量值