HashSet
HashSet 是一个没有重复元素的集合 。由HashMap实现,不保证元素的顺序,允许null 。
private transient HashMap<E,Object> map;
//定义一个静态的Object对象,来充当HashMap的value
private static final Object PRESENT = new Object();
public HashSet() {
map = new HashMap<>();
}
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
/**
* 不对外公开的一个构造方法(默认default修饰),底层构造的是LinkedHashMap,提供给LinkedHashSet使用。dummy无具体意义
*/
HashSet( int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor);
}
HashSet的其他方法,如add(),remove(),size(),都是调用了HashMap方法
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
public boolean contains(Object o) {
return map.containsKey(o);
}
LinkedHashSet
继承HashSet,没有重复元素,可以保持元素的插入顺序(LinkedHashMap可以维护插入顺序或访问顺序,LinkedHashSet只维护插入顺序)
构造方法:
public LinkedHashSet(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor, true);
}
public LinkedHashSet(int initialCapacity) {
super(initialCapacity, .75f, true);
}
public LinkedHashSet() {
super(16, .75f, true);
}
这三个构造方法都调用了HashSet类中 HashSet( int initialCapacity, float loadFactor, boolean dummy) 的构造方法。
HashSet( int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor);
}
public LinkedHashMap(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
accessOrder = false;
}
该方法中创建了一个LinkedHashMap对象,且accessOrder=false,即维护插入顺序。