注:以下源码基于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<E,Object> 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<? 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); }
方法几乎没什么好讲的,全都是直接调用HashMap的方法。
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<E,Object> m; // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object(); TreeSet(NavigableMap<E,Object> m) { this.m = m; } public TreeSet() {//内部是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); }
这里需要注意的是,由于TreeSet不支持null键,故而TreeSet也是不支持null键的。这要跟HashSet区分开来。
public boolean add(E e) { return m.put(e, PRESENT)==null; } public boolean remove(Object o) { return m.remove(o)==PRESENT; }
Set集合实际应用的很少,大家知道原理即可。
时间: 2024-10-22 16:32:43