HashSet
HashSet是一种类似数组/list的线性的数据结构。
This class implements the Set interface, backed by a hash table (actually a HashMap instance).
It makes no guarantees as to the iteration order of the set;
in particular, it does not guarantee that the order will remain constant over time.
This class permits the null element.
HashSet是基于HashMap的数据结构,内部是使用HashMap来存储数据的。内部无序且元素不可重复。
看一眼无参构造器:
/**
* Constructs a new, empty set; the backing HashMap instance has
* default initial capacity (16) and load factor (0.75).
*/
public HashSet() {
map = new HashMap<>();
}
add:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
// PRESENT
private static final Object PRESENT = new Object();
add方法就是把元素作为key put进map里,value统一使用一个Object对象。
迭代,实际上就是迭代HashMap的key了,看一下源码实现:
public Iterator iterator() {
return map.keySet().iterator();
}
HashSet只是浅层封装了HashMap,没有什么其他的东西。
LinkedHashSet
LinkedHashSet继承自HashSet,内部实现是LinkedHashMap;和HashSet的区别也就是有序。
/**
* Constructs a new, empty linked hash set with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity of the linked hash set
* @param loadFactor the load factor of the linked hash set
* @throws IllegalArgumentException if the initial capacity is less
* than zero, or if the load factor is nonpositive
*/
public LinkedHashSet(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor, true);
}
父类对应的构造器:
/**
* Constructs a new, empty linked hash set. (This package private
* constructor is only used by LinkedHashSet.) The backing
* HashMap instance is a LinkedHashMap with the specified initial
* capacity and the specified load factor.
*
* @param initialCapacity the initial capacity of the hash map
* @param loadFactor the load factor of the hash map
* @param dummy ignored (distinguishes this
* constructor from other int, float constructor.)
* @throws IllegalArgumentException if the initial capacity is less
* than zero, or if the load factor is nonpositive
*/
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
TreeSet
不出意外的话,TreeSet是使用TreeMap来实现的。
看一下构造器:
/**
* Constructs a new, empty tree set, sorted according to the
* natural ordering of its elements. All elements inserted into
* the set must implement the {@link Comparable} interface.
* Furthermore, all such elements must be mutually
* comparable: {@code e1.compareTo(e2)} must not throw a
* {@code ClassCastException} for any elements {@code e1} and
* {@code e2} in the set. If the user attempts to add an element
* to the set that violates this constraint (for example, the user
* attempts to add a string element to a set whose elements are
* integers), the {@code add} call will throw a
* {@code ClassCastException}.
*/
public TreeSet() {
this(new TreeMap());
}