//HashSet的实现依赖于HashMap
private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map
//申请Object类型的PRESENT作为HashMap中的value值
private static final Object PRESENT = new Object();
2、构造方法
//无参构造函数,申请一个HashMap
public HashSet() {
map = new HashMap<>();
}
//将指定的集合c转换为HashSet
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);
}
//指定初始化容量,其底层都是调用HashMap的构造函数
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
3、重要方法
/*在以下的一些增删改查中无一例外的都是调用HashMap的属性进行相关操作,
我们传入的参数e作为key-value中的key,而value值统一都是使用Object类型的PRESENT充当,并无实际含义
*/
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();
}