TreeMap同樣屬於Map集合中的一員,但是它沒有用到散列表和鏈表這些數據結構,它只使用了紅黑樹這一數據結構,可以直接在紅黑樹中進行增刪改查操作。我們首先回顧一下Map集合的家族成員:
可以看出TreeMap是和HashMap並列的,而HashMap中的鍵值對是無序的,TreeMap中的鍵值對是按照一定的順序進行排序的。
接下來繼續看其繼承結構:
public class TreeMap<K,V> extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
我們在繼承體系中看到了一個陌生的接口“NavigableMap”,這個接口有什麼用呢?
public interface NavigableMap<K,V> extends SortedMap<K,V>{
Map.Entry<K,V> lowerEntry(K key);
//獲得小於key值的最大Entry
K lowerKey(K key);
//獲得小於key值的最大Key
Map.Entry<K,V> floorEntry(K key);
//獲得不大於key值的最大Entry
K floorKey(K key);
//獲得不大於key值的最大Key
Map.Entry<K,V> ceilingEntry(K key);
//獲得不小於key值的最小Entry
K ceilingKey(K key);
//獲得不小於key值的最小Key
Map.Entry<K,V> higherEntry(K key);
//獲得大於key值的最小Entry
K higherKey(K key);
//獲得大於key值的最小key
Map.Entry<K,V> firstEntry();
//獲得第一個Entry
Map.Entry<K,V> lastEntry();
//獲得最後一個Entry
Map.Entry<K,V> pollFirstEntry();
//獲得並刪除第一個Entry
Map.Entry<K,V> pollLastEntry();
//獲得並刪除最後一個Entry
NavigableMap<K,V> descendingMap();
//獲得逆序的Map
NavigableSet<K> navigableKeySet();
//獲得順序的key值集合
NavigableSet<K> descendingKeySet();
//獲得逆序的key值集合
NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
K toKey, boolean toInclusive);
//獲得子Map
NavigableMap<K,V> headMap(K toKey, boolean inclusive);
//獲得首部子Map
NavigableMap<K,V> tailMap(K fromKey, boolean inclusive);
//獲得尾部子Map
SortedMap<K,V> subMap(K fromKey, K toKey);
//獲得SortedMap類型的子Map
SortedMap<K,V> headMap(K toKey);
//獲得SotredMap類型的首部子Map
SortedMap<K,V> tailMap(K fromKey);
//獲得SortedMap類型的尾部子Map
}
public interface SortedMap<K,V> extends Map<K,V> {
Comparator<? super K> comparator();
//比較器
SortedMap<K,V> subMap(K fromKey, K toKey);
//獲得子Map
SortedMap<K,V> headMap(K toKey);
//獲得首部子Map
SortedMap<K,V> tailMap(K fromKey);
//獲得尾部子Map
K firstKey();
//獲取第一個Key值
K lastKey();
//獲取最後一個key值
Set<K> keySet();
//獲得所有的Key組成的集合
Collection<V> values();
//獲得所有的value組成的集合
Set<Map.Entry<K, V>> entrySet();
//獲得所有的Entry組成的集合
}
由上面源碼可知,SortedMap繼承自Map接口,並且新增了比較器方法、獲取首尾key方法、獲得子Map方法與獲得key、value、Entry集合的方法,而NavigableMap接口除了繼承SortedMap類中的方法之外,還新增了一系列獲取邊界的key和Entry結點的方法。總之,就是除了有Map接口的方法之外,還新增了一個排序的功能。
接下來看看它的成員變量:
private final Comparator<? super K> comparator;
//自定義比較器
private transient Entry<K,V> root;
//根節點,不可序列化
private transient int size = 0;
//結點個數,不可序列化
private transient int modCount = 0;
//修改次數,不可序列化
static final class Entry<K,V> implements Map.Entry<K,V>{
//紅黑樹結點類
//成員變量
K key;//key值
V value;//value值
Entry<K,V> left;//左孩子
Entry<K,V> right;//右孩子
Entry<K,V> parent;//父結點
boolean color = BLACK;//默認黑色結點
}
由上可知,TreeMap的底層數據結構就是紅黑樹,並可以通過自己設置比較器來構建相應的紅黑樹。
接下來研究一下其構造器:
public TreeMap(){
//構造器1,不定義比較器
comparator = null;
}
public TreeMap(Comparator<? super K> comparator){
//構造器2,傳入構造器,根據構造器建樹
this.comparator = comparator;
}
public TreeMap(Map<? extends K, ? extends V> m){
//構造器3,傳入普通Map類型的容器,將容器中的鍵值對加入到樹中
comparator = null;
//將比較器設置爲Null
putAll(m);
}
public TreeMap(SortedMap<K, ? extends V> m){
//構造器4,傳入的是一個排序的Map類型容器,將容器中的鍵值對按照順序
//加入到樹中
comparator = m.comparator();
//將m的比較器設置成本類的比較器
try{
//使用迭代的方法將m的鍵值對複製到新的TreeMap的容器中
buildFromSorted(m.size(), m.entrySet().iterator(),null,null)
}catch(java.io.IOException cannotHappen){
}catch(ClassNotFoundException cannotHappen){
}
}
由上可知,TreeMap有四個構造器,當參數爲空時,則直接將比較器設置爲空,加入鍵值對構造紅黑樹時就利用鍵自己的比較器進行比較;當參數爲比較器時,則將比較器設置爲傳入的比較器,加入鍵值對構造紅黑樹時就採用傳入的比較器;當參數爲Map集合時,就直接將比較器置空,再將map中的鍵值對依次插入到紅黑樹中;當參數爲SortedMap集合時,則獲取其比較器作爲自己的比較器,再將其鍵值對依次插入到紅黑樹中。
下面再來看看常用方法:
1.put
public V put(K key, V value){
//將一個鍵值對放入紅黑樹中
Entry<K,V> t = root;
//獲取紅黑樹的根
if(t == null){
//如果根爲空,則說明紅黑樹中沒有結點
compare(key,key);//類型驗證
root = new Entry<>(key, value, null);
//新建結點作爲根
size = 1;
//結點數量設置爲1
modCount++;
//修改次數
return null;
//插入成功則返回null
}
int cmp;
//標記,記錄新節點應該插在哪裏或者尋找插入點時下一次向什麼方向尋找
Entry<K,V> parent;
Comparator<? super K> cpr = comparator;
//獲得比較器
if(cpr != null){
//如果比較器不爲空,則用TreeMap中的比較器進行比較
do{
parent = t;
//將當前結點作爲父結點
cmp = cpr.compare(key, t.key);
//獲得比較結果
if(cmp < 0)
//如果傳入的key值比當前結點的key值小
t = t.left;
//則向其左子樹下找
else if(cmp > 0)
//如果傳入key值比當前結點的key值大
t = t.right;
//則向其右子樹下找
else
return t.setValue(value);
//如果相等,則將該結點的value值設置爲傳進來的value值
//從此處可以看出其和HashMap的不同,key值不允許有相同的
}while(t != null);
}
else{
//否則表示比較器爲空,用key類自己的比較方式進行比較
if(key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>)key;
//對傳進來的key進行強制類型轉換
do{
//進行比較,尋找插入點
parent = t;
cmp = k.compareTo(t.key);
if(cmp < 0)
t = t.left;
if(cmp > 0)
t = t.right;
else
return t.setValue(value);
}while(t != null);
}
//上面爲尋找插入點,下面開始正式插入
Entry<K,V> e = new Entry<>(key,value,parent);
//新建結點
if(cmp < 0)
//如果cmp小於零,則表示將e插入其父結點的左孩子處
parent.left = e;
else
parent.right = e;
//否則將e插入其父節點的右孩子處
fixAfterInsertion(e);
//插入後的調整,類似HashMap中的balanceInsertion方法
size++;
//結點數目加一
modCount++;
//修改次數加一
return null;
//插入成功,返回Null
}
插入操作即直接在紅黑樹中操作,先找到需要插入的位置,如果該位置中已經有鍵值對了,則將該鍵值對更新成傳進去的value值並返回新的value值,否則直接將鍵值對插入並且開始調整紅黑樹。
2.get
public V get(Object key){
//根據key尋找相應鍵值對,如果沒找到返回null,
//找到了則返回key對應的value值
Entry<K,V> p = getEntry(key);
return (p == null ? null : p.value);
}
final Entry<K,V> getEntry(Object key){
//根據key值獲得鍵值對
if(comparator != null)
//如果比較器不爲空,則調用使用比較器的方法
return getEntryUsingComparator(key);
if(key == null)
//如果key值爲空,則拋出空指針異常
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>)key;
//如果沒有自定義比較器,則按照key值的比較方法進行比較
Entry<K,V> p = root;
//首先獲取紅黑樹的根
while(p != null){
//向下尋找,深度遍歷
int cmp = k.compareTo(p.key);
if(cmp < 0)
p = p.left;
else if(cmp > 0)
p = p.right;
else
return p;
}
return null;
}
get方法即首先判斷有沒有比較器,如果沒有比較器則按照key值自己的比較器進行比較,尋找對應的紅黑樹結點並返回其value值,如果value值爲空或者沒有找到對應的鍵值對時則返回null。
3.remove
public V remove(Object key){
//根據傳入的key值刪除對應的鍵值對
Entry<K,V> p = getEntry(key);
//先找到該鍵值對
if(p == null)
return null;
//如果找不到,則返回Null
V oldValue = p.value;
//如果找到該結點,則先得到其value值
deleteEnrty(p);
//刪除該結點
return oldValue;
//返回被刪除結點的value值
}
remove方法首先通過key獲得相應的結點,如果找不到結點則返回null,否則先將結點的value值取出,再將結點刪除,最後返回被刪除結點的value值。
4.獲得邊界結點
public Map.Entry<K,V> firstEntry(){
//獲得第一個鍵值對
return exportEntry(getFirstEntry());
//返回調用exportEntry方法
}
public Map.Entry<K,V> lastEntry(){
//獲得最後一個鍵值對
return exportEntry(getLastEntry());
}
public Map.Entry<K,V> pollFirstEntry(){
//刪除並返回第一個結點
Entry<K,V> p = getFirstEntry();
//獲得第一個結點
Map.Entry<K,V> result = exportEntry(p);
//返回p的一個簡單拷貝結點
if(p != null)
deleteEntry(p);
//刪除找到的結點
return result;
//返回結果
}
public Map.Entry<K,V> pollLastEntry(){
//刪除並返回最後一個結點
Entry<K,V> p = getLastEntry();
Map.Entry<K,V> result = exportEntry(p);
if(p != null)
deleteEnrty(p);
return result;
}
5.獲取相應集合
public Set<K> keySet(){
//獲取遍歷TreeMap中key的Set容器
return navigableKeySet();
}
public NavigableSet<K> navigableKeySet(){
//獲取順序的Set容器的key集合
KeySet<K> nks = navigableKeySet;
return (nks != null) ? nks : (navigableKeySet = new KeySet<>(this));
}
public NavigableSet<K> descendingKeySet(){
//返回逆序的Set容器的key集合
return descendingMap().navigableKeySet();
}
public Collection<V> values(){
//返回包含TreeMap中的所有value的集合
Collection<V> vs = values;
if(vs == null){
vs = new Values();
values = vs;
}
return vs;
}
public Set<Map.Entry<K,V>> entrySet(){
//獲取包含TreeMap中的所有鍵值對集合的Set容器
EntrySet es = entrySet;
return (es != null) ? es : (entrySet = new EntrySet());
}
6.其他方法
public void clear(){
//清空紅黑樹
modCount++;
//修改次數加一
size = 0;
//將結點數目重置爲0
root = null;
//將根節點置爲空就夠了
}
public int size(){
//獲得樹中的結點數量
return size;
}
public boolean containsKey(Object key){
//判斷樹中是否存在含有key值的結點
return getEntry(key) != null;
}
public boolean containsValue(Object value){
//判斷樹中是否存在含有value值的結點
for(Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
//遍歷樹中的結點,一個個進行比較,存在則返回true,不存在則返回false
if(valEquals(value,e.value))
return true;
return false;
}
總結:TreeMap的底層數據結構是紅黑樹,可以通過自定義比較器的方式讓TreeMap中的鍵值對按照相應的方式進行排序,並可以通過順序或逆序對TreeMap中的鍵值對進行遍歷。除此之外還可以獲得TreeMap中的子Map,即紅黑樹中的子樹,並對其進行操作。
總源碼
public class TreeMap<K,V> extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
{
private final Comparator<? super K> comparator;
//自定義比較器
private transient Entry<K,V> root;
//根節點,不可序列化
private transient int size = 0;
//結點個數,不可序列化
private transient int modCount = 0;
//修改次數,不可序列化
public TreeMap(){
//構造器1,不定義比較器
comparator = null;
}
public TreeMap(Comparator<? super K> comparator){
//構造器2,傳入構造器,根據構造器建樹
this.comparator = comparator;
}
public TreeMap(Map<? extends K, ? extends V> m){
//構造器3,傳入普通Map類型的容器,將容器中的鍵值對加入到樹中
comparator = null;
//將比較器設置爲Null
putAll(m);
}
public TreeMap(SortedMap<K, ? extends V> m){
//構造器4,傳入的是一個排序的Map類型容器,將容器中的鍵值對按照順序
//加入到樹中
comparator = m.comparator();
//將m的比較器設置成本類的比較器
try{
//使用迭代的方法將m的鍵值對複製到新的TreeMap的容器中
buildFromSorted(m.size(), m.entrySet().iterator(),null,null)
}catch(java.io.IOException cannotHappen){
}catch(ClassNotFoundException cannotHappen){
}
}
public int size(){
//獲得樹中的結點數量
return size;
}
public boolean containsKey(Object key){
//判斷樹中是否存在含有key值的結點
return getEntry(key) != null;
}
public boolean containsValue(Object value){
//判斷樹中是否存在含有value值的結點
for(Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
//遍歷樹中的結點,一個個進行比較,存在則返回true,不存在則返回false
if(valEquals(value,e.value))
return true;
return false;
}
public V get(Object key){
//根據key尋找相應鍵值對,如果沒找到返回null,
//找到了則返回key對應的value值
Entry<K,V> p = getEntry(key);
return (p == null ? null : p.value);
}
public Comparator<? super K> comparator(){
//獲得樹中的比較器
return comparator;
}
public K firstKey(){
//獲得第一個結點的key值
return key(getFirstEntry());
}
public K lastKey(){
//獲得最後一個結點的Key值
return key(getLastEntry());
}
public void putAll(Map<? extends K, ? extends V> map){
//將Map類型容器中的鍵值對放入本容器中
int mapSize = map.size();
//獲得m中的結點數量
if(size == 0 && mapSize != 0 && map instanceof SortedMap){
//如果當前容器中沒有結點且傳進來的容器有結點並是SortedMap類型
//的容器
Comparator<?> c = ((SortedMap<?,?>)map).comparator();
//獲得map中的比較器
if(c == comparator || (c != null && c.equals(comparator))){
//如果兩者的比較器一樣,則開始複製結點
++modCount;
try{
buildFromSorted(mapSize, map.entrySet().iterator(), null, null);
}catch(java.io.IOException cannotHappen){
}catch(ClassNotFoundException cannotHappen){
}
return;
}
}
super.putAll(map);
//如果不滿足,則調用父類的方法進行加入
}
final Entry<K,V> getEntry(Object key){
//根據key值獲得鍵值對
if(comparator != null)
//如果比較器不爲空,則調用使用比較器的方法
return getEntryUsingComparator(key);
if(key == null)
//如果key值爲空,則拋出空指針異常
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>)key;
//如果沒有自定義比較器,則按照key值的比較方法進行比較
Entry<K,V> p = root;
//首先獲取紅黑樹的根
while(p != null){
//向下尋找,深度遍歷
int cmp = k.compareTo(p.key);
if(cmp < 0)
p = p.left;
else if(cmp > 0)
p = p.right;
else
return p;
}
return null;
}
final Entry<K,V> getEntryUsingComparator(Object key){
//按照比較器進行查詢,根據key值獲得相應的鍵值對
@Suppressings("unchecked")
K k = (K) key;
//獲得傳入的key值
Comparator<? super K> cpr = comparator;
//首先獲得比較器
if(cpr != null){
//深度遍歷,根據比較器查找鍵值對
Entry<K,V> p = root;
while(p != null){
int cmp = cpr.compare(k,p.key);
if(cmp < 0)
p = p.left;
else if(cmp > 0)
p = p.right;
else
return p;
}
}
return null;
//如果找不到,則返回null
}
final Entry<K,V> getCeilingEntry(K key){
//尋找不小於key的最小結點,也就是說要麼是它自己
//要麼是紅黑樹中序遍歷中最接近自己的且比自己大的結點
Entry<K,V> p = root;
//首先獲得根節點
while(p != null){
//開始深度遍歷,使用比較器
int cmp = compare(key, p.key);
if(cmp < 0){
//如果傳進來的key比當前結點的key小,向左孩子深入
if(p.left != null)
p = p.left;
else
//如果左孩子爲空,說明此結點已經是這棵樹中大於key
//中結點的最小結點了
return p;
}else if(cmp > 0){
//如果傳進來的key比當前結點的key值大,則向右孩子深入
if(p.right != null){
p = p.right;
}else{
//如果右孩子爲空,則要找到中序遍歷的後一個結點,也就是說
//如果在遍歷的路徑上有一條路是通過深入父結點的左孩子下來的
//則就找那最近的父結點,如果沒有,說明是一直是通過深入父結點的
//右孩子下來的,則一直追溯到根節點,返回null
Entry<K,V> parent = p.parent;
Entry<K,V> ch = p;
while(parent != null && ch == parent.right){
ch = parent;
parent = parent.parent;
}
return parent;
}
}else
//如果找到相等的結點,則返回該結點
return p;
}
return null;
//否則返回null
}
final Entry<K,V> getFloorEntry(K key){
//和上一個方法相反,找到不大於key的最大結點,如果沒有,則返回Null
Entry<K,V> p = root;
while(p != null){
int cmp = compare(key, p.key);
if(cmp > 0){
if(p.right != null)
p = p.right;
else
return p;
}else if(cmp < 0){
if(p.left != null){
p = p.left;
}else{
Entry<K,V> parent = p.parent;
Entry<K,V> ch = p;
while(parent != null && ch == parent.left){
ch = parent;
parent = parent.parnet;
}
return parent;
}
}else
return p;
}
return null;
}
final Entry<K,V> getHigherEntry(K key){
//獲得大於key值的最小結點,自己不算,和getCeilingEntry方法類似
Entry<K,V> p = root;
while(p != null){
int cmp = compare(key, p.key);
if(cmp < 0){
if(p.left != null)
p = p.left;
else
return p;
}else{
if(p.right != null){
p = p.right;
}else{
Entry<K,V> parent = p.parent;
Entry<K,V> ch = p;
while(parent != null && ch == parent.right){
ch = parent;
parent = parent.parent;
}
return parent;
}
}
}
return null;
}
final Entry<K,V> getLowerEntry(K key){
//獲得小於key值的最大結點,自己不算,和getFloorEntry方法類似
Entry<K,V> p = root;
while(p != null){
int cmp = compare(key,p.key);
if(cmp > 0){
if(p.right != null)
p = p.right;
else
return p;
}else{
if(p.left != null){
p = p.left;
}else{
Entry<K,V> parent = parent;
Entry<K,V> ch = p;
while(parent != null && ch == parent.left){
ch = parent;
parent = parent.parent;
}
return parent;
}
}
}
return null;
}
public V put(K key, V value){
//將一個鍵值對放入紅黑樹中
Entry<K,V> t = root;
//獲取紅黑樹的根
if(t == null){
//如果根爲空,則說明紅黑樹中沒有結點
compare(key,key);//類型驗證
root = new Entry<>(key, value, null);
//新建結點作爲根
size = 1;
//結點數量設置爲1
modCount++;
//修改次數
return null;
//插入成功則返回null
}
int cmp;
//標記,記錄新節點應該插在哪裏或者尋找插入點時下一次向什麼方向尋找
Entry<K,V> parent;
Comparator<? super K> cpr = comparator;
//獲得比較器
if(cpr != null){
//如果比較器不爲空,則用TreeMap中的比較器進行比較
do{
parent = t;
//將當前結點作爲父結點
cmp = cpr.compare(key, t.key);
//獲得比較結果
if(cmp < 0)
//如果傳入的key值比當前結點的key值小
t = t.left;
//則向其左子樹下找
else if(cmp > 0)
//如果傳入key值比當前結點的key值大
t = t.right;
//則向其右子樹下找
else
return t.setValue(value);
//如果相等,則將該結點的value值設置爲傳進來的value值
//從此處可以看出其和HashMap的不同,key值不允許有相同的
}while(t != null);
}
else{
//否則表示比較器爲空,用key類自己的比較方式進行比較
if(key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>)key;
//對傳進來的key進行強制類型轉換
do{
//進行比較,尋找插入點
parent = t;
cmp = k.compareTo(t.key);
if(cmp < 0)
t = t.left;
if(cmp > 0)
t = t.right;
else
return t.setValue(value);
}while(t != null);
}
//上面爲尋找插入點,下面開始正式插入
Entry<K,V> e = new Entry<>(key,value,parent);
//新建結點
if(cmp < 0)
//如果cmp小於零,則表示將e插入其父結點的左孩子處
parent.left = e;
else
parent.right = e;
//否則將e插入其父節點的右孩子處
fixAfterInsertion(e);
//插入後的調整,類似HashMap中的balanceInsertion方法
size++;
//結點數目加一
modCount++;
//修改次數加一
return null;
//插入成功,返回Null
}
public V remove(Object key){
//根據傳入的key值刪除對應的鍵值對
Entry<K,V> p = getEntry(key);
//先找到該鍵值對
if(p == null)
return null;
//如果找不到,則返回Null
V oldValue = p.value;
//如果找到該結點,則先得到其value值
deleteEnrty(p);
//刪除該結點
return oldValue;
//返回被刪除結點的value值
}
public void clear(){
//清空紅黑樹
modCount++;
//修改次數加一
size = 0;
//將結點數目重置爲0
root = null;
//將根節點置爲空就夠了
}
public Object clone(){
//克隆方法
TreeMap<?,?> clone;
//首先創建一個TreeMap作爲克隆對象
try{
clone = (TreeMap<?,?>)super.clone();
//調用父類的克隆方法
}catch(CloneNotSupportedException e){
throw new InternalError(e);
//如果調用出錯,拋出錯誤
}
clone.root = null;
//首先設置克隆對象的根結點爲空
clone.size = 0;
//結點數量爲0
clone.modCount = 0;
//修改次數爲0
clone.entrySet = null;
//entrySet也爲空
clone.navigableKeySet = null;
//navigableKeySet爲空
clone.descendingMap = null;
//descendingMap爲空
try{
clone.buildFromSorted(size,entrySet().iterator(), null, null);
//使用迭代器進行克隆複製操作
}catch(java.io.IOException cannotHappen){
}catch(ClassNotFoundException cannotHappen){
}
return clone;
//返回克隆對象
}
public Map.Entry<K,V> firstEntry(){
//獲得第一個鍵值對
return exportEntry(getFirstEntry());
//返回調用exportEntry方法
}
public Map.Entry<K,V> lastEntry(){
//獲得最後一個鍵值對
return exportEntry(getLastEntry());
}
public Map.Entry<K,V> pollFirstEntry(){
//刪除並返回第一個結點
Entry<K,V> p = getFirstEntry();
//獲得第一個結點
Map.Entry<K,V> result = exportEntry(p);
//返回p的一個簡單拷貝結點
if(p != null)
deleteEntry(p);
//刪除找到的結點
return result;
//返回結果
}
public Map.Entry<K,V> pollLastEntry(){
//刪除並返回最後一個結點
Entry<K,V> p = getLastEntry();
Map.Entry<K,V> result = exportEntry(p);
if(p != null)
deleteEnrty(p);
return result;
}
public Map.Entry<K,V> lowerEntry(K key){
//對外方法,獲取小於key的最大結點鍵值對
return exportEntry(getLowerEntry(key));
}
public K lowerKey(K key){
//返回小於key值的最大key值,如果不存在則返回null
return keyOrNull(getLowerEntry(key));
}
public Map.Entry<K,V> floorEntry(K key){
//對外方法,獲取不大於key值的最大鍵值對
return exportEntry(getFloorEntry(key));
}
public K floorKey(K key){
//對外方法,獲取不大於key值的最大key值,如果沒有則返回null
return keyOrNull(getFloorEntry(key));
}
public Map.Entry<K,V> ceilingEntry(K key){
//對外方法,獲取不小於key值的最小鍵值對
return exportEntry(getCeilingEntry(key));
}
public K ceilingKey(K key){
//對外方法,獲取不小於key值的最小key值,如果沒有則返回Null
return keyOrNull(getCeilingEntry(key));
}
public Map.Entry<K,V> higherEntry(K key){
//對外方法,獲取大於key值的最小鍵值對
return exportEntry(getHigherEntry(key));
}
public K higherKey(K key){
//對外方法,獲取大於key值的最小key值,如果沒有則返回null
return keyOrNull(getHigherEntry(key));
}
private transient EntrySet entrySet;
//私有成員變量,不可序列化,用於遍歷TreeMap中的鍵值對
private transient KeySet<K> navigableKeySet;
//私有成員變量,不可序列化,用於遍歷TreeMap中的key
private transient NavigableMap<K,V> descendingMap;
//私有成員變量,不可序列化,用於逆序遍歷TreeMap中的鍵值對
public Set<K> keySet(){
//獲取遍歷TreeMap中key的Set容器
return navigableKeySet();
}
public NavigableSet<K> navigableKeySet(){
//獲取順序的Set容器的key集合
KeySet<K> nks = navigableKeySet;
return (nks != null) ? nks : (navigableKeySet = new KeySet<>(this));
}
public NavigableSet<K> descendingKeySet(){
//返回逆序的Set容器的key集合
return descendingMap().navigableKeySet();
}
public Collection<V> values(){
//返回包含TreeMap中的所有value的集合
Collection<V> vs = values;
if(vs == null){
vs = new Values();
values = vs;
}
return vs;
}
public Set<Map.Entry<K,V>> entrySet(){
//獲取包含TreeMap中的所有鍵值對集合的Set容器
EntrySet es = entrySet;
return (es != null) ? es : (entrySet = new EntrySet());
}
public NavigableMap<K,V> descendingMap(){
//獲取包含TreeMap中的所有鍵值對的逆序集合的Set容器
NavigableMap<K,V> km = descendingMap;
return (km != null) ? km
: (descendingMap = new DescendingSubMap<>(this,true,null,true,true,null,true));
}
public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive){
//獲取TreeMap中鍵值對的一部分,fromInclusive表示是否包含起始結點,toInclusive表示是否包含結束結點
return new AscendingSubMap<>(this,false,fromKey,fromInclusive,false,toKey,toInclusive);
}
public NavigableMap<K,V> headMap(K toKey, boolean inclusive){
//獲取TreeMap中鍵值對從頭開始的某一部分,inclusive表示是否包含結束結點
return new AscendingSubMap<>(this,true,null,true,false,toKey,inclusive);
}
public SortedMap<K,V> subMap(K fromKey, K toKey){
//獲取TreeMap中鍵值對的一部分,包含起始結點,不包含結束結點
return subMap(fromKey,true,toKey,false);
}
public SortedMap<K,V> headMap(K toKey){
//獲取TreeMap中鍵值對從頭開始的某一部分,不包含結束結點
return headMap(toKey,false);
}
public SortedMap<K,V> tailMap(K fromKey){
//獲取TreeMap中從某一個結點開始到尾結點,包含尾結點
return tailMap(fromKey,true);
}
@Override
public boolean replace(K key,V oldValue, V newValue){
//根據key值找到該鍵值對,將該鍵值對的Value值換爲新的Value值
Entry<K,V> p = getEntry(key);
//尋找該鍵值對
if(p != null && Objects.equals(oldValue,p.value)){
//如果找到了,則對比該鍵值對中value是否和傳進來的oldValue一致
p.value = newValue;
//如果一致,則將舊value換爲新value
return true;
//換成功則返回true
}
return false;
//否則返回false
}
@Override
public V replace(K key, V value){
//重載replace方法,不傳入舊值,直接換新值
//如果換成功了則返回新值,否則返回null
Entry<K,V> p = getEntry(key);
if(p != null){
V oldValue = p.value;
p.value = value;
return oldValue;
}
return null;
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action){
//java 1.8新特性
Objects.requireNonNull(action);
int expectedModCount = modCount;
for(Entry<K,V> e = getFirstEntry; e != null; e = successor(e)){
action.accept(e.key, e.value);
if(expectedModCount != modCount)
throw new ConcurrentModificationException();
}
}
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V>function){
//替換全部結點
Objects.requireNonNull(function);
int expectedModCount = modCount;
for(Entry<K,V> e = getFirstEntry(); e != null; e = successor(e)){
e.value = function.apply(e.key,e.value);
if(expectedModCount != modCount)
throw new ConcurrentModificationException();
}
}
class Values extends AbstractCollection<V>{
//values集合類,內部類,用於遍歷TreeMap中的value值
public Iterator<V> iterator(){
//獲取Value迭代器
return new ValueIterator(getFirstEntry());
}
public int size(){
//獲取TreeMap中的鍵值對數量
return TreeMap.this.size();
}
public boolean contains(Object o){
//判斷是否包含某value值
return TreeMap.this.containsValue(o);
}
public boolean remove(Object o){
//移除某個含有o的value值的鍵值對
for(Entry<K,V> e = getFirstEntry(); e != null; e = successor(e)){
if(valEquals(e.getValue(),o)){
deleteEnrty(e);
return true;
}
}
return false;
}
public void clear(){
//清空TreeMap
TreeMap.this.clear();
}
public Spliterator<V> spliterator(){
//獲取分割器
return new ValueSpliterator<K,V>(TreeMap.this, null, 0, -1, 0);
}
}
class EntrySet extends AbstractSet<Map.Entry<K,V>>{
//鍵值對Set容器類,內部類,用於遍歷TreeMap中的鍵值對
public Iterator<Map.Entry<K,V>> iterator(){
//獲得鍵值對迭代器
return new EntryIterator(getFirstEntry());
}
public boolean contains(Objects o){
//傳入一個鍵值對,返回TreeMap中是否包含該鍵值對
if(!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
Object value = entry.getValue();
Entry<K,V> p = getEntry(entry.getKey());
return p != null && valEquals(p.getValue(),value);
}
public boolean remove(Object o){
//從TreeMap中刪除某一個鍵值對
if(!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
Object value = entry.getValue();
Entry<K,V> p = getEntry(entry.getKey());
if(p != null && valEquals(p.getValue(), value)){
deleteEntry(p);
return true;
}
return false;
}
public int size(){
//獲得TreeMap的大小
return TreeMap.this.size();
}
public void clear(){
//清空TreeMap
TreeMap.this.clear();
}
public Spliterator<Map.Entry<K,V>> spliterator(){
//獲得分割器
return new EntrySpliterator<K,V>(TreeMap.this, null, null, 0, -1, 0);
}
}
Iterator<K> keyIterator(){
//獲得key值的正序迭代器
return new KeyIterator(getFirstEntry());
}
Iterator<K> descendingKeyIterator(){
//獲得key值的逆序迭代器
return new DescendingKeyIterator(getLastEntry());
}
static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E>{
//靜態內部類,主要用於遍歷key值
private final NavigableMap<E,?> m;
KeySet(NavigableMap<E,?> map){
//構造器
m = map;
}
public Iterator<E> iterator(){
//獲取正序迭代器
if(m instanceof TreeMap)
return ((TreeMap<E,?>)m).keyIterator();
else
return ((TreeMap.NavigableSubMap<E,?>)m).keyIterator();
}
public Iterator<E> descendingIterator(){
//獲取逆序迭代器
if(m instanceof TreeMap)
return ((TreeMap<E,?>)m).descendingKeyIterator();
else
return ((TreeMap.NavigableSubMap<E,?>)m).descendingKeyIterator();
}
public int size(){
//返回map的鍵值對數量
return m.size();
}
public boolean isEmpty(){
//判斷map是否爲空
return m.isEmpty();
}
public boolean contains(Object o){
//判斷m中是否包含某一個key值
return m.containsKey(o);
}
public void clear(){
//清空map
m.clear();
}
public E lower(E e){
//獲取小於e的最大key值
return m.lowerKey(e);
}
public E floor(E e){
//獲取不大於e的最大key值
return m.floorKey(e);
}
public E ceiling(E e){
//獲取不小於e的最小key值
return m.ceilingKey(e);
}
public E higher(E e){
//獲取大於e的最下key值
return m.higherKey(e);
}
public E first(){
//獲得第一個的key值
return m.firstKey();
}
public E last(){
//獲得最後一個key值
return m.lastKey();
}
public Comparator<? super E> comparator(){
//獲得比較器
return m.comparator();
}
public E pollFirst(){
//獲得並刪除第一個key值
Map.Entry<E,?> e = m.pollLastEntry();
return (e == null) ? null : e.getKey();
}
public E pollLast(){
//獲得並刪除最後一個key值
Map.Entry<E,?> e = m.pollLastEntry();
return (e == null) ? null : e.getKey();
}
public boolean remove(Object o){
//移除某一個鍵值對,如果刪除成功則返回true,否則返回false
int oldSize = size();
m.remove(o);
return size() != oldSize;
}
public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElment, boolean toInclusive){
//獲得map中key值的一部分
return new KeySet<>(m.subMap(fromElement,fromInclusive,toElement,toInclusive));
}
public NavigableSet<E> headSet(E toElement, boolean inclusive){
//獲得map中從頭開始的某一部分的key值
return new KeySet<>(m.headMap(toElement,inclusive));
}
public NavigableSet<E> tailSet(E fromElement, boolean inclusive){
//獲得map中從某一起始處到最後的一部分key值
return new KeySet<>(m.tailMap(fromElement, inclusive));
}
public NavigableSet<E> descendingSet(){
//獲得逆序的keySet
return new KeySet<>(m.descendingMap());
}
public Spliterator<E> spliterator(){
//獲得key值的迭代器
return keySpliteratorFor(m);
}
}
abstract class PrivateEntryIterator<T> implements Iterator<T>{
//TreeMap中的抽象類,實現了一些通用接口
Entry<K,V> next;//下一個結點
Entry<K,V> lastReturned;//最後返回的結點
int expectedModCount;//修改次數
PrivateEntryIterator(Entry<K,V> first){
//構造器
expectedModCount = modCount;
lastReturned = null;
next = first;
}
public final boolean hasNext(){
//是否存在下一個結點
return next != null;
}
final Entry<K,V> nextEntry(){
//下一個結點
Entry<K,V> e = next;
if(e == null)
throw new NoSuchElementException();
if(modCount != expectedModCount)
throw new ConcurrentModificationException();
next = successor(e);
lastReturned = e;
}
final Entry<K,V> prevEntry(){
//上一個結點
Entry<K,V> e = next;
if(e == null)
throw new NoSuchElementException();
if(modCount != expectedModCount)
throw new ConcurrentModificationException();
next = predecessor(e);
lastReturned = e;
return e;
}
public void remove(){
//刪除當前結點
if(lastReturned == null)
throw new IllegalStateException();
if(modCount != expectedModCount)
throw new ConcurrentModificationException();
if(lastReturned.left != null && lastReturned.right != null)
//此處當被刪除的結點的左右結點都不爲空,則說明在刪除的時候要
//將當前結點和其中序遍歷的後繼結點互換,因此next還可以指向當前
//結點,在當前結點刪除之後,next還可以繼續遍歷紅黑樹
next = lastReturned;
deleteEntry(lastReturned);
expectedModCount = modCount;
lastReturned = null;
}
}
final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>>{
//Entry迭代器
EntryIterator(Entry<K,V> first){
//構造器,調用父類構造器
super(first);
}
public Map.Entry<K,V> next(){
//實現了next方法
return nextEntry();
}
}
final class ValueIterator extends PrivateEntryIterator<V>{
//value迭代器
valueIterator(Entry<K,V> first){
super(first);
}
public V next(){
return nextEntry().value;
}
}
final class KeyInterator extends PrivateEntryIterator<K>{
//key值迭代器
KeyIterator(Entry<K,V> first){
super(first);
}
public K next(){
return nextEntry().key;
}
}
final class DescendingKeyIterator extends PrivateEntryIterator<K>{
//key值逆序迭代器
DescendingKeyIterator(Entry<K,V> first){
super(first);
}
public K next(){
//重寫next方法,此處調用獲取前一個結點實現逆序迭代的功能
return prevEntry().key;
}
public void remove(){
//移除當前結點
if(lastReturned == null)
throw new IllegalStateException();
if(modCount != expectedModCount)
throw new ConcurrentModificationException();
deleteEntry(lastReturned);
lastReturned = null;
expectedModCount = modCount;
}
}
@SuppressWarnings("unchecked")
final int compare(Object k1,Object k2){
//比較傳進來的兩個Key值,如果沒有比較器,則用自己的方法比較,否則就用比較器比較
return comparator == null ? ((Comparable < ? super K>)k1).compareTo((K)k2)
: comparator.compare((K)k1,(K)k2);
}
static final boolean valEquals(Object o1,Object o2){
//比較兩個值是否相等
return (o1 == null ? o2 == null : o1.equals(o2));
}
static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e){
//返回鍵值對的一個簡單拷貝
return (e == null) ? null :
new AbstractMap.SimpleImmutableEntry<>(e);
}
static <K,V> K keyOrNull(TreeMap.Entry<K,V> e){
//返回鍵值對的key值,如果沒有則返回null
return (e == null) ? null : e.key;
}
static <K> K key(Entry<K,?> e){
//獲得鍵值對中的key值,如果沒有則拋出異常
if(e == null)
throw new NoSuchElementException();
return e.key;
}
private static final Object UNBOUNDED = new Object();
//這個是什麼意思?幹什麼的????
abstract static class NavigableSubMap<K,V> extends AbstractMap<K,V>
implements NavigableMap<K,V>,java.io.Serializable{
//TreeMap中的一個子Map,抽象內部靜態類
private static final long serialVersionUID = -2102997345730753016L;
//序列化標誌,反序列化的
final TreeMap<K,V> m;
final K lo,hi;
//lo爲子Map範圍中的最小值,hi爲子Map範圍中的最大值
final boolean fromStart,toEnd;
//fromStart表示是否從第一個結點開始計算,toEnd表示是否從最後一個結點開始計算
final boolean loInclusive,hiInclusive;
//loInclusive表示是否包括最小結點,hiInclusive表示是否包括最大結點
NavigableSubMap(TreeMap<K,V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi, boolean hiInclusive){
//構造器
if(!fromStart && !toEnd){
if(m.compare(lo,hi) > 0)
throw new IllegalArgumentException("fromKey > toKey");
}else{
if(!fromStart)
m.compare(lo,lo);
if(!toEnd)
m.compare(hi,hi);
}
this.m = m;
this.fromStart = fromStart;
this.lo = lo;
this.loInclusive = loInclusive;
this.toEnd = toEnd;
this.hi = hi;
this.hiInclusive = hiInclusive;
}
final boolean tooLow(Object key){
//判斷key值是否太小,也就是判斷是否能成爲SubMap中的一員
if(!fromStart){
//首先SubMap不包括起始結點
int c = m.compare(key,lo);
if(c < 0 || (c == 0 && !loInclusive))
//並且key比最小結點小或者key和最小結點相等但是不包括最小結點
return true;
//則返回true
}
return false;
//否則返回false
}
final boolean tooHigh(Object key){
//判斷key值是否太大,判斷是否能成功SubMap中的一員
if(!toEnd){
//首先SubMap不包括結束結點
int c = m.compare(key,hi);
if(c > 0 || (c == 0) && !hiInclusive))
//並且key大於最大結點或者key和最大結點相等但是不包括最大結點
return true;
}
return false;
}
final boolean inRange(Object key){
//判斷某一個key值是否在(lo,hi)開區間範圍內,也就是既不太小也不太大
return !tooLow(key) && !tooHight(key);
}
final boolean inClosedRange(Object key){
//判斷某一個key值是否在[lo,hi]這個閉區間範圍內。不太懂????
return (fromStart || m.compare(key,lo) >= 0)
&& (toEnd || m.compare(hi,key) >= 0);
}
final boolean inRange(Object key, boolean inclusive){
//判斷一個key值是否在lo,hi這個區間內,inclusive控制區間的開閉
return inclusive ? inRange(key) : inClosedRange(key);
}
final TreeMap.Entry<K,V> absLowest(){
//取子Map中最小的結點
TreeMap.Entry<K,V> e = (fromStart ? m.getFirstEntry() : (loInclusive ? m.getCeilingEntry(lo) : m.getHigherEntry(lo)));
//如果包括第一個結點則直接取第一個結點否則判斷是否包含最小的結點,如果包含,取不小於lo的最小結點,否則取大於lo的最小結點
return (e == null || tooHigh(e.key)) ? null : e;
//如果e爲空或者e結點的key值太大了,不在範圍內,則返回null,否則返回e
}
final TreeMap.Enrty<K,V> absHighest(){
//取子Map中最大的結點,和上面一個方法類似
TreeMap.Entry<K,V> e = (toEnd ? m.getLastEntry() : (hiInclusive ? m.getFloorEntry(hi) : m.getLowerEntry(hi)));
return (e == null || tooLow(e.key)) ? null : e;
}
final TreeMap.Entry<K,V> absCeiling(K key){
//獲得不小於key值的最小Entry
if(tooLow(key))
//如果key不在範圍內
return absLowest();
//返回最小結點
TreeMap.Entry<K,V> e = m.getCeilingEntry(key);
//否則獲取map中不小於key值的最小Entry
return (e == null || tooHigh(e.key)) ? null : e;
//如果e結點爲空或者e的key值太大,則返回空,否則返回e
}
final TreeMap.Entry<K,V> absHigher(K key){
//獲取大於key值的最小Enrty
if(tooLow(key))
return absLowest();
TreeMap.Entry<K,V> e = m.getHigherEntry(key);
return (e == null || tooHigh(e.key)) ? null : e;
}
final TreeMap.Entry<K,V> absFloor(K key){
//獲取不大於key值的最大Entry
if(tooHigh(key))
return absHighest();
TreeMap.Entry<K,V> e = m.getFloorEntry(key);
return (e == null || tooLow(e.key)) ? null : e;
}
final TreeMap.Entry<K,V> absLower(K key){
//獲取小於key值的最大Entry
if(tooHigh(key))
return absHighest();
TreeMap.Entry<K,V> e = m.getLowerEntry(key);
return (e == null || tooLow(e.key)) ? null : e;
}
final TreeMap.Entry<K,V> absHighFence(){
//返回大於最大結點的最小結點
return (toEnd ? null : (hiInclusive ? m.getHigherEntry(hi) : m.getCeilingEntry(hi)));
//首先判斷是否包含最後一個結點,如果包含則返回空,否則判斷是否包含最大結點,如果包含則
//獲取大於hi結點的最小結點,否則獲取大於等於hi結點的最小結點
}
final TreeMap.Enrty<K,V> absLowFence(){
//返回小於最小結點的最大結點
return (fromStart ? null : (loInclusive ? m.getLowerEntry(lo) : m.getFloorEntry(lo)));
}
//實現NavigableMap類需要實現的方法
abstract TreeMap.Enrty<K,V> subLowest();
abstract TreeMap.Entry<K,V> subHighest();
abstract TreeMap.Entry<K,V> subCeiling(K key);
abstract TreeMap.Entry<K,V> subHigher(K key);
abstract TreeMap.Entry<K,V> subFloor(K key);
abstract TreeMap.Entry<K,V> subLower(K key);
abstract Iterator<K> keyIterator();
abstract Spliterator<K> keySpliterator();
abstract Iterator<K> descendingKeyIterator();
public boolean isEmpty(){
//判斷子Map是否爲空
return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty();
//如果包含第一個結點也包含最後一個結點,則調用m的判空方法,否則
//調用entrySet()獲得一個EntrySet,然後判斷EntrySet是否爲空,why?????
}
public int size(){
//獲取子Map中的結點數量
return (fromStart && toEnd) ? m.size() : entrySet().size();
}
public final boolean containsKey(Object key){
//判斷子map中是否含有某個key值
return inRange(key) && m.containsKey(key);
//首先判斷key是否在範圍內,再判斷有沒有
}
public final V put(K key, V value){
//將鍵值對插入到SubMap中
if(!inRange(key))
throw new IllegalArgumentException("key out of range");
return m.put(key,value);
}
public final V get(Object key){
//根據鍵值獲取SubMap中的value值
return !inRange(key) ? null : m.get(key);
}
public final V remove(Object key){
//移除SubMap中的某個結點
return !inRange(key) ? null : m.remove(key);
}
public final Map.Entry<K,V> ceilingEntry(K key){
//獲取不小於key的最小Entry
return exportEntry(subCeiling(key));
//返回該鍵值對的簡單拷貝
}
public final K ceilingKey(K key){
//返回不小於key值的最小key,如果沒有,則返回Null
return keyOrNull(SubCeiling(key));
}
public final Map.Entry<K,V> higherEntry(K key){
//獲取大於key的最小Entry的簡單拷貝
return exportEntry(subHigher(key));
}
public final K higherKey(K key){
//獲取大於Key值的最小key,如果沒有,返回null
return keyOrNull(subHigher(key));
}
public final Map.Enrty<K,V> floorEntry(K key){
//獲取不大於key的最大Entry的簡單拷貝
return exportEntry(subFloor(key));
}
public final K floorKey(K key){
//獲取不大於key的最大key值,如果沒有,返回null
return keyOrNull(subFloor(key));
}
public final Map.Entry<K,V> lowerEntry(K key){
//獲取小於key的最大Entry的簡單拷貝
return exportEntry(subLower(key));
}
public final K lowerKey(K key){
//獲取小於key的最大key值,如果沒有,返回null
return keyOrNull(subLower(key));
}
public final K firstKey(){
//獲得第一個結點的key,也就是返回最小的結點的key
return key(subLowest());
}
public final K lastKey(){
//獲得最後一個結點的key,也就是返回最大的結點的key
return key(subHighest());
}
public final Map.Entry<K,V> firstEntry(){
//獲得第一個結點
return exportEntry(subLowest());
}
public final Map.Entry<K,V> lastEntry(){
//獲得最後一個結點
return exportEntry(subHighest());
}
public final Map.Entry<K,V> pollFirstEntry(){
//返回並刪除第一個結點,獲得的是該結點的簡單拷貝
TreeMap.Entry<K,V> e = subLowest();
Map.Entry<K,V> result = exportEntry(e);
if(e != null)
m.deleteEntry(e);
return result;
}
public final Map.Entry<K,V> pollLastEntry(){
//返回並刪除最後一個結點,獲得的是該結點的簡單拷貝
TreeMap.Entry<K,V> e = subHighest();
Map.Entry<K,V> result = exportEntry(e);
if(e != null)
m.deleteEntry(e);
return result;
}
//視圖
transient NavigableMap<K,V> descendingMapView;
transient EntrySetView entrySetView;
transient KeySet<K> navigableKeySetView;
public final NavigableSet<K> navigableKeySet(){
//獲得key的集合Set
KeySet<K> nksv = navigableKeySetView;
return (nksv != null) ? nksv : (navigableKeySetView = new TreeMap.KeySet<>(this));
}
public final Set<K> keySet(){
//獲得key的集合Set
return navigableKeySet();
}
public NavigableSet<K> descendingKeySet(){
//獲得key的逆序集合Set
return descendingMap().navigableKeySet();
}
public final SortedMap<K,V> subMap(K fromKey, K toKey){
//在SubMap上面再建subMap,默認包含開始結點,不包含結束結點
return subMap(fromKey, true, toKey, false);
}
public final SortedMap<K,V> headMap(K toKey){
//從頭結點到結束結點,不包含結束結點
return headMap(toKey,false);
}
public final SortedMap<K,V> tailMap(K fromKey){
//從開始結點到尾結點,包含開始結點
return tailMap(fromKey,true);
}
abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>>{
//map的Entry集合
private transient int size = -1,sizeModCount;
public int size(){
//獲得Entry集合的大小
if(fromStart && toEnd)
//如果包含起始結點和結束結點
return m.size();
//直接返回m的大小
if(size == -1 || sizeModCount != m.modCount){
//如果沒有初始化,則開始初始化,使用迭代器獲得集合大小
sizeModCount = m.modCount;
size = 0;
Iterator<?> i = iterator();
while(i.hasNext()){
size++;
i.next();
}
}
return size;
}
public boolean isEmpty(){
//判斷Entry集合是否爲空
TreeMap.Entry<K,V> n = absLowest();
//先獲得最小結點
return n == null || tooHigh(n.key);
//如果該結點不是控制且在範圍內,則不爲空,否則爲空
}
public boolean contains(Object o){
//判斷Entry集合中是否包含某個Entry
if(!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
Object key = entry.getKey();
if(!inRange(key))
return false;
TreeMap.Entry<?,?> node = m.getEntry(key);
return node != null && valEquals(node.getValue(),entry.getValue());
}
public boolean remove(Object o){
//從Entry集合中刪除某個Entry
if(!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
Object key = entry.getKey();
if(!inRange(key))
return false;
TreeMap.Entry<K,V> node = m.getEntry(key);
if(node != null && valEquals(node.getValue(), entry.getValue())){
m.deleteEntry(node);
return true;
}
return false;
}
}
abstract class SubMapIterator<T> implements Iterator<T>{
//抽象類,抽取迭代器的一些共性
TreeMap.Entry<K,V> lastReturned;
TreeMap.Entry<K,V> next;
final Object fenceKey;
//這個fenceKey就是相當於一個柵欄的意思,規定終止結點
int expectedModCount;
SubMapIterator(TreeMap.Entry<K,V> first, TreeMap.Entry<K,V> fence){
//構造器
expectedModCount = m.modCount;
lastReturned = null;
next = first;
fenceKey = fence == null ? UNBOUNDED : fence.key;
}
public final boolean hasNext(){
//判斷是否還有下一個結點
return next != null && next.key != fenceKey;
//如果next不爲null或者next的key不等於fenceKey則說明還有下一個結點
}
final TreeMap.Entry<K,V> nextEntry(){
//獲取下一個結點
TreeMap.Entry<K,V> e = next;
if(e == null || e.key == fenceKey)
throw new NoSuchElementException();
if(m.modCount != expectedModCount)
throw new ConcurrentModificationException();
next = successor(e);
lastReturned = e;
return e;
}
final TreeMap.Entry<K,V> prevEntry(){
//獲取上一個結點
TreeMap.Entry<K,V> e = next;
if(e == null || e.key == fenceKey)
throw new NoSuchElementException();
if(m.modCount != expectedModCount)
throw new ConcurrentModificationException();
next = predecessor(e);
lastReturned = e;
return e;
}
final void removeAscending(){
//刪除之後,可以繼續升序遍歷
if(lastReturned == null)
throw new IllegalStateException();
if(m.modCount != expectedModCount)
throw new ConcurrentModificationException();
if(lastReturned.left != null && lastReturned.right != null)
next = lastReturned;
m.deleteEnrty(lastReturned);
lastReturned = null;
expectedModCount = m.modCount;
}
final void removeDescending(){
//刪除之後,可以繼續降序遍歷
if(lastReturned == null)
throw new IllegalStateException();
if(m.modCount != expectedModCount)
throw new ConcurrentModificationException();
m.deleteEnrty(lastReturned);
lastReturned = null;
expectedModCount = m.modCount;
}
}
final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>>{
//SubMap的Entry升序迭代器,只支持升序遍歷
SubMapEntryIterator(TreeMap.Entry<K,V> first,TreeMap.Entry<K,V> fence){
//構造器
super(first,fence);
}
public Map.Entry<K,V> next(){
//下一個Entry
return nextEntry();
}
public void remove(){
//刪除操作,調用升序刪除
removeAscending();
}
}
final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>>{
//SubMap的Entry降序迭代器,只支持降序遍歷
DescendingKeyIterator(TreeMap.Entry<K,V> last,TreeMap.Entry<K,V> fence){
//構造器,起始結點是最後一個結點
super(last,fence);
}
public Map.Entry<K,V> next(){
//下一個Entry
return prevEntry();
}
public void remove(){
//刪除操作,調用降序刪除
removeDescending();
}
}
final class SubMapKeyIterator extends SubMapIterator<K> implements Spliterator<K>{
//SubMap的Key的升序迭代器,支持升序遍歷,還實現了分割器接口
SubMapKeyIterator(TreeMap.Entry<K,V> first,TreeMap.Entry<K,V> fence){
//構造器
super(first,fence);
}
public K next(){
//下一個key
return nextEntry().key;
}
public void remove(){
//刪除當前結點
removeAscending();
}
public Spliterator<K> trySplit(){
return null;
}
public void forEachRemaining(Consumer<? super K> action){
while(hasNext())
action.accept(next());
}
public boolean tryAdvance(Consumer<? super K> action){
if(hasNext()){
action.accept(next());
return true;
}
return false;
}
public long estimateSize(){
return Long.MAX_VALUE;
}
public int characteristics(){
return Spliterator.DISTINCT | Spliterator.ORDERED | Spliterator.SORTED;
}
public final Comparator<? super K> getComparator(){
//獲得比較器
return NavigableSubMap.this.comparator();
}
}
final class DescendingSubMapKeyIterator extends SubMapIterator<K> implements Spliterator<K>{
//SubMap中的Key的逆序迭代器,支持逆序遍歷
DescendingSubMapKeyIterator(TreeMap.Entry<K,V> last,TreeMap.Entry<K,V> fence){
//構造器
super(last,fence);
}
public K next(){
//下一個key
return prevEntry().key;
}
public void remove(){
//刪除當前結點
removeDescending();
}
public Spliterator<K> trySplit(){
return null;
}
public void forEachRemaining(Consumer<? super K> action){
while(hasNext())
action.accpet(next());
}
public boolean tryAdvance(Consumer<? super K> action){
if(hasNext()){
action.accept(next());
return true;
}
return false;
}
public long estimateSize(){
return Long.MAX_VALUE;
}
public int characteristics(){
return Spliterator.DISTINCT | Spliterator.ORDERED;
}
}
}
static final class AscendingSubMap<K,V> extends NavigableSubMap<K,V>{
//升序的SubMap,繼承於NavigableSbMap
private static final long serialVersionUID = 912986545866124060L;
//序列化標誌,用於反序列化
AscendingSubMap(TreeMap<K,V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi, boolean hiInclusive){
//構造器
super(m,fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
}
public Comparator<? super K> comparator(){
//比較器
return m.comparator();
}
public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive){
//獲取SubMap,fromInclusive表示是否包含fromKey,toInclusive表示是否包含toKey
if(!inRange(fromKey,fromInclusive))
throw new IllegalArgumentException("fromKey out of range");
if(!inRange(toKey, toInclusive))
throw new IllegalArgumentException("toKey out of range");
return new AscendingSubMap<>(m, false, fromKey, fromInclusive, false, toKey, toInclusive);
}
public NavigableMap<K,V> headMap(K toKey, boolean inclusive){
//獲取Map的頭部
if(!inRange(toKey, inclusive))
throw new IllegalArgumentException("toKey out of range");
return new AscendingSubMap<>(m, fromStart, lo, loInclusive, false, toKey, inclusive);
}
public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
//獲取Map的尾部
if(!inRange(fromKey, inclusive))
throw new IllegalArgumentException("fromKey out of range");
return new AscendingSubMap<>(m, false, fromKey, inclusive, toEnd, hi, hiInclusive);
}
public NavigableMap<K,V> descendingMap(){
//獲取相應的降序map
NavigableMap<K,V> mv = descendingMapView;
return (mv != null) ? mv : (descendingMapView = new DescendingSubMap<>(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive));
}
Iterator<K> keyIterator(){
//獲取升序key值迭代器
return new SubMapKeyIterator(absLowest(), absHighFence());
}
Spliterator<K> keySpliterator(){
//獲取key值的分割器
return new SubMapKeyIterator(absLowest(), absHighFence());
}
Iterator<K> descendingKeyIterator(){
//降序key迭代器
return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
}
final class AscendingEntrySetView extends EntrySetView{
//升序的EntrySet集合類
public Iterator<Map.Entry<K,V>> iterator(){
//升序迭代器
return new SubMapEntryIterator(absLowest(), absHighFence());
}
}
public Set<Map.Entry<K,V>> entrySet(){
//升序SubEntry集合
EntrySetView es = entrySetView;
return (es != null) ? es : (entrySetView = new AscendingEntrySetView());
}
TreeMap.Entry<K,V> subLowest(){
//獲取最小的結點
return absLowest();
}
TreeMap.Entry<K,V> subHighest(){
//獲取最大的結點
return absHighest();
}
TreeMap.Entry<K,V> subCeiling(K key){
//獲取不小於key值的最小結點
return absCeiling(key);
}
TreeMap.Entry<K,V> subHigher(K key){
//獲取大於key值的最小結點
return absHigher(key);
}
TreeMap.Enrty<K,V> subFloor(K key){
//獲取不大於key值的最大結點
return absFloor(key);
}
TreeMap.Entry<K,V> subLower(K key){
//獲取小於key值的最大結點
return absLower(key);
}
}
static final class DescendingSubMap<K,V> extends NavigableSubMap<K,V>{
//逆序的SubMap,繼承於NavigableSubMap
private static final long serialVersionUID = 912986545866120460L;
//序列化標誌,用於反序列化
DescendingSubMap(TreeMap<K,V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi, boolean hiInclusive){
//構造器
super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
}
//反轉比較器,將原始比較器反轉獲得
private final Comparator<? super K> reverseComparator = Collections.reverseOrder(m.comparator);
public Comparator<? super K> comparator(){
//獲取比較器
return reverseComparator;
}
public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, boolean toEnd, K hi, boolean hiInclusive){
//獲取子Map
if(!inRange(fromKey, fromInclusive))
throw new IllegalArgumentException("fromKey out of range");
if(!inRange(toKey, toInclusive))
throw new IllegalArgumentException("toKey out of range");
return new DescendingSubMap<>(m, false, toKey, toInclusive, false, fromKey, fromInclusive);
}
public NavigableMap<K,V> headMap(K toKey, boolean inclusive){
//獲取首map
if(!inRange(toKey, inclusive))
throw new IllegalArgumentException("toKey out of range");
return new DescendingSubMap<>(m, false, toKey, inclusive, toEnd, hi, hiInclusive);
}
public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
//獲取尾map
if(!inRange(fromKey, inclusive))
throw new IllegalArgumentException("fromKey out of range");
return new DescendingSubMap<>(m, fromStart, lo, loInclusive, false, fromKey, inclusive);
}
public NavigableMap<K,V> descendingMap(){
//獲取對應的降序map
NavigableMap<K,V> mv = descendingMapView;
return (mv != null) ? mv : (descendingMapView = new AscendingSubMap<>(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive));
}
Iterator<K> keyIterator(){
//獲得正序(降序)的key迭代器
return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
}
Spliterator<K> keySpliterator(){
//獲得key的分割器
return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
}
Iterator<K> descendingKeyIterator(){
//獲取對應的逆序(升序)的key迭代器
return new SubMapKeyIterator(absLowest(), absHighFence());
}
final class DescendingEntrySetView extends EntrySetView{
//降序的EntrySet集合類
public Iterator<Map.Entry<K,V>> iterator(){
//獲得逆序的Entry迭代器
return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
}
}
public Set<Map.Entry<K,V>> entrySet(){
//返回EntrySet集合
EntrySetView es = entrySetView;
return (es != null) ? es : (entrySetView = new DescendingEntrySetView());
}
//和AscendingSubMap類中類似,只是所有的功能都逆轉一下,就不再贅述
TreeMap.Entry<K,V> subLowest(){
return absHighest();
}
TreeMap.Entry<K,V> subHighest(){
return absLowest();
}
TreeMap.Entry<K,V> subCeiling(K key){
return absFloor(key);
}
TreeMap.Entry<K,V> subHigher(K key){
return absLower(key);
}
TreeMap.Entry<K,V> subFloor(K key){
return absCeiling(key);
}
TreeMap.Entry<K,V> subLower(K key){
return absHigher(key);
}
}
private class SubMap extends AbstractMap<K,V> implements SortedMap<K,V> java.io.Serializable{
//舊版本中的SubMap,新版本的java中沒有用到
private static final long serialVersionUID = -6520786458950516097L;
private boolean fromStart = false, toEnd = false;
private K fromKey, toKey;
private Object readResolve(){
return new AscendingSubMap<>(TreeMap.this, fromStart, fromKey, true, toEnd, toKey, false);
}
public Set<Map.Entry<K,V>> entrySet(){
throw new InternalError();
}
public K lastKey(){
throw new InternalError();
}
public K firstKey(){
throw new InternalError();
}
public SortedMap<K,V> subMap(K fromKey, K toKey){
throw new InternalError();
}
public SortedMap<K,V> headMap(K toKey){
throw new InternalError();
}
public SortedMap<K,V> tailMap(K fromKey){
throw new InternalError();
}
public Comparator<? super K> comparator(){
throw new InternalError();
}
}
//下面就是紅黑樹的功能實現
private static final boolean RED = false;
//紅色結點標誌
private static final boolean BLACK = true;
//黑色結點標誌
static final class Entry<K,V> implements Map.Entry<K,V>{
//紅黑樹結點類
//成員變量
K key;//key值
V value;//value值
Entry<K,V> left;//左孩子
Entry<K,V> right;//右孩子
Entry<K,V> parent;//父結點
boolean color = BLACK;//默認黑色結點
Entry(K key, V value, Entry<K,V> parent){
//構造器
this.key = key;
this.value = value;
this.parent = parent;
}
public K getKey(){
return key;
}
public V getValue(){
return value;
}
public V setValue(V value){
V oldValue = this.value;
this.value = value;
return oldValue;
}
public boolean equals(Object o){
//比較兩個結點是否一樣
if(!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
return valEquals(Key, e.getKey()) && valEquals(value,e.getValue());
}
public int hashCode(){
//重寫結點類的hashCode方法
int keyHash = (key == null ? 0 : key.hashCode());
int valueHash = (value == null ? 0 : value.hashCode());
return keyHash ^ valueHash;
}
public String toString(){
return key + "=" + value;
}
}
final Entry<K,V> getFirstEntry(){
//獲得頭結點,也就是最左結點,最小結點
Entry<K,V> p = root;
if(p != null)
while(p.left != null)
p = p.left;
return p;
}
final Entry<K,V> getLastEntry(){
//獲得尾結點,也就是最右結點,最大結點
Entry<K,V> p = root;
if(p != null)
while(p.right != null)
p = p.right;
return p;
}
static <K,V> TreeMap.Enrty<K,V> successor(Entry<K,V> t){
//尋找t結點中序遍歷的後繼結點
if(t == null)
return null;
else if(t.right != null){
Entry<K,V> p = t.right;
while(p.left != null)
p = p.left;
return p;
} else {
Entry<K,V> p = t.parent;
Entry<K,V> ch = t;
while(p != null && ch == p.right){
ch = p;
p = p.parent;
}
return p;
}
}
static <K,V> Entry<K,V> predecessor(Entry<K,V> t){
//尋找t結點中序遍歷的前繼結點
if(t == null)
return null;
else if(t.left != null){
Entry<K,V> p = t.left;
while(p.right != null)
p = p.right;
return p;
} else {
Entry<K,V> p = t.parent;
Entry<K,V> ch = t;
while(p != null && ch == p.left){
ch = p;
p = p.parent;
}
return p;
}
}
private static <K,V> boolean colorOf(Entry<K,V> p){
//獲得結點的顏色
return (p == null ? BLACK : p.color);
}
private static <K,V> Entry<K,V> parentOf(Entry<K,V> p){
//獲得結點的父結點
return (p == null ? null : p.parent);
}
private static <K,V> void setColor(Entry<K,V> p, boolean c){
//設置結點顏色
if(p != null)
p.color = c;
}
private static <K,V> Entry<K,V> leftOf(Entry<K,V> p){
//獲得結點的左孩子
return (p == null) ? null : p.left;
}
private static <K,V> Entry<K,V> rightOf(Entry<K,V> p){
//獲得結點的右孩子
return (p == null) ? null : p.right;
}
private void rotateLeft(Entry<K,V> p){
//左旋操作,即以p結點作爲旋點,將p結點向左下旋轉
//將p結點的右孩子r向左上旋轉,將p作爲r的左孩子,將
//r作爲p的父結點
if(p != null){
Entry<K,V> r = p.right;
//首先取p結點的右孩子
p.right = r.left;
//再將曾經p的右孩子的左孩子設置爲現在p的右孩子
if(r.left != null)
r.left.parent = p;
//如果r的左孩子不爲空,則將其p作爲其父結點
r.parent = p.parent;
//再將p的父結點設置爲r的父結點
if(p.parent == null)
root = r;
//如果p的父結點爲空,則說明原來的p爲根節點,則現在將r設置爲根節點
else if(p.parent.left == p)
p.parent.left = r;
//否則,說明p不是根節點,則判斷它如果是左孩子,則將r設置爲p父結點的左孩子
else
p.parent.right = r;
//否則,將r作爲p父結點的右孩子
r.left = p;
//再將p作爲r的左孩子
p.parent = r;
//將r作爲p的父結點
}
}
private void rotateRight(Entry<K,V> p){
//右旋操作,將p作爲旋點,將p結點向右下旋轉
//將p結點的左孩子l向右上旋轉代替p結點,再將
//p作爲l的右孩子,將l作爲p的父結點
if(p != null){
Entry<K,V> l = p.left;
p.left = l.right;
if(l.right != null)
l.right.parent = p;
l.parent = p.parent;
if(p.parent == null)
root = l;
else if(p.parent.right == p)
p.parent.right = l;
else
p.parent.left = l;
l.right = p;
p.parent = l;
}
}
private void fixAfterInsertion(Entry<K,V> x){
//對插入新節點x後的整棵紅黑樹進行調整
x.color = RED;
//新插入的結點默認爲紅色
//首先聲明,如果x爲空或者新插入的x結點是根節點或者x
//結點的父結點是黑色結點,則直接插入即可,不需要調整
//此方法是對其他情況進行調整的
while(x != null && x !=root && x.parent.color == RED){
if(parentOf(x) == leftOf(parentOf(parentOf(x)))){
//如果x的父結點是其祖父結點的左孩子
Entry<K,V> y = rightOf(parentOf(parent(x)));
//首先取出x的叔叔結點,下面則是根據其叔叔結點的情況來進行調整
if(colorOf(y) == RED){
//如果叔叔結點也是紅色的,則符合第三種情況,此時需要將叔叔結點
//和父結點都染黑,再將祖父結點染紅即可,再由下向上進行調整
setColor(parentOf(x),BLACK);
setColor(y,BLACK);
setColor(parentOf(parentOf(x)), RED);
x = parentOf(parentOf(x));
} else {
//否則說明叔叔結點是黑色的
if(x == rightOf(parentOf(x))){
//再判斷x是否爲父結點的右孩子,如果是,則符合第四種情況
x = parentOf(x);//先將x定位於它的父結點
rotateLeft(x);//再以x結點,也就是原新插入結點的父結點爲旋點進行左旋
}
//如果上一個if語句執行,則說明是第四種情況,否則是第五種情況,這兩種情況都要進行右旋
setColor(parentOf(x), BLACK);//先將x結點的父結點染黑
setColor(parentOf(parentOf(x)),RED);//再將其祖父結點染紅
rotateRight(parentOf(parentOf(x)));//再將其祖父結點作爲旋點進行右旋
}
} else {
//如果x的父結點是其祖父結點的右孩子,則鏡像操作
Entry<K,V> y = leftOf(parentOf(parentOf(parentOf(x))));
if(color(y) == RED){
setColor(parentOf(x), BLACK);
setColor(y,BLACK);
setColor(parentOf(parentOf(x)),RED);
x = parentOf(parentOf(x));
}else {
if(x == leftOf(parentOf(x))){
x = parentOf(x);
rotateRight(x);
}
setColor(parentOf(x), BLACK);
setColor(parnetOf(parentOf(x)),RED);
rotateRight(parentOf(parentOf(x)));
}
}
}
root.color = BLACK;
//最後確保根節點顏色是黑色的
}
private void deleteEntry(Entry<K,V> p){
//刪除結點
modCount++;
size--;
if(p.left != null && p.right != null){
//如果要刪除結點既有左孩子又有右孩子,則不能直接刪除
Entry<K,V> s = successor(p);
//首先尋找到它的中序遍歷的後繼結點
p.key = s.key;
p.value = s.value;
p = s;
//再用s將p覆蓋,此時p已經刪除了,但是紅黑樹中有兩個s結點,因此需要將
//多餘的那個邊緣結點s刪除,注意此處並沒有覆蓋結點的顏色
}
Entry<K,V> replacement = (p.left != null ? p.left : p.right);
//獲取被刪除結點p的替代結點,如果有左孩子則用左孩子替代,否則用右孩子替代,如果都沒有,則爲null
if(replacement != null){
//如果替代結點不爲null,則將p的父結點作爲替代結點的父結點
replacement.parent = p.parent;
if(p.parent == null)
root = replacement;
//如果p的父結點爲Null,則說明p爲根節點,因此將替代結點作爲根節點
else if(p == p.parent.left)
p.parent.left = replacement;
else
p.parent.right = replacemnet;
//否則將替代結點作爲p父結點的左孩子或右孩子
p.left = p.right = p.parent = null;
//再將p結點的所有指針置空,此時已經將p結點刪除了,方便GC回收
if(p.color == BLACK)
fixAfterDeletion(replacement);
//如果被刪除的結點是紅色的,則不需要調整,否則需要調整
} else if (p.parent == null){
//否則替代結點爲空,並且其父結點爲空,說明它是孤立的根節點,因此將根置空即可
root == null;
} else {
//否則說明替代結點爲空,p結點沒有左右孩子
if(p.color == BLACK)
fixAfterDeletion(p);
//如果p是黑色的,先對紅黑樹進行調整
if(p.parent != null){
//再將p結點刪除
if(p == p.parent.left)
p.parent.left = null;
else if(p == p.parent.right)
p.parent.right = null;
p.parent = null;
}
}
}
private void fixAfterDeletion(Entry<K,V> x){
//刪除調整
//如果刪除的結點是紅色的或者爲根節點,則直接刪除即可
while(x != root && colorOf(x) == BLACK){
if(x == leftOf(parentOf(x))){
//否則先判斷刪除的x是否是其父結點的左孩子
Entry<K,V> sib = rightOf(parentOf(x));
//先獲取其兄弟結點
if(colorOf(sib) == RED){
//如果其兄弟結點是紅結點,則屬於第二種情況
setColor(sib,BLACK);//將其兄弟結點染黑
setColor(parentOf(x),RED);//將其父親節點染紅
rotateLeft(parentOf(x));//再以其父結點爲旋點進行左旋轉
sib = rightOf(parentOf(x));//再將sib設置爲被刪除結點的父結點的右孩子
}
if(colorOf(leftOf(sib)) == BLACK && colorOf(rightOf(sib)) == BLACK){
//此處有兩種可能,如果上面的if語句執行了,說明兄弟結點是紅色的,經過
//上面的處理,再加上將父結點的右孩子染紅,再從下往上調整即可
//還有一種可能是上面的if語句沒有執行,說明兄弟結點爲黑色且兄弟結點的
//孩子也都爲黑色,則屬於第三種情況,那麼將兄弟結點染紅,再從下往上調整即可
setColor(sib,RED);
x = parentOf(x);
} else {
//否則就說明兄弟結點是黑色的,且其子結點至少有一個是紅色的
if(colorOf(rightOf(sib)) == BLACK){
//如果兄弟結點的右孩子是黑色的,則說明其左孩子是紅色的
setColor(leftOf(sib), BLACK);//先將其左孩子染黑
setColor(sib,RED);//再將自己染紅
rotateRight(sib);//以自己爲旋點進行右旋
sib = rightOf(parentOf(x));//再將sib設置爲被刪除結點x的父結點
//即將原來x的兄弟結點的左孩子設置爲x的父結點的右孩子sib
}
//此時有兩種情況,一種是執行了上面的if語句,說明是第四種情況,兄弟結點爲黑
//其左孩子爲紅,右孩子爲黑。
//還有一種情況是沒有執行上面的if語句,則是第五種情況,兄弟結點爲黑,其右孩子爲
//紅,左孩子可紅可黑
setColor(sib,colorOf(parentOf(x)));//將sib染成x的父結點一樣的顏色
setColor(parentOf(x),BLACK);//再將x的父結點染成黑色
setColor(rightOf(sib),BLACK);//再將sib的右孩子染成黑色
rotateLeft(parentOf(x));//以x的父結點爲旋點向左旋轉
x = root;//將x設置爲根節點,調整完畢
}
}else {
//否則說明需要刪除的x是其父結點的右孩子,鏡像操作
Entry<K,V> sib = leftOf(parent(x));
if(colorOf(sib) == RED){
setColor(sib,BLACK);
setColor(parentOf(x),RED);
rotateRight(parentOf(x));
sib = leftOf(parent(x));
}
if(colorOf(rightOf(sib)) == BLACK && colorOf(leftOf(sib)) == BLACK){
setColor(sib,RED);
x = parentOf(x);
}else{
if(colorOf(leftOf(sib)) == BLACK){
setColor(rightOf(sib),BLACK);
setColor(sib,RED);
rotateLeft(sib);
sib = leftOf(parentOf(x));
}
setColor(sib,colorOf(parentOf(x)));
setColor(parentOf(x),BLACK);
setColor(leftOf(sib),BLACK);
rotateRight(parentOf(x));
x = root;
}
}
}
setColor(x,BLACK);//將根節點設置爲黑色
}
private static final long serialVersionUID = 919286545866124006L;
//序列化標誌,用於反序列化
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{
//寫出操作
s.defaultWriteObject();
s.writeInt(size);
for(Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext();){
//使用迭代器進行for循環寫出
Map.Entry<K,V> e = i.next();
s.writeObject(e.getKey());
s.writeObject(e.getValue());
}
}
private void readObject(final java.io.ObjectInputStream s) throws java.io.IOException,ClassNotFoundException{
//讀入操作
s.defaultReadObject();
int size = s.readInt();
buildFromSorted(size,null,s,null);
//重建樹
}
void readTreeSet(int size,java.io.ObjectInputStream s, V defaultVal) throws java.io.IOException,ClassNotFoundException{
//讀取操作
buildFromSorted(size,null,s,defaultVal);
}
void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal){
//向TreeSet中增加一個set集合
try{
buildFromSorted(set.size(),set.iterator(),null,defaultVal);
}catch(java.io.IOException cannotHappen){
}catch(ClassNotFoundException cannotHappen){
}
}
private void buildFromSorted(int size, Iterator<?> it, java.io.ObjectInputStream str, V defaultVal) throws java.io.IOException{
//根據一個已經排好序的map創建一個TreeMap
this.size = size;
root = buildFromSorted(0,0,size - 1, computeRedLevel(size),it, str, defaultVal);
}
@SuppressWarnings("unchecked")
private final Entry<K,V> buildFromSorted(int level, int lo, int hi, int redlevel, Iterator<?> it, java.io.ObjectInputStream str, V defaultVal)
throws java.io.IOException,ClassNotFoundException{
//根據一個已經排好序的map創建一個TreeMap,其中level表示結點所在的層次,lo表示第一個結點
//hi表示最後一個結點,redlevel表示紅色結點層次,it表示迭代器,str表示傳入的讀取信息,defaultVal表示默認value值
//以遞歸方式還原紅黑樹
if(hi < lo)
return null;
//如果傳進來的最後一個結點比第一個結點還要小,結束遞歸,返回null
int mid = (lo + hi) >>> 1;
//否則先算出其中間值
Entry<K,V> left = null;
//定義一個左結點爲null
if(lo < mid)
left = buildFromSorted(level + 1, lo, mid - 1, redLevel, it, str, defaultVal);
//如果第一個結點小於中間結點,則遞歸調用獲取mid的左孩子
//獲取middle的key值和value值
K key;
V value;
if(it != null){
//如果有迭代器,就從迭代器中獲取
if(defaultVal == null){
//如果默認值爲空,則從迭代器中獲取key和value
Map.Entry<?,?> entry = (Map.Entry<?,?>)it.next();
key = (K)entry.getKey();
value = (V)entry.getValue();
} else {
//否則,從迭代器中獲取key,且將value設置爲默認值
key = (K)it.next();
value = defaultVal;
}
} else {
//如果沒有迭代器,則讀取出key和value
key = (K) str.readObject();
value = (defaultVal != null ? defaultVal : (V) str.readObject());
}
//創建middle結點,將key值和value值賦進去
Entry<K,V> middle = new Entry<>(key,value,null);
if(level == redLevel)
middle.color = RED;
//如果當前結點深度等於紅色結點深度,則將結點顏色染紅
//因爲是建樹的結點是按照一定順序依次一層一層建立起來的
//所以只要確定最後一層是紅色結點,其他的都是黑色結點就
//是紅黑樹了,而不是像之前那樣隨機的插入,才需要調整樹
if(left != null){
middle.left = left;
left.parent = middle;
//將middle設置爲left的父結點,將left設置爲middle的左孩子結點
}
if(mid < hi){
//如果mid小於最後一個結點,則遞歸調用創建mid的右孩子
Entry<K,V> right = buildFromSorted(level + 1, mid + 1, hi, redLevel, it, str, defaultVal);
middle.right = right;
right.parent = middle;
}
return middle;
//返回middle結點作爲父結點
}
private static int computeRedLevel(int sz){
//計算結點樹爲sz的最大深度,也就是紅色結點的深度值
int level = 0;
for(int m = sz - 1; m >= 0; m = m / 2 - 1)
level++;
return level;
}
static <K> Spliterator<K> keySpliteratorFor(Navigable<K,?> m){
//根據m的種類獲得m的相應分割器
if(m instanceof TreeMap){
@SuppressWarnings("unchecked")
TreeMap<K,Object> t = (TreeMap<K,Object>) m;
return t.keySpliterator();
}
if(m instanceof DescendingSubMap){
@SuppressWarnings("unchecked")
DescendingSubMap<K,?> dm = (DescendingSubMap<K,?>) m;
TreeMap<K,?> tm = dm.m;
if(dm == tm.descendingMap){
@SuppressWarnings("unchecked")
TreeMap<K,Object> t = (TreeMap<K,Object>) tm;
return t.descendingKeySpliterator();
}
}
@SuppressWarnings("unchecked")
NavigableSubMap<K,?> sm = (NavigableSubMap<K,?>) m;
return sm.keySpliterator();
}
final Spliterator<K> keySpliterator(){
//獲取key分割器
return new KeySpliterator<K>(this,null,null, 0, -1, 0);
}
final Spliterator<K> descendingKeySpliterator(){
//獲取key的逆序分割器
return new DescendingKeySpliterator<K,V>(this, null, null, 0, -2, 0);
}
static class TreeMapSliterator<K,V>{
//靜態內部類,分割器
final TreeMap<K,V> tree;
TreeMap.Entry<K,V> current;
TreeMap.Entry<K,V> fence;
int side;
int est;//表示爲什麼類型的分隔,0表示從父結點開始分隔,-1表示左分隔,+1表示右分隔
int expectedModCount;
TreeMapSpliterator(TreeMap<K,V> tree, TreeMap.Entry<K,V> origin, TreeMap.Entry<K,V> fence, int side, int est, int expectedModCount){
//構造器
this.tree = tree;
this.current = origin;
this.fence = fence;
this.side = side;
this.est = est;
this.expectedModCount = expectedModCount;
}
final int getEstimate(){
int s;
TreeMap<K,V> t;
if((s = est) < 0){
if((t = tree) != null){
current = (s == -1) ? t.getFirstEntry() : t.getLastEntry();
s = est = t.size;
expectedModCount = t.modCount;
}
else
s = est = 0;
}
return s;
}
public final long estimateSize(){
return (long)getEstimate();
}
}
static final class KeySpliterator<K,V> extends TreeMapSpliterator<K,V> implements Spliterator<K>{
//key值的分割器
keySpliterator(TreeMap<K,V> tree, TreeMap.Entry<K,V> origin, TreeMap.Entry<K,V> fence, int side, int est, int expectedModCount){
super(tree,origin, fence, side, est, expectedModCount);
}
public KeySpliterator<K,V> trySplit(){
if(est < 0)
getEstimate();
int d = side;
TreeMap.Entry<K,V> e = current, f = fence;
s = ((e == null || e == f) ? null :
(d == 0) ? tree.root :
(d > 0) ? e.right :
(d < 0 && f != null) ? f.left :
null);
if(s != null && s != e && s != f && tree.compare(e.key, s.key) < 0){
side = 1;
return new KeySpliterator<>(tree, e, current = s, -1, est >>>= 1, expectedModCount);
}
return null;
}
public void forEachRemaining(Consumer<? super K> action){
if(action == null)
throw new NullPointerException();
if(est < 0)
getEstimate();
TreeMap.Entry<K,V> f = fence, e, p, pl;
if((e = current) != null && e != f){
current = f;
do{
action.accept(e.key);
if((p = e.right) != null){
while((pl = p.left) != null)
p = pl;
}else{
while((p = e.parent) != null && e == p.right)
e = p;
}
}while((e = p) != null && e != f);
if(tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
public boolean tryAdvance(Consumer<? super K> action){
TreeMap.Entry<K,V> e;
if(action == null)
throw new NullPointerException();
if(est < 0)
getEstimate();
if((e = current) == null || e = fence)
return false;
current = successor(e);
action.accept(e.key);
if(tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
public int characteristics(){
return (side == 0 ? Spliterator.SIZED : 0) | Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED;
}
public final Comparator<? super K> getComparator(){
return tree.comparator;
}
}
static final class DescendingKeySpliterator<K,V> extends TreeMapSpliterator<K,V> implements Spliterator<K>{
//key的逆序分割器
DescendingKeySpliterator(TreeMap<K,V> tree, TreeMap.Entry<K,V> origin, TreeMap.Entry<K,V> fence, int side, int est, int expectedModCount){
super(tree, origin, fence, side, est, expectedModCount);
}
public DescendingKeySpliterator<K,V> trySplit(){
if(est < 0)
getEstimate();
int d = side;
TreeMap.Entry<K,V> e = current, f = fence,
s = ((e == null || e == f) ? null :
(d == 0) ? tree.root :
(d < 0) ? e.left :
(d > 0 && f != null) ? f.right :
null);
if(s != null && s != e && s != f && tree.compare(e.key, s.key) > 0){
side = 1;
return new DescendingKeySpliterator<>(tree, e, current = s, -1, est >>>= 1, expectedModCount);
}
return null;
}
public forEachRemaining(Consumer<? super K> action){
if(action == null)
throw new NullPointerException();
if(est < 0)
getEstimate();
TreeMap.Entry<K,V> f = fence, e, p, pr;
if((e = current) != null && e != f){
current = f;
do{
action.accept(e.key);
if((p = e.left) != null){
while((pr = p.right) != null)
p = pr;
}
else{
while((p = e.parent) != null && e == p.left)
e = p;
}
}while((e = p) != null && e != f);
if(tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
public boolean tryAdvance(Consumer<? super K> action){
TreeMap.Entry<K,V> e;
if(action == null)
throw new NullPointerException();
if(est < 0)
getEstimate();
if((e = current) == null || e == fence)
return false;
current = predecessor(e);
action.accept(e.key);
if(tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
public int characteristics(){
return (side == 0 ? Spliterator.SIZED : 0) | Spliterator.DISTINCT | Spliterator.ORDERED;
}
}
static final class ValueSpliterator<K,V> extends TreeMapSpliterator<K,V> implements Spliterator<V>{
//value分割器
ValueSpliterator(TreeMap<K,V> tree, TreeMap.Entry<K,V> origin, TreeMap.Entry<K,V> fence, int side, int est, int expectedModCount){
super(tree, origin, fence, side, est, expectedModCount);
}
public ValueSpliterator<K,V> trySplit(){
if(est < 0)
getEstimate();
int d = side;
TreeMap.Entry<K,V> e = current, f = fence,
s = ((e == null || e == f) ? null :
(d == 0) ? tree.root :
(d > 0) ? e.right :
(d < 0 && f != null) ? f.left :
null);
if(s != null && s != e && s != f && tree.compare(e.key, s.key) < 0){
side = 1;
return new ValueSpliterator<>(tree, e, current = s, -1, est >>>= 1, expectedModCount);
}
return null;
}
public void forEachRemaining(Consumer<? super V> action){
if(action == null)
throw new NullPointerException();
if(est < 0)
getEstimate();
TreeMap.Entry<K,V> f = fence, e, p, pl;
if((e == current) != null && e != f){
current = f;
do{
action.accept(e.value);
if((p = e.right) != null){
while((pl = p.left) != null)
p = pl;
}else{
while((p = e.parent) != null && e == p.right)
e = p;
}
}while((e = p) != null && e != f);
if(tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
public boolean tryAdvance(Consumer<? super V> action){
TreeMap.Entry<K,V> e;
if(action == null)
throw new NullPointerException();
if(est < 0)
getEstimate();
if((e = current) == null || e == fence)
return false;
current = successor(e);
action.accept(e.value);
if(tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
public int characteristics(){
return (side == 0 ? Spliterator.SIZED : 0) | Spliterator.ORDERED;
}
}
static final class EntrySpliterator<K,V> extends TreeMapSpliterator<K,V> implements Spliterator<Map.Entry<K,V>>{
//Entry分割器
EntrySpliterator(TreeMap<K,V> tree, TreeMap.Entry<K,V> origin, TreeMap.Entry<K,V> fence, int side, int est, int expectedModCount){
super(tree,origin,fence, side, est, expectedModCount);
}
public EntrySpliterator<K,V> trySplit(){
if(est < 0)
getEstimate();
int d = side;
TreeMap.Entry<K,V> s = current, f = fence,
s = ((e == null || e == f) ? null :
(d == 0) ? tree.root :
(d > 0) ? e.right :
(d < 0 && f != null) ? f.left :
null);
if(s != null && s != e && s != f && tree.compare(e.key,s.key) < 0){
side = 1;
return new EntrySpliterator<>(tree, e, current = s, -1, est >>>= 1, expectedModCount);
}
return null;
}
public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action){
if(action == null)
throw new NullPointerException();
if(est < 0)
getEstimate();
TreeMap.Entry<K,V> f = fence, e, p, pl;
if((e = current) != null && e != f){
current = f;
do{
action.accept(e);
if((e = e.right) != null){
while((pl = p.left) != null)
p = pl;
}else{
while((p = e.parent) != null && e == p.right)
e = p;
}
}while((e = p) != null && e != f);
if(tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action){
TreeMap.Entry<K,V> e;
if(action == null)
throw new NullPointerException();
if(est < 0)
getEstimate();
if((e = current) == null || e == fence)
return false;
current = successor(e);
action.accept(e);
if(tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
public int characteristics(){
return (side == 0 ? Spliterator.SIZED : 0) | Spliertaor.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED;
}
@Override
public Comparator<Map.Entry<K,V>> getComparator(){
//重寫getComparator方法
if(tree.comparator != null){
return Map.Entry.comparingByKey(tree.comparator);
}else{
return (Comparator<Map.Entry<K,V>> & Serializable) (e1,e2) ->{
@SuppressWarnings("unchecked")
Comparable<? super K> k1 = (Comparable<? super K>) e1.getKey();
return k1.compareTo(e2.getKey());
}
}
}
}
}
參考資料: