一、Set核心实现类
如上图,Set和List是Collection接口的两个分支,比较重要且频繁使用的有HashSet、LinkedHashSet和TreeSet。比较鲜明的特点就是整个Set以及它的实现类中,集合中的元素是不能重复的,还有一个比较有意思的点在于,Set中的主要实现类都是对Map实现类的封装,例如HashSet封装了HashMap,LinkedHashSet封装了LinkedHashMap,TreeSet封装了TreeMap。查看源码,不难发现,HashSet中提供的构造方法,实际初始化的是一个HashMap对象。其他两个实现类亦是如此。
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
public HashSet() {
map = new HashMap<>();
}
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
}
//TreeSet构造方法
public TreeSet() {
this(new TreeMap<E,Object>());
}
public TreeSet(Comparator<