该类继承了AbstractSet
内部实现其实是基于HashMap(也有可能是LinkedHashSet)的,数据值作为Map的key;允许null值;
private transient HashMap<E, Object> map;
private static final Object PRESENT = new Object();
public HashSet() {//default initial capacity (16) and load factor (0.75)
map = new HashMap<E, Object>();
}
基本的操作都是基于HashMap的:
public Iterator<E> iterator() {
return map.keySet().iterator();
}
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();
}