注:下面源代码基于jdk1.7.0_11
Set集合事实上是对Map集合的封装,Map集合存储的是键值对,那么我们将值隐藏,不向外界暴露,这样就形成了Set集合。
相应Map集合的两个非常重要的实现HashMap(基于哈希表),TreeMap(基于红黑树),Set集合也相应了两个类HashSet和TreeSet。因为之前花非常多篇幅介绍了HashMap和TreeMap,在此将不再介绍事实上现细节。
简单分析下HashSet:
static final long serialVersionUID = -5024744406713321676L; private transient HashMap方法差点儿没什么好讲的,全都是直接调用HashMap的方法。map;//内部封装了HashMap // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object();//值固定为new Object /*构造器照搬HashMap的*/ public HashSet() { map = new HashMap<>(); } public HashSet(Collection 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); }
public boolean add(E e) { return map.put(e, PRESENT)==null; }add方法插入的值为固定的new Object(). HashMap支持null键,HashSet自然也是支持的 。
public boolean remove(Object o) { return map.remove(o)==PRESENT; }TreeSet:
private transient NavigableMap这里须要注意的是,因为TreeSet不支持null键,故而TreeSet也是不支持null键的。这要跟HashSet区分开来。m; // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object(); TreeSet(NavigableMap m) { this.m = m; } public TreeSet() {//内部是TreeSet this(new TreeMap ()); } public TreeSet(Comparator comparator) { this(new TreeMap<>(comparator)); } public TreeSet(Collection c) { this(); addAll(c); } public TreeSet(SortedSet s) { this(s.comparator()); addAll(s); }
public boolean add(E e) { return m.put(e, PRESENT)==null; } public boolean remove(Object o) { return m.remove(o)==PRESENT; }Set集合实际应用的非常少,大家知道原理就可以。