問題
(1)TreeSet真的是使用TreeMap來存儲元素的嗎?
(2)TreeSet是有序的嗎?
(3)TreeSet和LinkedHashSet有何不同?
簡介
TreeSet底層是採用TreeMap實現的一種Set,所以它是有序的,同樣也是非線程安全的。既然是有序,那麼它是靠什麼來維持順序的呢,回憶一下TreeMap中是怎麼比較兩個key大小的,是通過一個比較器Comparator對不對,不過遺憾的是,今天仍然不會講Comparator,但是需要明白的是TreeSet要實現信息也必須依靠於Comparator接口。 關於Set,在前面我們講過一個HashSet,是不是想起了什麼,Set和Map在java中是很神奇的一對,他們都是一對對出現的,就像雙胞胎。來看一下這兩個容器(是的,容器,我們還是要正規一些,什麼雙胞胎嘛),Map有HashMap,LinkedHashMap還有TreeMap,那Set呢有HashSet,LinkedHashSet還有TreeSet,很一致!。TreeSet和TreeMap一樣都是基於紅黑樹實現,明白了前面的TreeMap原理,TreeSet我們就更好理解了。
繼承體系
TreeSet實現了Cloneable,可以被克隆。
TreeSet實現了Serializable,可以被序列化。
TreeSet實現了NavigableSet,NavigableSet接口繼承自SortedSet接口。它的行爲類似於SortedSet,除了SortedSet的排序機制之外我們還有導航方法。例如,與SortedSet中定義的順序相比,NavigableSet接口可以以相反的順序導航集合。
源碼分析
經過前面我們學習HashSet和LinkedHashSet,基本上已經掌握了Set實現的套路了。
所以,也不廢話了,直接上源碼:
package java.util;
// TreeSet實現了NavigableSet接口,所以它是有序的
public class TreeSet<E> extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, java.io.Serializable
{
// TreeSet底層用的是NavigableMap來存儲數據,而不是直接使用TreeMap
// 我們知道TreeMap是實現類NavigableMap接口的,所以TreeSet默認構造了
// 一個TreeMap來作爲NavigableMap的一個實現類,提供給TreeSet存儲數據
// 注意它不一定就是TreeMap
private transient NavigableMap<E,Object> m;
// 虛擬元素, 用來作爲value存儲在map中
private static final Object PRESENT = new Object();
// 直接使用傳進來的NavigableMap存儲元素
// 這裏不是深拷貝,如果外面的map有增刪元素也會反映到這裏
// 而且, 這個方法不是public的, 說明只能給同包使用
TreeSet(NavigableMap<E,Object> m) {
this.m = m;
}
// 使用TreeMap初始化
public TreeSet() {
this(new TreeMap<E,Object>());
}
// 使用帶comparator的TreeMap初始化
public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<>(comparator));
}
// 將集合c中的所有元素添加的TreeSet中
public TreeSet(Collection<? extends E> c) {
this();
addAll(c);
}
// 將SortedSet中的所有元素添加到TreeSet中
public TreeSet(SortedSet<E> s) {
this(s.comparator());
addAll(s);
}
// 迭代器
public Iterator<E> iterator() {
return m.navigableKeySet().iterator();
}
// 逆序迭代器
public Iterator<E> descendingIterator() {
return m.descendingKeySet().iterator();
}
// 以逆序返回一個新的TreeSet
public NavigableSet<E> descendingSet() {
return new TreeSet<>(m.descendingMap());
}
// 元素個數
public int size() {
return m.size();
}
// 判斷是否爲空
public boolean isEmpty() {
return m.isEmpty();
}
// 判斷是否包含某元素
public boolean contains(Object o) {
return m.containsKey(o);
}
// 添加元素, 調用map的put()方法, value爲PRESENT
public boolean add(E e) {
return m.put(e, PRESENT)==null;
}
// 刪除元素
public boolean remove(Object o) {
return m.remove(o)==PRESENT;
}
// 清空所有元素
public void clear() {
m.clear();
}
// 添加集合c中的所有元素
public boolean addAll(Collection<? extends E> c) {
// 滿足一定條件時直接調用TreeMap的addAllForTreeSet()方法添加元素
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<?> cc = set.comparator();
Comparator<? super E> mc = map.comparator();
if (cc==mc || (cc != null && cc.equals(mc))) {
map.addAllForTreeSet(set, PRESENT);
return true;
}
}
// 不滿足上述條件, 調用父類的addAll()通過遍歷的方式一個一個地添加元素
return super.addAll(c);
}
// 子set(NavigableSet中的方法)
public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
E toElement, boolean toInclusive) {
return new TreeSet<>(m.subMap(fromElement, fromInclusive,
toElement, toInclusive));
}
// 頭set(NavigableSet中的方法)
public NavigableSet<E> headSet(E toElement, boolean inclusive) {
return new TreeSet<>(m.headMap(toElement, inclusive));
}
// 尾set(NavigableSet中的方法)
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return new TreeSet<>(m.tailMap(fromElement, inclusive));
}
// 子set(SortedSet接口中的方法)
public SortedSet<E> subSet(E fromElement, E toElement) {
return subSet(fromElement, true, toElement, false);
}
// 頭set(SortedSet接口中的方法)
public SortedSet<E> headSet(E toElement) {
return headSet(toElement, false);
}
// 尾set(SortedSet接口中的方法)
public SortedSet<E> tailSet(E fromElement) {
return tailSet(fromElement, true);
}
// 比較器
public Comparator<? super E> comparator() {
return m.comparator();
}
// 返回最小的元素
public E first() {
return m.firstKey();
}
// 返回最大的元素
public E last() {
return m.lastKey();
}
// 返回小於e的最大的元素
public E lower(E e) {
return m.lowerKey(e);
}
// 返回小於等於e的最大的元素
public E floor(E e) {
return m.floorKey(e);
}
// 返回大於等於e的最小的元素
public E ceiling(E e) {
return m.ceilingKey(e);
}
// 返回大於e的最小的元素
public E higher(E e) {
return m.higherKey(e);
}
// 彈出最小的元素
public E pollFirst() {
Map.Entry<E,?> e = m.pollFirstEntry();
return (e == null) ? null : e.getKey();
}
public E pollLast() {
Map.Entry<E,?> e = m.pollLastEntry();
return (e == null) ? null : e.getKey();
}
// 克隆方法
@SuppressWarnings("unchecked")
public Object clone() {
TreeSet<E> clone;
try {
clone = (TreeSet<E>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
clone.m = new TreeMap<>(m);
return clone;
}
// 序列化寫出方法
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden stuff
s.defaultWriteObject();
// Write out Comparator
s.writeObject(m.comparator());
// Write out size
s.writeInt(m.size());
// Write out all elements in the proper order.
for (E e : m.keySet())
s.writeObject(e);
}
// 序列化寫入方法
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden stuff
s.defaultReadObject();
// Read in Comparator
@SuppressWarnings("unchecked")
Comparator<? super E> c = (Comparator<? super E>) s.readObject();
// Create backing TreeMap
TreeMap<E,Object> tm = new TreeMap<>(c);
m = tm;
// Read in size
int size = s.readInt();
tm.readTreeSet(size, s, PRESENT);
}
// 可分割的迭代器
public Spliterator<E> spliterator() {
return TreeMap.keySpliteratorFor(m);
}
// 序列化id
private static final long serialVersionUID = -2479143000061671589L;
}
源碼比較簡單,基本都是調用map相應的方法。
NavigableMap定義
public interface NavigableMap<K,V> extends SortedMap<K,V> {
// 獲取小於指定key的第一個節點對象
Map.Entry<K,V> lowerEntry(K key);
// 獲取小於指定key的第一個key
K lowerKey(K key);
// 獲取小於或等於指定key的第一個節點對象
Map.Entry<K,V> floorEntry(K key);
// 獲取小於或等於指定key的第一個key
K floorKey(K key);
// 獲取大於或等於指定key的第一個節點對象
Map.Entry<K,V> ceilingEntry(K key);
// 獲取大於或等於指定key的第一個key
K ceilingKey(K key);
// 獲取大於指定key的第一個節點對象
Map.Entry<K,V> higherEntry(K key);
// 獲取大於指定key的第一個key
K higherKey(K key);
// 獲取Map的第一個(最小的)節點對象
Map.Entry<K,V> firstEntry();
// 獲取Map的最後一個(最大的)節點對象
Map.Entry<K,V> lastEntry();
// 獲取Map的第一個節點對象,並從Map中移除改節點
Map.Entry<K,V> pollFirstEntry();
// 獲取Map的最後一個節點對象,並從Map中移除改節點
Map.Entry<K,V> pollLastEntry();
// 返回當前Map的逆序Map集合
NavigableMap<K,V> descendingMap();
// 返回當前Map中包含的所有key的Set集合
NavigableSet<K> navigableKeySet();
// 返回當前map的逆序Set集合,Set由key組成
NavigableSet<K> descendingKeySet();
// 返回當前map中介於fromKey(fromInclusive是否包含)和toKey(toInclusive是否包含) 之間的子map
NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
K toKey, boolean toInclusive);
// 返回介於map第一個元素到toKey(inInclusive是否包含)之間的子map
NavigableMap<K,V> headMap(K toKey, boolean inclusive);
// 返回當前map中介於fromKey(inInclusive是否包含) 到map最後一個元素之間的子map
NavigableMap<K,V> tailMap(K fromKey, boolean inclusive);
// 返回當前map中介於fromKey(包含)和toKey(不包含)之間的子map
SortedMap<K,V> subMap(K fromKey, K toKey);
// 返回介於map第一個元素到toKey(不包含)之間的子map
SortedMap<K,V> headMap(K toKey);
// 返回當前map中介於fromKey(包含) 到map最後一個元素之間的子map
SortedMap<K,V> tailMap(K fromKey);
}
從NavigableMap接口的方法中可以看出,基本上定義的都是一些邊界的搜索和查詢。當然這些方法是不能實現Set的,再看下NavigableMap的定義,NavigableMap繼承了SortedMap接口,而SortedMap繼承了Map接口,所以NavigableMap是在Map接口的基礎上豐富了這些對於邊界查詢的方法,但是不妨礙你只是用其中Map中自身的功能。
總結
(1)TreeSet底層使用NavigableMap存儲元素;
(2)TreeSet是有序的;
(3)TreeSet是非線程安全的;
(4)TreeSet實現了NavigableSet接口,而NavigableSet繼承自SortedSet接口;
(5)TreeSet實現了SortedSet接口;
彩蛋
(1)通過之前的學習,我們知道TreeSet和LinkedHashSet都是有序的,那它們有何不同?
LinkedHashSet並沒有實現SortedSet接口,它的有序性主要依賴於LinkedHashMap的有序性,所以它的有序性是指按照插入順序保證的有序性;
而TreeSet實現了SortedSet接口,它的有序性主要依賴於NavigableMap的有序性,而NavigableMap又繼承自SortedMap,這個接口的有序性是指按照key的自然排序保證的有序性,而key的自然排序又有兩種實現方式,一種是key實現Comparable接口,一種是構造方法傳入Comparator比較器。
(2)TreeSet裏面真的是使用TreeMap來存儲元素的嗎?
通過源碼分析我們知道TreeSet裏面實際上是使用的NavigableMap來存儲元素,雖然大部分時候這個map確實是TreeMap,但不是所有時候都是TreeMap。
因爲有一個構造方法是TreeSet(NavigableMap<E,Object> m)
,而且這是一個非public方法,通過調用關係我們可以發現這個構造方法都是在自己類中使用的,比如下面這個:
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return new TreeSet<>(m.tailMap(fromElement, inclusive));
}
而這個m我們姑且認爲它是TreeMap,也就是調用TreeMap的tailMap()方法:
public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
return new AscendingSubMap<>(this,
false, fromKey, inclusive,
true, null, true);
}
可以看到,返回的是AscendingSubMap對象,這個類的繼承鏈是怎麼樣的呢?
可以看到,這個類並沒有繼承TreeMap,不過通過源碼分析也可以看出來這個類是組合了TreeMap,也算和TreeMap有點關係,只是不是繼承關係。
所以,TreeSet的底層不完全是使用TreeMap來實現的,更準確地說,應該是NavigableMap。