读注释
This class implements the {@code Set} interface, backed by a hash table (actually a {@code 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 {@code null} element.
HashSet实质上就是HashMap实例,它的value全是指定为Object,允许一个null元素。其他的特性与HashMap一致,可以去看看HashMap。
读源码
构造函数
public HashSet() {
map = new HashMap<>();
}
通过构造函数可以看出其内部就是一个hashMap实例,所有的操作都是通过map来操作
常用函数
public int size() {
return map.size();
}
public boolean isEmpty() {
return map.isEmpty();
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
此处省略若干方法…,都是调用HashMap的方法,还是去看HashMap来的实在。