HashSet
类关系
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{}
主要参数
private transient HashMap<E,Object> map;
private static final Object PRESENT = new Object();
构造方法
构造方法在底层会创建不同的Map,前几个是HashMap ,最后一个是LinkedHashMap ,这个主要是给LinkedHashSet 提供的
public HashSet() {
map = new HashMap<>();
}
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);
}
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
基础方法
add()
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
remove()
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
LinkedHashSet
LinkedHashSet 类的内容很简单,就这么几行,LinkedHash 和HashSet 的相比,不但元素去重,而且还能保持元素顺序,那么底层就是借助LinkedHashMap
那么LinkedHashMap 如何来的,就在构造方法中,LinkedHashSet 调用的都是父类HashSet 3个参数的构造方法,这样通过上面就可以看到,直接创建了LinkedHashMap
public class LinkedHashSet<E>
extends HashSet<E>
implements Set<E>, Cloneable, java.io.Serializable {
private static final long serialVersionUID = -2851667679971038690L;
public LinkedHashSet(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor, true);
}
public LinkedHashSet(int initialCapacity) {
super(initialCapacity, .75f, true);
}
public LinkedHashSet() {
super(16, .75f, true);
}
public LinkedHashSet(Collection<? extends E> c) {
super(Math.max(2*c.size(), 11), .75f, true);
addAll(c);
}
@Override
public Spliterator<E> spliterator() {
return Spliterators.spliterator(this, Spliterator.DISTINCT | Spliterator.ORDERED);
}
}
|