1 Set
1.1 代码简要说明:
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1
and e2
such that e1.equals(e2)
, and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
译文:集合不包含复制的元素,更加正式的,Set中不包含成对的元素,像e1.equals(e2),至多一个null元素。正如它的名字一样,这个接口模型的数学Set抽象。
2 HashSet
2.1 说明:
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.
译文:实现Set接口,依靠Hashtable,他不保证迭代的顺序,特别的是,它不能保证数据保持不变,随着时间的推移。这个集合可以包含null值。存储结构实际为HashMap。
private transient HashMap<E,Object> map;
2.2 重要方法:
构造函数本质均为实现HashMap集合,但有一个例外,创建一个LinkedHashMap对象
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
HashSet集合判断两个元素相等的标准是两个对象equals方法比较相等,并且两个对象的hashCode的返回值也相等。当存入一个元素时,会调用该对象的hashCode方法得到该对象的hashCode值,然后根据HashCode值决定该对象在HashSet中的存储位置。
如果需要重写equals和hashCode()方法,这需要满足如下规则:如果equals返回true,则hashCode的值也需要相同。
3 TreeSet
3.1 说明
A {@link NavigableSet} implementation based on a {@link TreeMap}.The elements are ordered using their {@linkplain Comparable natural ordering}, or by a {@link Comparator} provided at set creationtime, depending on which constructor is used.
TreeSet基于TreeMap集合,元素根据比较元素进行排序,否则根据创建时间,取决于构造器创建时间。
3.2 存储结构:
/**
* The backing map.
*/
private transient NavigableMap<E,Object> m;
3.3重要方法:
构造方法可传TreeMap SortedSet对象或其子类对应的集合
public boolean addAll(Collection<? extends E> c) {
// Use linear-time version if applicable
if (m.size()==0 && c.size() > 0 &&
c instanceof SortedSet &&
m instanceof TreeMap) {
SortedSet<? extends E> set = (SortedSet<? extends E>) c;
TreeMap<E,Object> map = (TreeMap<E, Object>) m;
Comparator<? super E> cc = (Comparator<? super E>) set.comparator();
Comparator<? super E> mc = map.comparator();
if (cc==mc || (cc != null && cc.equals(mc))) {
map.addAllForTreeSet(set, PRESENT);
return true;
}
}
return super.addAll(c);
}