Set概述
Set幾乎都是內(nèi)部用一個(gè)Map來實(shí)現(xiàn), 因?yàn)镸ap里的KeySet就是一個(gè)Set棍现,而value是假值庙洼,全部使用同一個(gè)Object培己。Set的特征也繼承了那些內(nèi)部Map實(shí)現(xiàn)的特征依溯。
HashSet
- 1 以jdk7為準(zhǔn)進(jìn)行說明
package java.util;
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();
public HashSet() {
map = new HashMap<>();
}
//其余省略
}
- 2 HashSet是基于HashMap來實(shí)現(xiàn)的,操作很簡(jiǎn)單葡粒,更像是對(duì)HashMap做了一次“封裝”份殿,而且只使用了HashMap的key來實(shí)現(xiàn)各種特性,而HashMap的value始終都是PRESENT嗽交。
- 3 HashSet不允許重復(fù)(HashMap的key不允許重復(fù)卿嘲,如果出現(xiàn)重復(fù)就覆蓋),允許null值夫壁,非線程安全拾枣。
- 4 主要的幾個(gè)方法如下
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();
}
- 5 HashSet有4個(gè)共有的構(gòu)造函數(shù):
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);
}
LinkedHashSet
- 1 以jdk7為準(zhǔn)進(jìn)行說明
package java.util;
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);
}
}
- 2 整個(gè)LinkedHashSet的四個(gè)構(gòu)造函數(shù)全部都是調(diào)用了HashSet中的這個(gè)包級(jí)私有的構(gòu)造函數(shù)(構(gòu)造函數(shù)中的dummy就是標(biāo)記,無實(shí)用盒让,為了實(shí)現(xiàn)方法的重載而已)梅肤,也就是說LinkedHashSet就是基于LinkedHashMap實(shí)現(xiàn)的。
TreeSet
- 1 以jdk7為準(zhǔn)進(jìn)行說明
package java.util;
public class TreeSet<E> extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, java.io.Serializable
{
private transient NavigableMap<E,Object> m;
private static final Object PRESENT = new Object();
public TreeSet() {
this(new TreeMap<E,Object>());
}
public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<>(comparator));
}
public TreeSet(Collection<? extends E> c) {
this();
addAll(c);
}
public TreeSet(SortedSet<E> s) {
this(s.comparator());
addAll(s);
}
//其余省略
}
- 2 TreeSet的內(nèi)部基于TreeMap實(shí)現(xiàn)邑茄,同樣value永遠(yuǎn)為PRESENT.