java集合12--TreeMap源碼詳解

轉載地址:http://blog.csdn.net/wangxiaotongfan/article/details/51345561

概要

這一章,我們對TreeMap進行學習。 
我們先對TreeMap有個整體認識,然後再學習它的源碼,最後再通過實例來學會使用TreeMap。內容包括: 
第1部分 TreeMap介紹 
第2部分 TreeMap數據結構 
第3部分 TreeMap源碼解析(基於JDK1.6.0_45) 
第4部分 TreeMap遍歷方式 
第5部分 TreeMap示例

第1部分 TreeMap介紹

TreeMap 簡介

TreeMap 是一個有序的key-value集合,它是通過紅黑樹實現的。 
TreeMap 繼承於AbstractMap,所以它是一個Map,即一個key-value集合。 
TreeMap 實現了NavigableMap接口,意味着它支持一系列的導航方法。比如返回有序的key集合。 
TreeMap 實現了Cloneable接口,意味着它能被克隆。 
TreeMap 實現了java.io.Serializable接口,意味着它支持序列化。

TreeMap基於紅黑樹(Red-Black tree)實現。該映射根據其鍵的自然順序進行排序,或者根據創建映射時提供的 Comparator 進行排序,具體取決於使用的構造方法。 
TreeMap的基本操作 containsKey、get、put 和 remove 的時間複雜度是 log(n) 。 
另外,TreeMap是非同步的。 它的iterator 方法返回的迭代器是fail-fastl的。

TreeMap的構造函數
// 默認構造函數。使用該構造函數,TreeMap中的元素按照自然排序進行排列。
TreeMap()

// 創建的TreeMap包含Map
TreeMap(Map<? extends K, ? extends V> copyFrom)

// 指定Tree的比較器
TreeMap(Comparator<? super K> comparator)

// 創建的TreeSet包含copyFrom
TreeMap(SortedMap<K, ? extends V> copyFrom)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

TreeMap的API
Entry<K, V>                ceilingEntry(K key)
K                          ceilingKey(K key)
void                       clear()
Object                     clone()
Comparator<? super K>      comparator()
boolean                    containsKey(Object key)
NavigableSet<K>            descendingKeySet()
NavigableMap<K, V>         descendingMap()
Set<Entry<K, V>>           entrySet()
Entry<K, V>                firstEntry()
K                          firstKey()
Entry<K, V>                floorEntry(K key)
K                          floorKey(K key)
V                          get(Object key)
NavigableMap<K, V>         headMap(K to, boolean inclusive)
SortedMap<K, V>            headMap(K toExclusive)
Entry<K, V>                higherEntry(K key)
K                          higherKey(K key)
boolean                    isEmpty()
Set<K>                     keySet()
Entry<K, V>                lastEntry()
K                          lastKey()
Entry<K, V>                lowerEntry(K key)
K                          lowerKey(K key)
NavigableSet<K>            navigableKeySet()
Entry<K, V>                pollFirstEntry()
Entry<K, V>                pollLastEntry()
V                          put(K key, V value)
V                          remove(Object key)
int                        size()
SortedMap<K, V>            subMap(K fromInclusive, K toExclusive)
NavigableMap<K, V>         subMap(K from, boolean fromInclusive, K to, boolean toInclusive)
NavigableMap<K, V>         tailMap(K from, boolean inclusive)
SortedMap<K, V>            tailMap(K fromInclusive)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

第2部分 TreeMap數據結構

TreeMap的繼承關係
java.lang.Object
   ↳     java.util.AbstractMap<K, V>
         ↳     java.util.TreeMap<K, V>

public class TreeMap<K,V>
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable {}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

TreeMap與Map關係如下圖:

從圖中可以看出: 
(01) TreeMap實現繼承於AbstractMap,並且實現了NavigableMap接口。 
(02) TreeMap的本質是R-B Tree(紅黑樹),它包含幾個重要的成員變量: root, size, comparator。 
  root 是紅黑數的根節點。它是Entry類型,Entry是紅黑數的節點,它包含了紅黑數的6個基本組成成分:key(鍵)、value(值)、left(左孩子)、right(右孩子)、parent(父節點)、color(顏色)。Entry節點根據key進行排序,Entry節點包含的內容爲value。 
  紅黑數排序時,根據Entry中的key進行排序;Entry中的key比較大小是根據比較器comparator來進行判斷的。 
  size是紅黑數中節點的個數。

關於紅黑數的具體算法,請參考”紅黑樹(一) 原理和算法詳細介紹”。

第3部分 TreeMap源碼解析(基於JDK1.6.0_45)

爲了更瞭解TreeMap的原理,下面對TreeMap源碼代碼作出分析。我們先給出源碼內容,後面再對源碼進行詳細說明,當然,源碼內容中也包含了詳細的代碼註釋。讀者閱讀的時候,建議先看後面的說明,先建立一個整體印象;之後再閱讀源碼。

   1 package java.util;
   2 
   3 public class TreeMap<K,V>
   4 extends AbstractMap<K,V>
   5 implements NavigableMap<K,V>, Cloneable, java.io.Serializable
   6 {
   7 
   8     // 比較器。用來給TreeMap排序
   9     private final Comparator<? super K> comparator;
  10 
  11     // TreeMap是紅黑樹實現的,root是紅黑書的根節點
  12     private transient Entry<K,V> root = null;
  13 
  14     // 紅黑樹的節點總數
  15     private transient int size = 0;
  16 
  17     // 記錄紅黑樹的修改次數
  18     private transient int modCount = 0;
  19 
  20     // 默認構造函數
  21     public TreeMap() {
  22         comparator = null;
  23     }
  24 
  25     // 帶比較器的構造函數
  26     public TreeMap(Comparator<? super K> comparator) {
  27         this.comparator = comparator;
  28     }
  29 
  30     // 帶Map的構造函數,Map會成爲TreeMap的子集
  31     public TreeMap(Map<? extends K, ? extends V> m) {
  32         comparator = null;
  33         putAll(m);
  34     }
  35 
  36     // 帶SortedMap的構造函數,SortedMap會成爲TreeMap的子集
  37     public TreeMap(SortedMap<K, ? extends V> m) {
  38         comparator = m.comparator();
  39         try {
  40             buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
  41         } catch (java.io.IOException cannotHappen) {
  42         } catch (ClassNotFoundException cannotHappen) {
  43         }
  44     }
  45 
  46     public int size() {
  47         return size;
  48     }
  49 
  50     // 返回TreeMap中是否保護“鍵(key)”
  51     public boolean containsKey(Object key) {
  52         return getEntry(key) != null;
  53     }
  54 
  55     // 返回TreeMap中是否保護"值(value)"
  56     public boolean containsValue(Object value) {
  57         // getFirstEntry() 是返回紅黑樹的第一個節點
  58         // successor(e) 是獲取節點e的後繼節點
  59         for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
  60             if (valEquals(value, e.value))
  61                 return true;
  62         return false;
  63     }
  64 
  65     // 獲取“鍵(key)”對應的“值(value)”
  66     public V get(Object key) {
  67         // 獲取“鍵”爲key的節點(p)
  68         Entry<K,V> p = getEntry(key);
  69         // 若節點(p)爲null,返回null;否則,返回節點對應的值
  70         return (p==null ? null : p.value);
  71     }
  72 
  73     public Comparator<? super K> comparator() {
  74         return comparator;
  75     }
  76 
  77     // 獲取第一個節點對應的key
  78     public K firstKey() {
  79         return key(getFirstEntry());
  80     }
  81 
  82     // 獲取最後一個節點對應的key
  83     public K lastKey() {
  84         return key(getLastEntry());
  85     }
  86 
  87     // 將map中的全部節點添加到TreeMap中
  88     public void putAll(Map<? extends K, ? extends V> map) {
  89         // 獲取map的大小
  90         int mapSize = map.size();
  91         // 如果TreeMap的大小是0,且map的大小不是0,且map是已排序的“key-value對”
  92         if (size==0 && mapSize!=0 && map instanceof SortedMap) {
  93             Comparator c = ((SortedMap)map).comparator();
  94             // 如果TreeMap和map的比較器相等;
  95             // 則將map的元素全部拷貝到TreeMap中,然後返回!
  96             if (c == comparator || (c != null && c.equals(comparator))) {
  97                 ++modCount;
  98                 try {
  99                     buildFromSorted(mapSize, map.entrySet().iterator(),
 100                                 null, null);
 101                 } catch (java.io.IOException cannotHappen) {
 102                 } catch (ClassNotFoundException cannotHappen) {
 103                 }
 104                 return;
 105             }
 106         }
 107         // 調用AbstractMap中的putAll();
 108         // AbstractMap中的putAll()又會調用到TreeMap的put()
 109         super.putAll(map);
 110     }
 111 
 112     // 獲取TreeMap中“鍵”爲key的節點
 113     final Entry<K,V> getEntry(Object key) {
 114         // 若“比較器”爲null,則通過getEntryUsingComparator()獲取“鍵”爲key的節點
 115         if (comparator != null)
 116             return getEntryUsingComparator(key);
 117         if (key == null)
 118             throw new NullPointerException();
 119         Comparable<? super K> k = (Comparable<? super K>) key;
 120         // 將p設爲根節點
 121         Entry<K,V> p = root;
 122         while (p != null) {
 123             int cmp = k.compareTo(p.key);
 124             // 若“p的key” < key,則p=“p的左孩子”
 125             if (cmp < 0)
 126                 p = p.left;
 127             // 若“p的key” > key,則p=“p的左孩子”
 128             else if (cmp > 0)
 129                 p = p.right;
 130             // 若“p的key” = key,則返回節點p
 131             else
 132                 return p;
 133         }
 134         return null;
 135     }
 136 
 137     // 獲取TreeMap中“鍵”爲key的節點(對應TreeMap的比較器不是null的情況)
 138     final Entry<K,V> getEntryUsingComparator(Object key) {
 139         K k = (K) key;
 140         Comparator<? super K> cpr = comparator;
 141         if (cpr != null) {
 142             // 將p設爲根節點
 143             Entry<K,V> p = root;
 144             while (p != null) {
 145                 int cmp = cpr.compare(k, p.key);
 146                 // 若“p的key” < key,則p=“p的左孩子”
 147                 if (cmp < 0)
 148                     p = p.left;
 149                 // 若“p的key” > key,則p=“p的左孩子”
 150                 else if (cmp > 0)
 151                     p = p.right;
 152                 // 若“p的key” = key,則返回節點p
 153                 else
 154                     return p;
 155             }
 156         }
 157         return null;
 158     }
 159 
 160     // 獲取TreeMap中不小於key的最小的節點;
 161     // 若不存在(即TreeMap中所有節點的鍵都比key大),就返回null
 162     final Entry<K,V> getCeilingEntry(K key) {
 163         Entry<K,V> p = root;
 164         while (p != null) {
 165             int cmp = compare(key, p.key);
 166             // 情況一:若“p的key” > key。
 167             // 若 p 存在左孩子,則設 p=“p的左孩子”;
 168             // 否則,返回p
 169             if (cmp < 0) {
 170                 if (p.left != null)
 171                     p = p.left;
 172                 else
 173                     return p;
 174             // 情況二:若“p的key” < key。
 175             } else if (cmp > 0) {
 176                 // 若 p 存在右孩子,則設 p=“p的右孩子”
 177                 if (p.right != null) {
 178                     p = p.right;
 179                 } else {
 180                     // 若 p 不存在右孩子,則找出 p 的後繼節點,並返回
 181                     // 注意:這裏返回的 “p的後繼節點”有2種可能性:第一,null;第二,TreeMap中大於key的最小的節點。
 182                     //   理解這一點的核心是,getCeilingEntry是從root開始遍歷的。
 183                     //   若getCeilingEntry能走到這一步,那麼,它之前“已經遍歷過的節點的key”都 > key。
 184                     //   能理解上面所說的,那麼就很容易明白,爲什麼“p的後繼節點”又2種可能性了。
 185                     Entry<K,V> parent = p.parent;
 186                     Entry<K,V> ch = p;
 187                     while (parent != null && ch == parent.right) {
 188                         ch = parent;
 189                         parent = parent.parent;
 190                     }
 191                     return parent;
 192                 }
 193             // 情況三:若“p的key” = key。
 194             } else
 195                 return p;
 196         }
 197         return null;
 198     }
 199 
 200     // 獲取TreeMap中不大於key的最大的節點;
 201     // 若不存在(即TreeMap中所有節點的鍵都比key小),就返回null
 202     // getFloorEntry的原理和getCeilingEntry類似,這裏不再多說。
 203     final Entry<K,V> getFloorEntry(K key) {
 204         Entry<K,V> p = root;
 205         while (p != null) {
 206             int cmp = compare(key, p.key);
 207             if (cmp > 0) {
 208                 if (p.right != null)
 209                     p = p.right;
 210                 else
 211                     return p;
 212             } else if (cmp < 0) {
 213                 if (p.left != null) {
 214                     p = p.left;
 215                 } else {
 216                     Entry<K,V> parent = p.parent;
 217                     Entry<K,V> ch = p;
 218                     while (parent != null && ch == parent.left) {
 219                         ch = parent;
 220                         parent = parent.parent;
 221                     }
 222                     return parent;
 223                 }
 224             } else
 225                 return p;
 226 
 227         }
 228         return null;
 229     }
 230 
 231     // 獲取TreeMap中大於key的最小的節點。
 232     // 若不存在,就返回null。
 233     //   請參照getCeilingEntry來對getHigherEntry進行理解。
 234     final Entry<K,V> getHigherEntry(K key) {
 235         Entry<K,V> p = root;
 236         while (p != null) {
 237             int cmp = compare(key, p.key);
 238             if (cmp < 0) {
 239                 if (p.left != null)
 240                     p = p.left;
 241                 else
 242                     return p;
 243             } else {
 244                 if (p.right != null) {
 245                     p = p.right;
 246                 } else {
 247                     Entry<K,V> parent = p.parent;
 248                     Entry<K,V> ch = p;
 249                     while (parent != null && ch == parent.right) {
 250                         ch = parent;
 251                         parent = parent.parent;
 252                     }
 253                     return parent;
 254                 }
 255             }
 256         }
 257         return null;
 258     }
 259 
 260     // 獲取TreeMap中小於key的最大的節點。
 261     // 若不存在,就返回null。
 262     //   請參照getCeilingEntry來對getLowerEntry進行理解。
 263     final Entry<K,V> getLowerEntry(K key) {
 264         Entry<K,V> p = root;
 265         while (p != null) {
 266             int cmp = compare(key, p.key);
 267             if (cmp > 0) {
 268                 if (p.right != null)
 269                     p = p.right;
 270                 else
 271                     return p;
 272             } else {
 273                 if (p.left != null) {
 274                     p = p.left;
 275                 } else {
 276                     Entry<K,V> parent = p.parent;
 277                     Entry<K,V> ch = p;
 278                     while (parent != null && ch == parent.left) {
 279                         ch = parent;
 280                         parent = parent.parent;
 281                     }
 282                     return parent;
 283                 }
 284             }
 285         }
 286         return null;
 287     }
 288 
 289     // 將“key, value”添加到TreeMap中
 290     // 理解TreeMap的前提是掌握“紅黑樹”。
 291     // 若理解“紅黑樹中添加節點”的算法,則很容易理解put。
 292     public V put(K key, V value) {
 293         Entry<K,V> t = root;
 294         // 若紅黑樹爲空,則插入根節點
 295         if (t == null) {
 296         // TBD:
 297         // 5045147: (coll) Adding null to an empty TreeSet should
 298         // throw NullPointerException
 299         //
 300         // compare(key, key); // type check
 301             root = new Entry<K,V>(key, value, null);
 302             size = 1;
 303             modCount++;
 304             return null;
 305         }
 306         int cmp;
 307         Entry<K,V> parent;
 308         // split comparator and comparable paths
 309         Comparator<? super K> cpr = comparator;
 310         // 在二叉樹(紅黑樹是特殊的二叉樹)中,找到(key, value)的插入位置。
 311         // 紅黑樹是以key來進行排序的,所以這裏以key來進行查找。
 312         if (cpr != null) {
 313             do {
 314                 parent = t;
 315                 cmp = cpr.compare(key, t.key);
 316                 if (cmp < 0)
 317                     t = t.left;
 318                 else if (cmp > 0)
 319                     t = t.right;
 320                 else
 321                     return t.setValue(value);
 322             } while (t != null);
 323         }
 324         else {
 325             if (key == null)
 326                 throw new NullPointerException();
 327             Comparable<? super K> k = (Comparable<? super K>) key;
 328             do {
 329                 parent = t;
 330                 cmp = k.compareTo(t.key);
 331                 if (cmp < 0)
 332                     t = t.left;
 333                 else if (cmp > 0)
 334                     t = t.right;
 335                 else
 336                     return t.setValue(value);
 337             } while (t != null);
 338         }
 339         // 新建紅黑樹的節點(e)
 340         Entry<K,V> e = new Entry<K,V>(key, value, parent);
 341         if (cmp < 0)
 342             parent.left = e;
 343         else
 344             parent.right = e;
 345         // 紅黑樹插入節點後,不再是一顆紅黑樹;
 346         // 這裏通過fixAfterInsertion的處理,來恢復紅黑樹的特性。
 347         fixAfterInsertion(e);
 348         size++;
 349         modCount++;
 350         return null;
 351     }
 352 
 353     // 刪除TreeMap中的鍵爲key的節點,並返回節點的值
 354     public V remove(Object key) {
 355         // 找到鍵爲key的節點
 356         Entry<K,V> p = getEntry(key);
 357         if (p == null)
 358             return null;
 359 
 360         // 保存節點的值
 361         V oldValue = p.value;
 362         // 刪除節點
 363         deleteEntry(p);
 364         return oldValue;
 365     }
 366 
 367     // 清空紅黑樹
 368     public void clear() {
 369         modCount++;
 370         size = 0;
 371         root = null;
 372     }
 373 
 374     // 克隆一個TreeMap,並返回Object對象
 375     public Object clone() {
 376         TreeMap<K,V> clone = null;
 377         try {
 378             clone = (TreeMap<K,V>) super.clone();
 379         } catch (CloneNotSupportedException e) {
 380             throw new InternalError();
 381         }
 382 
 383         // Put clone into "virgin" state (except for comparator)
 384         clone.root = null;
 385         clone.size = 0;
 386         clone.modCount = 0;
 387         clone.entrySet = null;
 388         clone.navigableKeySet = null;
 389         clone.descendingMap = null;
 390 
 391         // Initialize clone with our mappings
 392         try {
 393             clone.buildFromSorted(size, entrySet().iterator(), null, null);
 394         } catch (java.io.IOException cannotHappen) {
 395         } catch (ClassNotFoundException cannotHappen) {
 396         }
 397 
 398         return clone;
 399     }
 400 
 401     // 獲取第一個節點(對外接口)。
 402     public Map.Entry<K,V> firstEntry() {
 403         return exportEntry(getFirstEntry());
 404     }
 405 
 406     // 獲取最後一個節點(對外接口)。
 407     public Map.Entry<K,V> lastEntry() {
 408         return exportEntry(getLastEntry());
 409     }
 410 
 411     // 獲取第一個節點,並將改節點從TreeMap中刪除。
 412     public Map.Entry<K,V> pollFirstEntry() {
 413         // 獲取第一個節點
 414         Entry<K,V> p = getFirstEntry();
 415         Map.Entry<K,V> result = exportEntry(p);
 416         // 刪除第一個節點
 417         if (p != null)
 418             deleteEntry(p);
 419         return result;
 420     }
 421 
 422     // 獲取最後一個節點,並將改節點從TreeMap中刪除。
 423     public Map.Entry<K,V> pollLastEntry() {
 424         // 獲取最後一個節點
 425         Entry<K,V> p = getLastEntry();
 426         Map.Entry<K,V> result = exportEntry(p);
 427         // 刪除最後一個節點
 428         if (p != null)
 429             deleteEntry(p);
 430         return result;
 431     }
 432 
 433     // 返回小於key的最大的鍵值對,沒有的話返回null
 434     public Map.Entry<K,V> lowerEntry(K key) {
 435         return exportEntry(getLowerEntry(key));
 436     }
 437 
 438     // 返回小於key的最大的鍵值對所對應的KEY,沒有的話返回null
 439     public K lowerKey(K key) {
 440         return keyOrNull(getLowerEntry(key));
 441     }
 442 
 443     // 返回不大於key的最大的鍵值對,沒有的話返回null
 444     public Map.Entry<K,V> floorEntry(K key) {
 445         return exportEntry(getFloorEntry(key));
 446     }
 447 
 448     // 返回不大於key的最大的鍵值對所對應的KEY,沒有的話返回null
 449     public K floorKey(K key) {
 450         return keyOrNull(getFloorEntry(key));
 451     }
 452 
 453     // 返回不小於key的最小的鍵值對,沒有的話返回null
 454     public Map.Entry<K,V> ceilingEntry(K key) {
 455         return exportEntry(getCeilingEntry(key));
 456     }
 457 
 458     // 返回不小於key的最小的鍵值對所對應的KEY,沒有的話返回null
 459     public K ceilingKey(K key) {
 460         return keyOrNull(getCeilingEntry(key));
 461     }
 462 
 463     // 返回大於key的最小的鍵值對,沒有的話返回null
 464     public Map.Entry<K,V> higherEntry(K key) {
 465         return exportEntry(getHigherEntry(key));
 466     }
 467 
 468     // 返回大於key的最小的鍵值對所對應的KEY,沒有的話返回null
 469     public K higherKey(K key) {
 470         return keyOrNull(getHigherEntry(key));
 471     }
 472 
 473     // TreeMap的紅黑樹節點對應的集合
 474     private transient EntrySet entrySet = null;
 475     // KeySet爲KeySet導航類
 476     private transient KeySet<K> navigableKeySet = null;
 477     // descendingMap爲鍵值對的倒序“映射”
 478     private transient NavigableMap<K,V> descendingMap = null;
 479 
 480     // 返回TreeMap的“鍵的集合”
 481     public Set<K> keySet() {
 482         return navigableKeySet();
 483     }
 484 
 485     // 獲取“可導航”的Key的集合
 486     // 實際上是返回KeySet類的對象。
 487     public NavigableSet<K> navigableKeySet() {
 488         KeySet<K> nks = navigableKeySet;
 489         return (nks != null) ? nks : (navigableKeySet = new KeySet(this));
 490     }
 491 
 492     // 返回“TreeMap的值對應的集合”
 493     public Collection<V> values() {
 494         Collection<V> vs = values;
 495         return (vs != null) ? vs : (values = new Values());
 496     }
 497 
 498     // 獲取TreeMap的Entry的集合,實際上是返回EntrySet類的對象。
 499     public Set<Map.Entry<K,V>> entrySet() {
 500         EntrySet es = entrySet;
 501         return (es != null) ? es : (entrySet = new EntrySet());
 502     }
 503 
 504     // 獲取TreeMap的降序Map
 505     // 實際上是返回DescendingSubMap類的對象
 506     public NavigableMap<K, V> descendingMap() {
 507         NavigableMap<K, V> km = descendingMap;
 508         return (km != null) ? km :
 509             (descendingMap = new DescendingSubMap(this,
 510                                                   true, null, true,
 511                                                   true, null, true));
 512     }
 513 
 514     // 獲取TreeMap的子Map
 515     // 範圍是從fromKey 到 toKey;fromInclusive是是否包含fromKey的標記,toInclusive是是否包含toKey的標記
 516     public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
 517                                     K toKey,   boolean toInclusive) {
 518         return new AscendingSubMap(this,
 519                                    false, fromKey, fromInclusive,
 520                                    false, toKey,   toInclusive);
 521     }
 522 
 523     // 獲取“Map的頭部”
 524     // 範圍從第一個節點 到 toKey, inclusive是是否包含toKey的標記
 525     public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
 526         return new AscendingSubMap(this,
 527                                    true,  null,  true,
 528                                    false, toKey, inclusive);
 529     }
 530 
 531     // 獲取“Map的尾部”。
 532     // 範圍是從 fromKey 到 最後一個節點,inclusive是是否包含fromKey的標記
 533     public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
 534         return new AscendingSubMap(this,
 535                                    false, fromKey, inclusive,
 536                                    true,  null,    true);
 537     }
 538 
 539     // 獲取“子Map”。
 540     // 範圍是從fromKey(包括) 到 toKey(不包括)
 541     public SortedMap<K,V> subMap(K fromKey, K toKey) {
 542         return subMap(fromKey, true, toKey, false);
 543     }
 544 
 545     // 獲取“Map的頭部”。
 546     // 範圍從第一個節點 到 toKey(不包括)
 547     public SortedMap<K,V> headMap(K toKey) {
 548         return headMap(toKey, false);
 549     }
 550 
 551     // 獲取“Map的尾部”。
 552     // 範圍是從 fromKey(包括) 到 最後一個節點
 553     public SortedMap<K,V> tailMap(K fromKey) {
 554         return tailMap(fromKey, true);
 555     }
 556 
 557     // ”TreeMap的值的集合“對應的類,它集成於AbstractCollection
 558     class Values extends AbstractCollection<V> {
 559         // 返回迭代器
 560         public Iterator<V> iterator() {
 561             return new ValueIterator(getFirstEntry());
 562         }
 563 
 564         // 返回個數
 565         public int size() {
 566             return TreeMap.this.size();
 567         }
 568 
 569         // "TreeMap的值的集合"中是否包含"對象o"
 570         public boolean contains(Object o) {
 571             return TreeMap.this.containsValue(o);
 572         }
 573 
 574         // 刪除"TreeMap的值的集合"中的"對象o"
 575         public boolean remove(Object o) {
 576             for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e)) {
 577                 if (valEquals(e.getValue(), o)) {
 578                     deleteEntry(e);
 579                     return true;
 580                 }
 581             }
 582             return false;
 583         }
 584 
 585         // 清空刪除"TreeMap的值的集合"
 586         public void clear() {
 587             TreeMap.this.clear();
 588         }
 589     }
 590 
 591     // EntrySet是“TreeMap的所有鍵值對組成的集合”,
 592     // EntrySet集合的單位是單個“鍵值對”。
 593     class EntrySet extends AbstractSet<Map.Entry<K,V>> {
 594         public Iterator<Map.Entry<K,V>> iterator() {
 595             return new EntryIterator(getFirstEntry());
 596         }
 597 
 598         // EntrySet中是否包含“鍵值對Object”
 599         public boolean contains(Object o) {
 600             if (!(o instanceof Map.Entry))
 601                 return false;
 602             Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
 603             V value = entry.getValue();
 604             Entry<K,V> p = getEntry(entry.getKey());
 605             return p != null && valEquals(p.getValue(), value);
 606         }
 607 
 608         // 刪除EntrySet中的“鍵值對Object”
 609         public boolean remove(Object o) {
 610             if (!(o instanceof Map.Entry))
 611                 return false;
 612             Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
 613             V value = entry.getValue();
 614             Entry<K,V> p = getEntry(entry.getKey());
 615             if (p != null && valEquals(p.getValue(), value)) {
 616                 deleteEntry(p);
 617                 return true;
 618             }
 619             return false;
 620         }
 621 
 622         // 返回EntrySet中元素個數
 623         public int size() {
 624             return TreeMap.this.size();
 625         }
 626 
 627         // 清空EntrySet
 628         public void clear() {
 629             TreeMap.this.clear();
 630         }
 631     }
 632 
 633     // 返回“TreeMap的KEY組成的迭代器(順序)”
 634     Iterator<K> keyIterator() {
 635         return new KeyIterator(getFirstEntry());
 636     }
 637 
 638     // 返回“TreeMap的KEY組成的迭代器(逆序)”
 639     Iterator<K> descendingKeyIterator() {
 640         return new DescendingKeyIterator(getLastEntry());
 641     }
 642 
 643     // KeySet是“TreeMap中所有的KEY組成的集合”
 644     // KeySet繼承於AbstractSet,而且實現了NavigableSet接口。
 645     static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
 646         // NavigableMap成員,KeySet是通過NavigableMap實現的
 647         private final NavigableMap<E, Object> m;
 648         KeySet(NavigableMap<E,Object> map) { m = map; }
 649 
 650         // 升序迭代器
 651         public Iterator<E> iterator() {
 652             // 若是TreeMap對象,則調用TreeMap的迭代器keyIterator()
 653             // 否則,調用TreeMap子類NavigableSubMap的迭代器keyIterator()
 654             if (m instanceof TreeMap)
 655                 return ((TreeMap<E,Object>)m).keyIterator();
 656             else
 657                 return (Iterator<E>)(((TreeMap.NavigableSubMap)m).keyIterator());
 658         }
 659 
 660         // 降序迭代器
 661         public Iterator<E> descendingIterator() {
 662             // 若是TreeMap對象,則調用TreeMap的迭代器descendingKeyIterator()
 663             // 否則,調用TreeMap子類NavigableSubMap的迭代器descendingKeyIterator()
 664             if (m instanceof TreeMap)
 665                 return ((TreeMap<E,Object>)m).descendingKeyIterator();
 666             else
 667                 return (Iterator<E>)(((TreeMap.NavigableSubMap)m).descendingKeyIterator());
 668         }
 669 
 670         public int size() { return m.size(); }
 671         public boolean isEmpty() { return m.isEmpty(); }
 672         public boolean contains(Object o) { return m.containsKey(o); }
 673         public void clear() { m.clear(); }
 674         public E lower(E e) { return m.lowerKey(e); }
 675         public E floor(E e) { return m.floorKey(e); }
 676         public E ceiling(E e) { return m.ceilingKey(e); }
 677         public E higher(E e) { return m.higherKey(e); }
 678         public E first() { return m.firstKey(); }
 679         public E last() { return m.lastKey(); }
 680         public Comparator<? super E> comparator() { return m.comparator(); }
 681         public E pollFirst() {
 682             Map.Entry<E,Object> e = m.pollFirstEntry();
 683             return e == null? null : e.getKey();
 684         }
 685         public E pollLast() {
 686             Map.Entry<E,Object> e = m.pollLastEntry();
 687             return e == null? null : e.getKey();
 688         }
 689         public boolean remove(Object o) {
 690             int oldSize = size();
 691             m.remove(o);
 692             return size() != oldSize;
 693         }
 694         public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
 695                                       E toElement,   boolean toInclusive) {
 696             return new TreeSet<E>(m.subMap(fromElement, fromInclusive,
 697                                            toElement,   toInclusive));
 698         }
 699         public NavigableSet<E> headSet(E toElement, boolean inclusive) {
 700             return new TreeSet<E>(m.headMap(toElement, inclusive));
 701         }
 702         public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
 703             return new TreeSet<E>(m.tailMap(fromElement, inclusive));
 704         }
 705         public SortedSet<E> subSet(E fromElement, E toElement) {
 706             return subSet(fromElement, true, toElement, false);
 707         }
 708         public SortedSet<E> headSet(E toElement) {
 709             return headSet(toElement, false);
 710         }
 711         public SortedSet<E> tailSet(E fromElement) {
 712             return tailSet(fromElement, true);
 713         }
 714         public NavigableSet<E> descendingSet() {
 715             return new TreeSet(m.descendingMap());
 716         }
 717     }
 718 
 719     // 它是TreeMap中的一個抽象迭代器,實現了一些通用的接口。
 720     abstract class PrivateEntryIterator<T> implements Iterator<T> {
 721         // 下一個元素
 722         Entry<K,V> next;
 723         // 上一次返回元素
 724         Entry<K,V> lastReturned;
 725         // 期望的修改次數,用於實現fast-fail機制
 726         int expectedModCount;
 727 
 728         PrivateEntryIterator(Entry<K,V> first) {
 729             expectedModCount = modCount;
 730             lastReturned = null;
 731             next = first;
 732         }
 733 
 734         public final boolean hasNext() {
 735             return next != null;
 736         }
 737 
 738         // 獲取下一個節點
 739         final Entry<K,V> nextEntry() {
 740             Entry<K,V> e = next;
 741             if (e == null)
 742                 throw new NoSuchElementException();
 743             if (modCount != expectedModCount)
 744                 throw new ConcurrentModificationException();
 745             next = successor(e);
 746             lastReturned = e;
 747             return e;
 748         }
 749 
 750         // 獲取上一個節點
 751         final Entry<K,V> prevEntry() {
 752             Entry<K,V> e = next;
 753             if (e == null)
 754                 throw new NoSuchElementException();
 755             if (modCount != expectedModCount)
 756                 throw new ConcurrentModificationException();
 757             next = predecessor(e);
 758             lastReturned = e;
 759             return e;
 760         }
 761 
 762         // 刪除當前節點
 763         public void remove() {
 764             if (lastReturned == null)
 765                 throw new IllegalStateException();
 766             if (modCount != expectedModCount)
 767                 throw new ConcurrentModificationException();
 768             // 這裏重點強調一下“爲什麼當lastReturned的左右孩子都不爲空時,要將其賦值給next”。
 769             // 目的是爲了“刪除lastReturned節點之後,next節點指向的仍然是下一個節點”。
 770             //     根據“紅黑樹”的特性可知:
 771             //     當被刪除節點有兩個兒子時。那麼,首先把“它的後繼節點的內容”複製給“該節點的內容”;之後,刪除“它的後繼節點”。
 772             //     這意味着“當被刪除節點有兩個兒子時,刪除當前節點之後,'新的當前節點'實際上是‘原有的後繼節點(即下一個節點)’”。
 773             //     而此時next仍然指向"新的當前節點"。也就是說next是仍然是指向下一個節點;能繼續遍歷紅黑樹。
 774             if (lastReturned.left != null && lastReturned.right != null)
 775                 next = lastReturned;
 776             deleteEntry(lastReturned);
 777             expectedModCount = modCount;
 778             lastReturned = null;
 779         }
 780     }
 781 
 782     // TreeMap的Entry對應的迭代器
 783     final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
 784         EntryIterator(Entry<K,V> first) {
 785             super(first);
 786         }
 787         public Map.Entry<K,V> next() {
 788             return nextEntry();
 789         }
 790     }
 791 
 792     // TreeMap的Value對應的迭代器
 793     final class ValueIterator extends PrivateEntryIterator<V> {
 794         ValueIterator(Entry<K,V> first) {
 795             super(first);
 796         }
 797         public V next() {
 798             return nextEntry().value;
 799         }
 800     }
 801 
 802     // reeMap的KEY組成的迭代器(順序)
 803     final class KeyIterator extends PrivateEntryIterator<K> {
 804         KeyIterator(Entry<K,V> first) {
 805             super(first);
 806         }
 807         public K next() {
 808             return nextEntry().key;
 809         }
 810     }
 811 
 812     // TreeMap的KEY組成的迭代器(逆序)
 813     final class DescendingKeyIterator extends PrivateEntryIterator<K> {
 814         DescendingKeyIterator(Entry<K,V> first) {
 815             super(first);
 816         }
 817         public K next() {
 818             return prevEntry().key;
 819         }
 820     }
 821 
 822     // 比較兩個對象的大小
 823     final int compare(Object k1, Object k2) {
 824         return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
 825             : comparator.compare((K)k1, (K)k2);
 826     }
 827 
 828     // 判斷兩個對象是否相等
 829     final static boolean valEquals(Object o1, Object o2) {
 830         return (o1==null ? o2==null : o1.equals(o2));
 831     }
 832 
 833     // 返回“Key-Value鍵值對”的一個簡單拷貝(AbstractMap.SimpleImmutableEntry<K,V>對象)
 834     // 可用來讀取“鍵值對”的值
 835     static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
 836         return e == null? null :
 837             new AbstractMap.SimpleImmutableEntry<K,V>(e);
 838     }
 839 
 840     // 若“鍵值對”不爲null,則返回KEY;否則,返回null
 841     static <K,V> K keyOrNull(TreeMap.Entry<K,V> e) {
 842         return e == null? null : e.key;
 843     }
 844 
 845     // 若“鍵值對”不爲null,則返回KEY;否則,拋出異常
 846     static <K> K key(Entry<K,?> e) {
 847         if (e==null)
 848             throw new NoSuchElementException();
 849         return e.key;
 850     }
 851 
 852     // TreeMap的SubMap,它一個抽象類,實現了公共操作。
 853     // 它包括了"(升序)AscendingSubMap"和"(降序)DescendingSubMap"兩個子類。
 854     static abstract class NavigableSubMap<K,V> extends AbstractMap<K,V>
 855         implements NavigableMap<K,V>, java.io.Serializable {
 856         // TreeMap的拷貝
 857         final TreeMap<K,V> m;
 858         // lo是“子Map範圍的最小值”,hi是“子Map範圍的最大值”;
 859         // loInclusive是“是否包含lo的標記”,hiInclusive是“是否包含hi的標記”
 860         // fromStart是“表示是否從第一個節點開始計算”,
 861         // toEnd是“表示是否計算到最後一個節點      ”
 862         final K lo, hi;      
 863         final boolean fromStart, toEnd;
 864         final boolean loInclusive, hiInclusive;
 865 
 866         // 構造函數
 867         NavigableSubMap(TreeMap<K,V> m,
 868                         boolean fromStart, K lo, boolean loInclusive,
 869                         boolean toEnd,     K hi, boolean hiInclusive) {
 870             if (!fromStart && !toEnd) {
 871                 if (m.compare(lo, hi) > 0)
 872                     throw new IllegalArgumentException("fromKey > toKey");
 873             } else {
 874                 if (!fromStart) // type check
 875                     m.compare(lo, lo);
 876                 if (!toEnd)
 877                     m.compare(hi, hi);
 878             }
 879 
 880             this.m = m;
 881             this.fromStart = fromStart;
 882             this.lo = lo;
 883             this.loInclusive = loInclusive;
 884             this.toEnd = toEnd;
 885             this.hi = hi;
 886             this.hiInclusive = hiInclusive;
 887         }
 888 
 889         // 判斷key是否太小
 890         final boolean tooLow(Object key) {
 891             // 若該SubMap不包括“起始節點”,
 892             // 並且,“key小於最小鍵(lo)”或者“key等於最小鍵(lo),但最小鍵卻沒包括在該SubMap內”
 893             // 則判斷key太小。其餘情況都不是太小!
 894             if (!fromStart) {
 895                 int c = m.compare(key, lo);
 896                 if (c < 0 || (c == 0 && !loInclusive))
 897                     return true;
 898             }
 899             return false;
 900         }
 901 
 902         // 判斷key是否太大
 903         final boolean tooHigh(Object key) {
 904             // 若該SubMap不包括“結束節點”,
 905             // 並且,“key大於最大鍵(hi)”或者“key等於最大鍵(hi),但最大鍵卻沒包括在該SubMap內”
 906             // 則判斷key太大。其餘情況都不是太大!
 907             if (!toEnd) {
 908                 int c = m.compare(key, hi);
 909                 if (c > 0 || (c == 0 && !hiInclusive))
 910                     return true;
 911             }
 912             return false;
 913         }
 914 
 915         // 判斷key是否在“lo和hi”開區間範圍內
 916         final boolean inRange(Object key) {
 917             return !tooLow(key) && !tooHigh(key);
 918         }
 919 
 920         // 判斷key是否在封閉區間內
 921         final boolean inClosedRange(Object key) {
 922             return (fromStart || m.compare(key, lo) >= 0)
 923                 && (toEnd || m.compare(hi, key) >= 0);
 924         }
 925 
 926         // 判斷key是否在區間內, inclusive是區間開關標誌
 927         final boolean inRange(Object key, boolean inclusive) {
 928             return inclusive ? inRange(key) : inClosedRange(key);
 929         }
 930 
 931         // 返回最低的Entry
 932         final TreeMap.Entry<K,V> absLowest() {
 933         // 若“包含起始節點”,則調用getFirstEntry()返回第一個節點
 934         // 否則的話,若包括lo,則調用getCeilingEntry(lo)獲取大於/等於lo的最小的Entry;
 935         //           否則,調用getHigherEntry(lo)獲取大於lo的最小Entry
 936         TreeMap.Entry<K,V> e =
 937                 (fromStart ?  m.getFirstEntry() :
 938                  (loInclusive ? m.getCeilingEntry(lo) :
 939                                 m.getHigherEntry(lo)));
 940             return (e == null || tooHigh(e.key)) ? null : e;
 941         }
 942 
 943         // 返回最高的Entry
 944         final TreeMap.Entry<K,V> absHighest() {
 945         // 若“包含結束節點”,則調用getLastEntry()返回最後一個節點
 946         // 否則的話,若包括hi,則調用getFloorEntry(hi)獲取小於/等於hi的最大的Entry;
 947         //           否則,調用getLowerEntry(hi)獲取大於hi的最大Entry
 948         TreeMap.Entry<K,V> e =
 949         TreeMap.Entry<K,V> e =
 950                 (toEnd ?  m.getLastEntry() :
 951                  (hiInclusive ?  m.getFloorEntry(hi) :
 952                                  m.getLowerEntry(hi)));
 953             return (e == null || tooLow(e.key)) ? null : e;
 954         }
 955 
 956         // 返回"大於/等於key的最小的Entry"
 957         final TreeMap.Entry<K,V> absCeiling(K key) {
 958             // 只有在“key太小”的情況下,absLowest()返回的Entry纔是“大於/等於key的最小Entry”
 959             // 其它情況下不行。例如,當包含“起始節點”時,absLowest()返回的是最小Entry了!
 960             if (tooLow(key))
 961                 return absLowest();
 962             // 獲取“大於/等於key的最小Entry”
 963         TreeMap.Entry<K,V> e = m.getCeilingEntry(key);
 964             return (e == null || tooHigh(e.key)) ? null : e;
 965         }
 966 
 967         // 返回"大於key的最小的Entry"
 968         final TreeMap.Entry<K,V> absHigher(K key) {
 969             // 只有在“key太小”的情況下,absLowest()返回的Entry纔是“大於key的最小Entry”
 970             // 其它情況下不行。例如,當包含“起始節點”時,absLowest()返回的是最小Entry了,而不一定是“大於key的最小Entry”!
 971             if (tooLow(key))
 972                 return absLowest();
 973             // 獲取“大於key的最小Entry”
 974         TreeMap.Entry<K,V> e = m.getHigherEntry(key);
 975             return (e == null || tooHigh(e.key)) ? null : e;
 976         }
 977 
 978         // 返回"小於/等於key的最大的Entry"
 979         final TreeMap.Entry<K,V> absFloor(K key) {
 980             // 只有在“key太大”的情況下,(absHighest)返回的Entry纔是“小於/等於key的最大Entry”
 981             // 其它情況下不行。例如,當包含“結束節點”時,absHighest()返回的是最大Entry了!
 982             if (tooHigh(key))
 983                 return absHighest();
 984         // 獲取"小於/等於key的最大的Entry"
 985         TreeMap.Entry<K,V> e = m.getFloorEntry(key);
 986             return (e == null || tooLow(e.key)) ? null : e;
 987         }
 988 
 989         // 返回"小於key的最大的Entry"
 990         final TreeMap.Entry<K,V> absLower(K key) {
 991             // 只有在“key太大”的情況下,(absHighest)返回的Entry纔是“小於key的最大Entry”
 992             // 其它情況下不行。例如,當包含“結束節點”時,absHighest()返回的是最大Entry了,而不一定是“小於key的最大Entry”!
 993             if (tooHigh(key))
 994                 return absHighest();
 995         // 獲取"小於key的最大的Entry"
 996         TreeMap.Entry<K,V> e = m.getLowerEntry(key);
 997             return (e == null || tooLow(e.key)) ? null : e;
 998         }
 999 
1000         // 返回“大於最大節點中的最小節點”,不存在的話,返回null
1001         final TreeMap.Entry<K,V> absHighFence() {
1002             return (toEnd ? null : (hiInclusive ?
1003                                     m.getHigherEntry(hi) :
1004                                     m.getCeilingEntry(hi)));
1005         }
1006 
1007         // 返回“小於最小節點中的最大節點”,不存在的話,返回null
1008         final TreeMap.Entry<K,V> absLowFence() {
1009             return (fromStart ? null : (loInclusive ?
1010                                         m.getLowerEntry(lo) :
1011                                         m.getFloorEntry(lo)));
1012         }
1013 
1014         // 下面幾個abstract方法是需要NavigableSubMap的實現類實現的方法
1015         abstract TreeMap.Entry<K,V> subLowest();
1016         abstract TreeMap.Entry<K,V> subHighest();
1017         abstract TreeMap.Entry<K,V> subCeiling(K key);
1018         abstract TreeMap.Entry<K,V> subHigher(K key);
1019         abstract TreeMap.Entry<K,V> subFloor(K key);
1020         abstract TreeMap.Entry<K,V> subLower(K key);
1021         // 返回“順序”的鍵迭代器
1022         abstract Iterator<K> keyIterator();
1023         // 返回“逆序”的鍵迭代器
1024         abstract Iterator<K> descendingKeyIterator();
1025 
1026         // 返回SubMap是否爲空。空的話,返回true,否則返回false
1027         public boolean isEmpty() {
1028             return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty();
1029         }
1030 
1031         // 返回SubMap的大小
1032         public int size() {
1033             return (fromStart && toEnd) ? m.size() : entrySet().size();
1034         }
1035 
1036         // 返回SubMap是否包含鍵key
1037         public final boolean containsKey(Object key) {
1038             return inRange(key) && m.containsKey(key);
1039         }
1040 
1041         // 將key-value 插入SubMap中
1042         public final V put(K key, V value) {
1043             if (!inRange(key))
1044                 throw new IllegalArgumentException("key out of range");
1045             return m.put(key, value);
1046         }
1047 
1048         // 獲取key對應值
1049         public final V get(Object key) {
1050             return !inRange(key)? null :  m.get(key);
1051         }
1052 
1053         // 刪除key對應的鍵值對
1054         public final V remove(Object key) {
1055             return !inRange(key)? null  : m.remove(key);
1056         }
1057 
1058         // 獲取“大於/等於key的最小鍵值對”
1059         public final Map.Entry<K,V> ceilingEntry(K key) {
1060             return exportEntry(subCeiling(key));
1061         }
1062 
1063         // 獲取“大於/等於key的最小鍵”
1064         public final K ceilingKey(K key) {
1065             return keyOrNull(subCeiling(key));
1066         }
1067 
1068         // 獲取“大於key的最小鍵值對”
1069         public final Map.Entry<K,V> higherEntry(K key) {
1070             return exportEntry(subHigher(key));
1071         }
1072 
1073         // 獲取“大於key的最小鍵”
1074         public final K higherKey(K key) {
1075             return keyOrNull(subHigher(key));
1076         }
1077 
1078         // 獲取“小於/等於key的最大鍵值對”
1079         public final Map.Entry<K,V> floorEntry(K key) {
1080             return exportEntry(subFloor(key));
1081         }
1082 
1083         // 獲取“小於/等於key的最大鍵”
1084         public final K floorKey(K key) {
1085             return keyOrNull(subFloor(key));
1086         }
1087 
1088         // 獲取“小於key的最大鍵值對”
1089         public final Map.Entry<K,V> lowerEntry(K key) {
1090             return exportEntry(subLower(key));
1091         }
1092 
1093         // 獲取“小於key的最大鍵”
1094         public final K lowerKey(K key) {
1095             return keyOrNull(subLower(key));
1096         }
1097 
1098         // 獲取"SubMap的第一個鍵"
1099         public final K firstKey() {
1100             return key(subLowest());
1101         }
1102 
1103         // 獲取"SubMap的最後一個鍵"
1104         public final K lastKey() {
1105             return key(subHighest());
1106         }
1107 
1108         // 獲取"SubMap的第一個鍵值對"
1109         public final Map.Entry<K,V> firstEntry() {
1110             return exportEntry(subLowest());
1111         }
1112 
1113         // 獲取"SubMap的最後一個鍵值對"
1114         public final Map.Entry<K,V> lastEntry() {
1115             return exportEntry(subHighest());
1116         }
1117 
1118         // 返回"SubMap的第一個鍵值對",並從SubMap中刪除改鍵值對
1119         public final Map.Entry<K,V> pollFirstEntry() {
1120         TreeMap.Entry<K,V> e = subLowest();
1121             Map.Entry<K,V> result = exportEntry(e);
1122             if (e != null)
1123                 m.deleteEntry(e);
1124             return result;
1125         }
1126 
1127         // 返回"SubMap的最後一個鍵值對",並從SubMap中刪除改鍵值對
1128         public final Map.Entry<K,V> pollLastEntry() {
1129         TreeMap.Entry<K,V> e = subHighest();
1130             Map.Entry<K,V> result = exportEntry(e);
1131             if (e != null)
1132                 m.deleteEntry(e);
1133             return result;
1134         }
1135 
1136         // Views
1137         transient NavigableMap<K,V> descendingMapView = null;
1138         transient EntrySetView entrySetView = null;
1139         transient KeySet<K> navigableKeySetView = null;
1140 
1141         // 返回NavigableSet對象,實際上返回的是當前對象的"Key集合"。 
1142         public final NavigableSet<K> navigableKeySet() {
1143             KeySet<K> nksv = navigableKeySetView;
1144             return (nksv != null) ? nksv :
1145                 (navigableKeySetView = new TreeMap.KeySet(this));
1146         }
1147 
1148         // 返回"Key集合"對象
1149         public final Set<K> keySet() {
1150             return navigableKeySet();
1151         }
1152 
1153         // 返回“逆序”的Key集合
1154         public NavigableSet<K> descendingKeySet() {
1155             return descendingMap().navigableKeySet();
1156         }
1157 
1158         // 排列fromKey(包含) 到 toKey(不包含) 的子map
1159         public final SortedMap<K,V> subMap(K fromKey, K toKey) {
1160             return subMap(fromKey, true, toKey, false);
1161         }
1162 
1163         // 返回當前Map的頭部(從第一個節點 到 toKey, 不包括toKey)
1164         public final SortedMap<K,V> headMap(K toKey) {
1165             return headMap(toKey, false);
1166         }
1167 
1168         // 返回當前Map的尾部[從 fromKey(包括fromKeyKey) 到 最後一個節點]
1169         public final SortedMap<K,V> tailMap(K fromKey) {
1170             return tailMap(fromKey, true);
1171         }
1172 
1173         // Map的Entry的集合
1174         abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1175             private transient int size = -1, sizeModCount;
1176 
1177             // 獲取EntrySet的大小
1178             public int size() {
1179                 // 若SubMap是從“開始節點”到“結尾節點”,則SubMap大小就是原TreeMap的大小
1180                 if (fromStart && toEnd)
1181                     return m.size();
1182                 // 若SubMap不是從“開始節點”到“結尾節點”,則調用iterator()遍歷EntrySetView中的元素
1183                 if (size == -1 || sizeModCount != m.modCount) {
1184                     sizeModCount = m.modCount;
1185                     size = 0;
1186                     Iterator i = iterator();
1187                     while (i.hasNext()) {
1188                         size++;
1189                         i.next();
1190                     }
1191                 }
1192                 return size;
1193             }
1194 
1195             // 判斷EntrySetView是否爲空
1196             public boolean isEmpty() {
1197                 TreeMap.Entry<K,V> n = absLowest();
1198                 return n == null || tooHigh(n.key);
1199             }
1200 
1201             // 判斷EntrySetView是否包含Object
1202             public boolean contains(Object o) {
1203                 if (!(o instanceof Map.Entry))
1204                     return false;
1205                 Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1206                 K key = entry.getKey();
1207                 if (!inRange(key))
1208                     return false;
1209                 TreeMap.Entry node = m.getEntry(key);
1210                 return node != null &&
1211                     valEquals(node.getValue(), entry.getValue());
1212             }
1213 
1214             // 從EntrySetView中刪除Object
1215             public boolean remove(Object o) {
1216                 if (!(o instanceof Map.Entry))
1217                     return false;
1218                 Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1219                 K key = entry.getKey();
1220                 if (!inRange(key))
1221                     return false;
1222                 TreeMap.Entry<K,V> node = m.getEntry(key);
1223                 if (node!=null && valEquals(node.getValue(),entry.getValue())){
1224                     m.deleteEntry(node);
1225                     return true;
1226                 }
1227                 return false;
1228             }
1229         }
1230 
1231         // SubMap的迭代器
1232         abstract class SubMapIterator<T> implements Iterator<T> {
1233             // 上一次被返回的Entry
1234             TreeMap.Entry<K,V> lastReturned;
1235             // 指向下一個Entry
1236             TreeMap.Entry<K,V> next;
1237             // “柵欄key”。根據SubMap是“升序”還是“降序”具有不同的意義
1238             final K fenceKey;
1239             int expectedModCount;
1240 
1241             // 構造函數
1242             SubMapIterator(TreeMap.Entry<K,V> first,
1243                            TreeMap.Entry<K,V> fence) {
1244                 // 每創建一個SubMapIterator時,保存修改次數
1245                 // 若後面發現expectedModCount和modCount不相等,則拋出ConcurrentModificationException異常。
1246                 // 這就是所說的fast-fail機制的原理!
1247                 expectedModCount = m.modCount;
1248                 lastReturned = null;
1249                 next = first;
1250                 fenceKey = fence == null ? null : fence.key;
1251             }
1252 
1253             // 是否存在下一個Entry
1254             public final boolean hasNext() {
1255                 return next != null && next.key != fenceKey;
1256             }
1257 
1258             // 返回下一個Entry
1259             final TreeMap.Entry<K,V> nextEntry() {
1260                 TreeMap.Entry<K,V> e = next;
1261                 if (e == null || e.key == fenceKey)
1262                     throw new NoSuchElementException();
1263                 if (m.modCount != expectedModCount)
1264                     throw new ConcurrentModificationException();
1265                 // next指向e的後繼節點
1266                 next = successor(e);
1267         lastReturned = e;
1268                 return e;
1269             }
1270 
1271             // 返回上一個Entry
1272             final TreeMap.Entry<K,V> prevEntry() {
1273                 TreeMap.Entry<K,V> e = next;
1274                 if (e == null || e.key == fenceKey)
1275                     throw new NoSuchElementException();
1276                 if (m.modCount != expectedModCount)
1277                     throw new ConcurrentModificationException();
1278                 // next指向e的前繼節點
1279                 next = predecessor(e);
1280         lastReturned = e;
1281                 return e;
1282             }
1283 
1284             // 刪除當前節點(用於“升序的SubMap”)。
1285             // 刪除之後,可以繼續升序遍歷;紅黑樹特性沒變。
1286             final void removeAscending() {
1287                 if (lastReturned == null)
1288                     throw new IllegalStateException();
1289                 if (m.modCount != expectedModCount)
1290                     throw new ConcurrentModificationException();
1291                 // 這裏重點強調一下“爲什麼當lastReturned的左右孩子都不爲空時,要將其賦值給next”。
1292                 // 目的是爲了“刪除lastReturned節點之後,next節點指向的仍然是下一個節點”。
1293                 //     根據“紅黑樹”的特性可知:
1294                 //     當被刪除節點有兩個兒子時。那麼,首先把“它的後繼節點的內容”複製給“該節點的內容”;之後,刪除“它的後繼節點”。
1295                 //     這意味着“當被刪除節點有兩個兒子時,刪除當前節點之後,'新的當前節點'實際上是‘原有的後繼節點(即下一個節點)’”。
1296                 //     而此時next仍然指向"新的當前節點"。也就是說next是仍然是指向下一個節點;能繼續遍歷紅黑樹。
1297                 if (lastReturned.left != null && lastReturned.right != null)
1298                     next = lastReturned;
1299                 m.deleteEntry(lastReturned);
1300                 lastReturned = null;
1301                 expectedModCount = m.modCount;
1302             }
1303 
1304             // 刪除當前節點(用於“降序的SubMap”)。
1305             // 刪除之後,可以繼續降序遍歷;紅黑樹特性沒變。
1306             final void removeDescending() {
1307                 if (lastReturned == null)
1308                     throw new IllegalStateException();
1309                 if (m.modCount != expectedModCount)
1310                     throw new ConcurrentModificationException();
1311                 m.deleteEntry(lastReturned);
1312                 lastReturned = null;
1313                 expectedModCount = m.modCount;
1314             }
1315 
1316         }
1317 
1318         // SubMap的Entry迭代器,它只支持升序操作,繼承於SubMapIterator
1319         final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1320             SubMapEntryIterator(TreeMap.Entry<K,V> first,
1321                                 TreeMap.Entry<K,V> fence) {
1322                 super(first, fence);
1323             }
1324             // 獲取下一個節點(升序)
1325             public Map.Entry<K,V> next() {
1326                 return nextEntry();
1327             }
1328             // 刪除當前節點(升序)
1329             public void remove() {
1330                 removeAscending();
1331             }
1332         }
1333 
1334         // SubMap的Key迭代器,它只支持升序操作,繼承於SubMapIterator
1335         final class SubMapKeyIterator extends SubMapIterator<K> {
1336             SubMapKeyIterator(TreeMap.Entry<K,V> first,
1337                               TreeMap.Entry<K,V> fence) {
1338                 super(first, fence);
1339             }
1340             // 獲取下一個節點(升序)
1341             public K next() {
1342                 return nextEntry().key;
1343             }
1344             // 刪除當前節點(升序)
1345             public void remove() {
1346                 removeAscending();
1347             }
1348         }
1349 
1350         // 降序SubMap的Entry迭代器,它只支持降序操作,繼承於SubMapIterator
1351         final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1352             DescendingSubMapEntryIterator(TreeMap.Entry<K,V> last,
1353                                           TreeMap.Entry<K,V> fence) {
1354                 super(last, fence);
1355             }
1356 
1357             // 獲取下一個節點(降序)
1358             public Map.Entry<K,V> next() {
1359                 return prevEntry();
1360             }
1361             // 刪除當前節點(降序)
1362             public void remove() {
1363                 removeDescending();
1364             }
1365         }
1366 
1367         // 降序SubMap的Key迭代器,它只支持降序操作,繼承於SubMapIterator
1368         final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
1369             DescendingSubMapKeyIterator(TreeMap.Entry<K,V> last,
1370                                         TreeMap.Entry<K,V> fence) {
1371                 super(last, fence);
1372             }
1373             // 獲取下一個節點(降序)
1374             public K next() {
1375                 return prevEntry().key;
1376             }
1377             // 刪除當前節點(降序)
1378             public void remove() {
1379                 removeDescending();
1380             }
1381         }
1382     }
1383 
1384 
1385     // 升序的SubMap,繼承於NavigableSubMap
1386     static final class AscendingSubMap<K,V> extends NavigableSubMap<K,V> {
1387         private static final long serialVersionUID = 912986545866124060L;
1388 
1389         // 構造函數
1390         AscendingSubMap(TreeMap<K,V> m,
1391                         boolean fromStart, K lo, boolean loInclusive,
1392                         boolean toEnd,     K hi, boolean hiInclusive) {
1393             super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1394         }
1395 
1396         // 比較器
1397         public Comparator<? super K> comparator() {
1398             return m.comparator();
1399         }
1400 
1401         // 獲取“子Map”。
1402         // 範圍是從fromKey 到 toKey;fromInclusive是是否包含fromKey的標記,toInclusive是是否包含toKey的標記
1403         public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1404                                         K toKey,   boolean toInclusive) {
1405             if (!inRange(fromKey, fromInclusive))
1406                 throw new IllegalArgumentException("fromKey out of range");
1407             if (!inRange(toKey, toInclusive))
1408                 throw new IllegalArgumentException("toKey out of range");
1409             return new AscendingSubMap(m,
1410                                        false, fromKey, fromInclusive,
1411                                        false, toKey,   toInclusive);
1412         }
1413 
1414         // 獲取“Map的頭部”。
1415         // 範圍從第一個節點 到 toKey, inclusive是是否包含toKey的標記
1416         public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1417             if (!inRange(toKey, inclusive))
1418                 throw new IllegalArgumentException("toKey out of range");
1419             return new AscendingSubMap(m,
1420                                        fromStart, lo,    loInclusive,
1421                                        false,     toKey, inclusive);
1422         }
1423 
1424         // 獲取“Map的尾部”。
1425         // 範圍是從 fromKey 到 最後一個節點,inclusive是是否包含fromKey的標記
1426         public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1427             if (!inRange(fromKey, inclusive))
1428                 throw new IllegalArgumentException("fromKey out of range");
1429             return new AscendingSubMap(m,
1430                                        false, fromKey, inclusive,
1431                                        toEnd, hi,      hiInclusive);
1432         }
1433 
1434         // 獲取對應的降序Map
1435         public NavigableMap<K,V> descendingMap() {
1436             NavigableMap<K,V> mv = descendingMapView;
1437             return (mv != null) ? mv :
1438                 (descendingMapView =
1439                  new DescendingSubMap(m,
1440                                       fromStart, lo, loInclusive,
1441                                       toEnd,     hi, hiInclusive));
1442         }
1443 
1444         // 返回“升序Key迭代器”
1445         Iterator<K> keyIterator() {
1446             return new SubMapKeyIterator(absLowest(), absHighFence());
1447         }
1448 
1449         // 返回“降序Key迭代器”
1450         Iterator<K> descendingKeyIterator() {
1451             return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1452         }
1453 
1454         // “升序EntrySet集合”類
1455         // 實現了iterator()
1456         final class AscendingEntrySetView extends EntrySetView {
1457             public Iterator<Map.Entry<K,V>> iterator() {
1458                 return new SubMapEntryIterator(absLowest(), absHighFence());
1459             }
1460         }
1461 
1462         // 返回“升序EntrySet集合”
1463         public Set<Map.Entry<K,V>> entrySet() {
1464             EntrySetView es = entrySetView;
1465             return (es != null) ? es : new AscendingEntrySetView();
1466         }
1467 
1468         TreeMap.Entry<K,V> subLowest()       { return absLowest(); }
1469         TreeMap.Entry<K,V> subHighest()      { return absHighest(); }
1470         TreeMap.Entry<K,V> subCeiling(K key) { return absCeiling(key); }
1471         TreeMap.Entry<K,V> subHigher(K key)  { return absHigher(key); }
1472         TreeMap.Entry<K,V> subFloor(K key)   { return absFloor(key); }
1473         TreeMap.Entry<K,V> subLower(K key)   { return absLower(key); }
1474     }
1475 
1476     // 降序的SubMap,繼承於NavigableSubMap
1477     // 相比於升序SubMap,它的實現機制是將“SubMap的比較器反轉”!
1478     static final class DescendingSubMap<K,V>  extends NavigableSubMap<K,V> {
1479         private static final long serialVersionUID = 912986545866120460L;
1480         DescendingSubMap(TreeMap<K,V> m,
1481                         boolean fromStart, K lo, boolean loInclusive,
1482                         boolean toEnd,     K hi, boolean hiInclusive) {
1483             super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1484         }
1485 
1486         // 反轉的比較器:是將原始比較器反轉得到的。
1487         private final Comparator<? super K> reverseComparator =
1488             Collections.reverseOrder(m.comparator);
1489 
1490         // 獲取反轉比較器
1491         public Comparator<? super K> comparator() {
1492             return reverseComparator;
1493         }
1494 
1495         // 獲取“子Map”。
1496         // 範圍是從fromKey 到 toKey;fromInclusive是是否包含fromKey的標記,toInclusive是是否包含toKey的標記
1497         public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1498                                         K toKey,   boolean toInclusive) {
1499             if (!inRange(fromKey, fromInclusive))
1500                 throw new IllegalArgumentException("fromKey out of range");
1501             if (!inRange(toKey, toInclusive))
1502                 throw new IllegalArgumentException("toKey out of range");
1503             return new DescendingSubMap(m,
1504                                         false, toKey,   toInclusive,
1505                                         false, fromKey, fromInclusive);
1506         }
1507 
1508         // 獲取“Map的頭部”。
1509         // 範圍從第一個節點 到 toKey, inclusive是是否包含toKey的標記
1510         public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1511             if (!inRange(toKey, inclusive))
1512                 throw new IllegalArgumentException("toKey out of range");
1513             return new DescendingSubMap(m,
1514                                         false, toKey, inclusive,
1515                                         toEnd, hi,    hiInclusive);
1516         }
1517 
1518         // 獲取“Map的尾部”。
1519         // 範圍是從 fromKey 到 最後一個節點,inclusive是是否包含fromKey的標記
1520         public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1521             if (!inRange(fromKey, inclusive))
1522                 throw new IllegalArgumentException("fromKey out of range");
1523             return new DescendingSubMap(m,
1524                                         fromStart, lo, loInclusive,
1525                                         false, fromKey, inclusive);
1526         }
1527 
1528         // 獲取對應的降序Map
1529         public NavigableMap<K,V> descendingMap() {
1530             NavigableMap<K,V> mv = descendingMapView;
1531             return (mv != null) ? mv :
1532                 (descendingMapView =
1533                  new AscendingSubMap(m,
1534                                      fromStart, lo, loInclusive,
1535                                      toEnd,     hi, hiInclusive));
1536         }
1537 
1538         // 返回“升序Key迭代器”
1539         Iterator<K> keyIterator() {
1540             return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1541         }
1542 
1543         // 返回“降序Key迭代器”
1544         Iterator<K> descendingKeyIterator() {
1545             return new SubMapKeyIterator(absLowest(), absHighFence());
1546         }
1547 
1548         // “降序EntrySet集合”類
1549         // 實現了iterator()
1550         final class DescendingEntrySetView extends EntrySetView {
1551             public Iterator<Map.Entry<K,V>> iterator() {
1552                 return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
1553             }
1554         }
1555 
1556         // 返回“降序EntrySet集合”
1557         public Set<Map.Entry<K,V>> entrySet() {
1558             EntrySetView es = entrySetView;
1559             return (es != null) ? es : new DescendingEntrySetView();
1560         }
1561 
1562         TreeMap.Entry<K,V> subLowest()       { return absHighest(); }
1563         TreeMap.Entry<K,V> subHighest()      { return absLowest(); }
1564         TreeMap.Entry<K,V> subCeiling(K key) { return absFloor(key); }
1565         TreeMap.Entry<K,V> subHigher(K key)  { return absLower(key); }
1566         TreeMap.Entry<K,V> subFloor(K key)   { return absCeiling(key); }
1567         TreeMap.Entry<K,V> subLower(K key)   { return absHigher(key); }
1568     }
1569 
1570     // SubMap是舊版本的類,新的Java中沒有用到。
1571     private class SubMap extends AbstractMap<K,V>
1572     implements SortedMap<K,V>, java.io.Serializable {
1573         private static final long serialVersionUID = -6520786458950516097L;
1574         private boolean fromStart = false, toEnd = false;
1575         private K fromKey, toKey;
1576         private Object readResolve() {
1577             return new AscendingSubMap(TreeMap.this,
1578                                        fromStart, fromKey, true,
1579                                        toEnd, toKey, false);
1580         }
1581         public Set<Map.Entry<K,V>> entrySet() { throw new InternalError(); }
1582         public K lastKey() { throw new InternalError(); }
1583         public K firstKey() { throw new InternalError(); }
1584         public SortedMap<K,V> subMap(K fromKey, K toKey) { throw new InternalError(); }
1585         public SortedMap<K,V> headMap(K toKey) { throw new InternalError(); }
1586         public SortedMap<K,V> tailMap(K fromKey) { throw new InternalError(); }
1587         public Comparator<? super K> comparator() { throw new InternalError(); }
1588     }
1589 
1590 
1591     // 紅黑樹的節點顏色--紅色
1592     private static final boolean RED   = false;
1593     // 紅黑樹的節點顏色--黑色
1594     private static final boolean BLACK = true;
1595 
1596     // “紅黑樹的節點”對應的類。
1597     // 包含了 key(鍵)、value(值)、left(左孩子)、right(右孩子)、parent(父節點)、color(顏色)
1598     static final class Entry<K,V> implements Map.Entry<K,V> {
1599         // 鍵
1600         K key;
1601         // 值
1602         V value;
1603         // 左孩子
1604         Entry<K,V> left = null;
1605         // 右孩子
1606         Entry<K,V> right = null;
1607         // 父節點
1608         Entry<K,V> parent;
1609         // 當前節點顏色
1610         boolean color = BLACK;
1611 
1612         // 構造函數
1613         Entry(K key, V value, Entry<K,V> parent) {
1614             this.key = key;
1615             this.value = value;
1616             this.parent = parent;
1617         }
1618 
1619         // 返回“鍵”
1620         public K getKey() {
1621             return key;
1622         }
1623 
1624         // 返回“值”
1625         public V getValue() {
1626             return value;
1627         }
1628 
1629         // 更新“值”,返回舊的值
1630         public V setValue(V value) {
1631             V oldValue = this.value;
1632             this.value = value;
1633             return oldValue;
1634         }
1635 
1636         // 判斷兩個節點是否相等的函數,覆蓋equals()函數。
1637         // 若兩個節點的“key相等”並且“value相等”,則兩個節點相等
1638         public boolean equals(Object o) {
1639             if (!(o instanceof Map.Entry))
1640                 return false;
1641             Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1642 
1643             return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
1644         }
1645 
1646         // 覆蓋hashCode函數。
1647         public int hashCode() {
1648             int keyHash = (key==null ? 0 : key.hashCode());
1649             int valueHash = (value==null ? 0 : value.hashCode());
1650             return keyHash ^ valueHash;
1651         }
1652 
1653         // 覆蓋toString()函數。
1654         public String toString() {
1655             return key + "=" + value;
1656         }
1657     }
1658 
1659     // 返回“紅黑樹的第一個節點”
1660     final Entry<K,V> getFirstEntry() {
1661         Entry<K,V> p = root;
1662         if (p != null)
1663             while (p.left != null)
1664                 p = p.left;
1665         return p;
1666     }
1667 
1668     // 返回“紅黑樹的最後一個節點”
1669     final Entry<K,V> getLastEntry() {
1670         Entry<K,V> p = root;
1671         if (p != null)
1672             while (p.right != null)
1673                 p = p.right;
1674         return p;
1675     }
1676 
1677     // 返回“節點t的後繼節點”
1678     static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
1679         if (t == null)
1680             return null;
1681         else if (t.right != null) {
1682             Entry<K,V> p = t.right;
1683             while (p.left != null)
1684                 p = p.left;
1685             return p;
1686         } else {
1687             Entry<K,V> p = t.parent;
1688             Entry<K,V> ch = t;
1689             while (p != null && ch == p.right) {
1690                 ch = p;
1691                 p = p.parent;
1692             }
1693             return p;
1694         }
1695     }
1696 
1697     // 返回“節點t的前繼節點”
1698     static <K,V> Entry<K,V> predecessor(Entry<K,V> t) {
1699         if (t == null)
1700             return null;
1701         else if (t.left != null) {
1702             Entry<K,V> p = t.left;
1703             while (p.right != null)
1704                 p = p.right;
1705             return p;
1706         } else {
1707             Entry<K,V> p = t.parent;
1708             Entry<K,V> ch = t;
1709             while (p != null && ch == p.left) {
1710                 ch = p;
1711                 p = p.parent;
1712             }
1713             return p;
1714         }
1715     }
1716 
1717     // 返回“節點p的顏色”
1718     // 根據“紅黑樹的特性”可知:空節點顏色是黑色。
1719     private static <K,V> boolean colorOf(Entry<K,V> p) {
1720         return (p == null ? BLACK : p.color);
1721     }
1722 
1723     // 返回“節點p的父節點”
1724     private static <K,V> Entry<K,V> parentOf(Entry<K,V> p) {
1725         return (p == null ? null: p.parent);
1726     }
1727 
1728     // 設置“節點p的顏色爲c”
1729     private static <K,V> void setColor(Entry<K,V> p, boolean c) {
1730         if (p != null)
1731         p.color = c;
1732     }
1733 
1734     // 設置“節點p的左孩子”
1735     private static <K,V> Entry<K,V> leftOf(Entry<K,V> p) {
1736         return (p == null) ? null: p.left;
1737     }
1738 
1739     // 設置“節點p的右孩子”
1740     private static <K,V> Entry<K,V> rightOf(Entry<K,V> p) {
1741         return (p == null) ? null: p.right;
1742     }
1743 
1744     // 對節點p執行“左旋”操作
1745     private void rotateLeft(Entry<K,V> p) {
1746         if (p != null) {
1747             Entry<K,V> r = p.right;
1748             p.right = r.left;
1749             if (r.left != null)
1750                 r.left.parent = p;
1751             r.parent = p.parent;
1752             if (p.parent == null)
1753                 root = r;
1754             else if (p.parent.left == p)
1755                 p.parent.left = r;
1756             else
1757                 p.parent.right = r;
1758             r.left = p;
1759             p.parent = r;
1760         }
1761     }
1762 
1763     // 對節點p執行“右旋”操作
1764     private void rotateRight(Entry<K,V> p) {
1765         if (p != null) {
1766             Entry<K,V> l = p.left;
1767             p.left = l.right;
1768             if (l.right != null) l.right.parent = p;
1769             l.parent = p.parent;
1770             if (p.parent == null)
1771                 root = l;
1772             else if (p.parent.right == p)
1773                 p.parent.right = l;
1774             else p.parent.left = l;
1775             l.right = p;
1776             p.parent = l;
1777         }
1778     }
1779 
1780     // 插入之後的修正操作。
1781     // 目的是保證:紅黑樹插入節點之後,仍然是一顆紅黑樹
1782     private void fixAfterInsertion(Entry<K,V> x) {
1783         x.color = RED;
1784 
1785         while (x != null && x != root && x.parent.color == RED) {
1786             if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
1787                 Entry<K,V> y = rightOf(parentOf(parentOf(x)));
1788                 if (colorOf(y) == RED) {
1789                     setColor(parentOf(x), BLACK);
1790                     setColor(y, BLACK);
1791                     setColor(parentOf(parentOf(x)), RED);
1792                     x = parentOf(parentOf(x));
1793                 } else {
1794                     if (x == rightOf(parentOf(x))) {
1795                         x = parentOf(x);
1796                         rotateLeft(x);
1797                     }
1798                     setColor(parentOf(x), BLACK);
1799                     setColor(parentOf(parentOf(x)), RED);
1800                     rotateRight(parentOf(parentOf(x)));
1801                 }
1802             } else {
1803                 Entry<K,V> y = leftOf(parentOf(parentOf(x)));
1804                 if (colorOf(y) == RED) {
1805                     setColor(parentOf(x), BLACK);
1806                     setColor(y, BLACK);
1807                     setColor(parentOf(parentOf(x)), RED);
1808                     x = parentOf(parentOf(x));
1809                 } else {
1810                     if (x == leftOf(parentOf(x))) {
1811                         x = parentOf(x);
1812                         rotateRight(x);
1813                     }
1814                     setColor(parentOf(x), BLACK);
1815                     setColor(parentOf(parentOf(x)), RED);
1816                     rotateLeft(parentOf(parentOf(x)));
1817                 }
1818             }
1819         }
1820         root.color = BLACK;
1821     }
1822 
1823     // 刪除“紅黑樹的節點p”
1824     private void deleteEntry(Entry<K,V> p) {
1825         modCount++;
1826         size--;
1827 
1828         // If strictly internal, copy successor's element to p and then make p
1829         // point to successor.
1830         if (p.left != null && p.right != null) {
1831             Entry<K,V> s = successor (p);
1832             p.key = s.key;
1833             p.value = s.value;
1834             p = s;
1835         } // p has 2 children
1836 
1837         // Start fixup at replacement node, if it exists.
1838         Entry<K,V> replacement = (p.left != null ? p.left : p.right);
1839 
1840         if (replacement != null) {
1841             // Link replacement to parent
1842             replacement.parent = p.parent;
1843             if (p.parent == null)
1844                 root = replacement;
1845             else if (p == p.parent.left)
1846                 p.parent.left  = replacement;
1847             else
1848                 p.parent.right = replacement;
1849 
1850             // Null out links so they are OK to use by fixAfterDeletion.
1851             p.left = p.right = p.parent = null;
1852 
1853             // Fix replacement
1854             if (p.color == BLACK)
1855                 fixAfterDeletion(replacement);
1856         } else if (p.parent == null) { // return if we are the only node.
1857             root = null;
1858         } else { //  No children. Use self as phantom replacement and unlink.
1859             if (p.color == BLACK)
1860                 fixAfterDeletion(p);
1861 
1862             if (p.parent != null) {
1863                 if (p == p.parent.left)
1864                     p.parent.left = null;
1865                 else if (p == p.parent.right)
1866                     p.parent.right = null;
1867                 p.parent = null;
1868             }
1869         }
1870     }
1871 
1872     // 刪除之後的修正操作。
1873     // 目的是保證:紅黑樹刪除節點之後,仍然是一顆紅黑樹
1874     private void fixAfterDeletion(Entry<K,V> x) {
1875         while (x != root && colorOf(x) == BLACK) {
1876             if (x == leftOf(parentOf(x))) {
1877                 Entry<K,V> sib = rightOf(parentOf(x));
1878 
1879                 if (colorOf(sib) == RED) {
1880                     setColor(sib, BLACK);
1881                     setColor(parentOf(x), RED);
1882                     rotateLeft(parentOf(x));
1883                     sib = rightOf(parentOf(x));
1884                 }
1885 
1886                 if (colorOf(leftOf(sib))  == BLACK &&
1887                     colorOf(rightOf(sib)) == BLACK) {
1888                     setColor(sib, RED);
1889                     x = parentOf(x);
1890                 } else {
1891                     if (colorOf(rightOf(sib)) == BLACK) {
1892                         setColor(leftOf(sib), BLACK);
1893                         setColor(sib, RED);
1894                         rotateRight(sib);
1895                         sib = rightOf(parentOf(x));
1896                     }
1897                     setColor(sib, colorOf(parentOf(x)));
1898                     setColor(parentOf(x), BLACK);
1899                     setColor(rightOf(sib), BLACK);
1900                     rotateLeft(parentOf(x));
1901                     x = root;
1902                 }
1903             } else { // symmetric
1904                 Entry<K,V> sib = leftOf(parentOf(x));
1905 
1906                 if (colorOf(sib) == RED) {
1907                     setColor(sib, BLACK);
1908                     setColor(parentOf(x), RED);
1909                     rotateRight(parentOf(x));
1910                     sib = leftOf(parentOf(x));
1911                 }
1912 
1913                 if (colorOf(rightOf(sib)) == BLACK &&
1914                     colorOf(leftOf(sib)) == BLACK) {
1915                     setColor(sib, RED);
1916                     x = parentOf(x);
1917                 } else {
1918                     if (colorOf(leftOf(sib)) == BLACK) {
1919                         setColor(rightOf(sib), BLACK);
1920                         setColor(sib, RED);
1921                         rotateLeft(sib);
1922                         sib = leftOf(parentOf(x));
1923                     }
1924                     setColor(sib, colorOf(parentOf(x)));
1925                     setColor(parentOf(x), BLACK);
1926                     setColor(leftOf(sib), BLACK);
1927                     rotateRight(parentOf(x));
1928                     x = root;
1929                 }
1930             }
1931         }
1932 
1933         setColor(x, BLACK);
1934     }
1935 
1936     private static final long serialVersionUID = 919286545866124006L;
1937 
1938     // java.io.Serializable的寫入函數
1939     // 將TreeMap的“容量,所有的Entry”都寫入到輸出流中
1940     private void writeObject(java.io.ObjectOutputStream s)
1941         throws java.io.IOException {
1942         // Write out the Comparator and any hidden stuff
1943         s.defaultWriteObject();
1944 
1945         // Write out size (number of Mappings)
1946         s.writeInt(size);
1947 
1948         // Write out keys and values (alternating)
1949         for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) {
1950             Map.Entry<K,V> e = i.next();
1951             s.writeObject(e.getKey());
1952             s.writeObject(e.getValue());
1953         }
1954     }
1955 
1956 
1957     // java.io.Serializable的讀取函數:根據寫入方式讀出
1958     // 先將TreeMap的“容量、所有的Entry”依次讀出
1959     private void readObject(final java.io.ObjectInputStream s)
1960         throws java.io.IOException, ClassNotFoundException {
1961         // Read in the Comparator and any hidden stuff
1962         s.defaultReadObject();
1963 
1964         // Read in size
1965         int size = s.readInt();
1966 
1967         buildFromSorted(size, null, s, null);
1968     }
1969 
1970     // 根據已經一個排好序的map創建一個TreeMap
1971     private void buildFromSorted(int size, Iterator it,
1972                  java.io.ObjectInputStream str,
1973                  V defaultVal)
1974         throws  java.io.IOException, ClassNotFoundException {
1975         this.size = size;
1976         root = buildFromSorted(0, 0, size-1, computeRedLevel(size),
1977                    it, str, defaultVal);
1978     }
1979 
1980     // 根據已經一個排好序的map創建一個TreeMap
1981     // 將map中的元素逐個添加到TreeMap中,並返回map的中間元素作爲根節點。
1982     private final Entry<K,V> buildFromSorted(int level, int lo, int hi,
1983                          int redLevel,
1984                          Iterator it,
1985                          java.io.ObjectInputStream str,
1986                          V defaultVal)
1987         throws  java.io.IOException, ClassNotFoundException {
1988 
1989         if (hi < lo) return null;
1990 
1991       
1992         // 獲取中間元素
1993         int mid = (lo + hi) / 2;
1994 
1995         Entry<K,V> left  = null;
1996         // 若lo小於mid,則遞歸調用獲取(middel的)左孩子。
1997         if (lo < mid)
1998             left = buildFromSorted(level+1, lo, mid - 1, redLevel,
1999                    it, str, defaultVal);
2000 
2001         // 獲取middle節點對應的key和value
2002         K key;
2003         V value;
2004         if (it != null) {
2005             if (defaultVal==null) {
2006                 Map.Entry<K,V> entry = (Map.Entry<K,V>)it.next();
2007                 key = entry.getKey();
2008                 value = entry.getValue();
2009             } else {
2010                 key = (K)it.next();
2011                 value = defaultVal;
2012             }
2013         } else { // use stream
2014             key = (K) str.readObject();
2015             value = (defaultVal != null ? defaultVal : (V) str.readObject());
2016         }
2017 
2018         // 創建middle節點
2019         Entry<K,V> middle =  new Entry<K,V>(key, value, null);
2020 
2021         // 若當前節點的深度=紅色節點的深度,則將節點着色爲紅色。
2022         if (level == redLevel)
2023             middle.color = RED;
2024 
2025         // 設置middle爲left的父親,left爲middle的左孩子
2026         if (left != null) {
2027             middle.left = left;
2028             left.parent = middle;
2029         }
2030 
2031         if (mid < hi) {
2032             // 遞歸調用獲取(middel的)右孩子。
2033             Entry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel,
2034                            it, str, defaultVal);
2035             // 設置middle爲left的父親,left爲middle的左孩子
2036             middle.right = right;
2037             right.parent = middle;
2038         }
2039 
2040         return middle;
2041     }
2042 
2043     // 計算節點樹爲sz的最大深度,也是紅色節點的深度值。
2044     private static int computeRedLevel(int sz) {
2045         int level = 0;
2046         for (int m = sz - 1; m >= 0; m = m / 2 - 1)
2047             level++;
2048         return level;
2049     }
2050 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358
  • 359
  • 360
  • 361
  • 362
  • 363
  • 364
  • 365
  • 366
  • 367
  • 368
  • 369
  • 370
  • 371
  • 372
  • 373
  • 374
  • 375
  • 376
  • 377
  • 378
  • 379
  • 380
  • 381
  • 382
  • 383
  • 384
  • 385
  • 386
  • 387
  • 388
  • 389
  • 390
  • 391
  • 392
  • 393
  • 394
  • 395
  • 396
  • 397
  • 398
  • 399
  • 400
  • 401
  • 402
  • 403
  • 404
  • 405
  • 406
  • 407
  • 408
  • 409
  • 410
  • 411
  • 412
  • 413
  • 414
  • 415
  • 416
  • 417
  • 418
  • 419
  • 420
  • 421
  • 422
  • 423
  • 424
  • 425
  • 426
  • 427
  • 428
  • 429
  • 430
  • 431
  • 432
  • 433
  • 434
  • 435
  • 436
  • 437
  • 438
  • 439
  • 440
  • 441
  • 442
  • 443
  • 444
  • 445
  • 446
  • 447
  • 448
  • 449
  • 450
  • 451
  • 452
  • 453
  • 454
  • 455
  • 456
  • 457
  • 458
  • 459
  • 460
  • 461
  • 462
  • 463
  • 464
  • 465
  • 466
  • 467
  • 468
  • 469
  • 470
  • 471
  • 472
  • 473
  • 474
  • 475
  • 476
  • 477
  • 478
  • 479
  • 480
  • 481
  • 482
  • 483
  • 484
  • 485
  • 486
  • 487
  • 488
  • 489
  • 490
  • 491
  • 492
  • 493
  • 494
  • 495
  • 496
  • 497
  • 498
  • 499
  • 500
  • 501
  • 502
  • 503
  • 504
  • 505
  • 506
  • 507
  • 508
  • 509
  • 510
  • 511
  • 512
  • 513
  • 514
  • 515
  • 516
  • 517
  • 518
  • 519
  • 520
  • 521
  • 522
  • 523
  • 524
  • 525
  • 526
  • 527
  • 528
  • 529
  • 530
  • 531
  • 532
  • 533
  • 534
  • 535
  • 536
  • 537
  • 538
  • 539
  • 540
  • 541
  • 542
  • 543
  • 544
  • 545
  • 546
  • 547
  • 548
  • 549
  • 550
  • 551
  • 552
  • 553
  • 554
  • 555
  • 556
  • 557
  • 558
  • 559
  • 560
  • 561
  • 562
  • 563
  • 564
  • 565
  • 566
  • 567
  • 568
  • 569
  • 570
  • 571
  • 572
  • 573
  • 574
  • 575
  • 576
  • 577
  • 578
  • 579
  • 580
  • 581
  • 582
  • 583
  • 584
  • 585
  • 586
  • 587
  • 588
  • 589
  • 590
  • 591
  • 592
  • 593
  • 594
  • 595
  • 596
  • 597
  • 598
  • 599
  • 600
  • 601
  • 602
  • 603
  • 604
  • 605
  • 606
  • 607
  • 608
  • 609
  • 610
  • 611
  • 612
  • 613
  • 614
  • 615
  • 616
  • 617
  • 618
  • 619
  • 620
  • 621
  • 622
  • 623
  • 624
  • 625
  • 626
  • 627
  • 628
  • 629
  • 630
  • 631
  • 632
  • 633
  • 634
  • 635
  • 636
  • 637
  • 638
  • 639
  • 640
  • 641
  • 642
  • 643
  • 644
  • 645
  • 646
  • 647
  • 648
  • 649
  • 650
  • 651
  • 652
  • 653
  • 654
  • 655
  • 656
  • 657
  • 658
  • 659
  • 660
  • 661
  • 662
  • 663
  • 664
  • 665
  • 666
  • 667
  • 668
  • 669
  • 670
  • 671
  • 672
  • 673
  • 674
  • 675
  • 676
  • 677
  • 678
  • 679
  • 680
  • 681
  • 682
  • 683
  • 684
  • 685
  • 686
  • 687
  • 688
  • 689
  • 690
  • 691
  • 692
  • 693
  • 694
  • 695
  • 696
  • 697
  • 698
  • 699
  • 700
  • 701
  • 702
  • 703
  • 704
  • 705
  • 706
  • 707
  • 708
  • 709
  • 710
  • 711
  • 712
  • 713
  • 714
  • 715
  • 716
  • 717
  • 718
  • 719
  • 720
  • 721
  • 722
  • 723
  • 724
  • 725
  • 726
  • 727
  • 728
  • 729
  • 730
  • 731
  • 732
  • 733
  • 734
  • 735
  • 736
  • 737
  • 738
  • 739
  • 740
  • 741
  • 742
  • 743
  • 744
  • 745
  • 746
  • 747
  • 748
  • 749
  • 750
  • 751
  • 752
  • 753
  • 754
  • 755
  • 756
  • 757
  • 758
  • 759
  • 760
  • 761
  • 762
  • 763
  • 764
  • 765
  • 766
  • 767
  • 768
  • 769
  • 770
  • 771
  • 772
  • 773
  • 774
  • 775
  • 776
  • 777
  • 778
  • 779
  • 780
  • 781
  • 782
  • 783
  • 784
  • 785
  • 786
  • 787
  • 788
  • 789
  • 790
  • 791
  • 792
  • 793
  • 794
  • 795
  • 796
  • 797
  • 798
  • 799
  • 800
  • 801
  • 802
  • 803
  • 804
  • 805
  • 806
  • 807
  • 808
  • 809
  • 810
  • 811
  • 812
  • 813
  • 814
  • 815
  • 816
  • 817
  • 818
  • 819
  • 820
  • 821
  • 822
  • 823
  • 824
  • 825
  • 826
  • 827
  • 828
  • 829
  • 830
  • 831
  • 832
  • 833
  • 834
  • 835
  • 836
  • 837
  • 838
  • 839
  • 840
  • 841
  • 842
  • 843
  • 844
  • 845
  • 846
  • 847
  • 848
  • 849
  • 850
  • 851
  • 852
  • 853
  • 854
  • 855
  • 856
  • 857
  • 858
  • 859
  • 860
  • 861
  • 862
  • 863
  • 864
  • 865
  • 866
  • 867
  • 868
  • 869
  • 870
  • 871
  • 872
  • 873
  • 874
  • 875
  • 876
  • 877
  • 878
  • 879
  • 880
  • 881
  • 882
  • 883
  • 884
  • 885
  • 886
  • 887
  • 888
  • 889
  • 890
  • 891
  • 892
  • 893
  • 894
  • 895
  • 896
  • 897
  • 898
  • 899
  • 900
  • 901
  • 902
  • 903
  • 904
  • 905
  • 906
  • 907
  • 908
  • 909
  • 910
  • 911
  • 912
  • 913
  • 914
  • 915
  • 916
  • 917
  • 918
  • 919
  • 920
  • 921
  • 922
  • 923
  • 924
  • 925
  • 926
  • 927
  • 928
  • 929
  • 930
  • 931
  • 932
  • 933
  • 934
  • 935
  • 936
  • 937
  • 938
  • 939
  • 940
  • 941
  • 942
  • 943
  • 944
  • 945
  • 946
  • 947
  • 948
  • 949
  • 950
  • 951
  • 952
  • 953
  • 954
  • 955
  • 956
  • 957
  • 958
  • 959
  • 960
  • 961
  • 962
  • 963
  • 964
  • 965
  • 966
  • 967
  • 968
  • 969
  • 970
  • 971
  • 972
  • 973
  • 974
  • 975
  • 976
  • 977
  • 978
  • 979
  • 980
  • 981
  • 982
  • 983
  • 984
  • 985
  • 986
  • 987
  • 988
  • 989
  • 990
  • 991
  • 992
  • 993
  • 994
  • 995
  • 996
  • 997
  • 998
  • 999
  • 1000
  • 1001
  • 1002
  • 1003
  • 1004
  • 1005
  • 1006
  • 1007
  • 1008
  • 1009
  • 1010
  • 1011
  • 1012
  • 1013
  • 1014
  • 1015
  • 1016
  • 1017
  • 1018
  • 1019
  • 1020
  • 1021
  • 1022
  • 1023
  • 1024
  • 1025
  • 1026
  • 1027
  • 1028
  • 1029
  • 1030
  • 1031
  • 1032
  • 1033
  • 1034
  • 1035
  • 1036
  • 1037
  • 1038
  • 1039
  • 1040
  • 1041
  • 1042
  • 1043
  • 1044
  • 1045
  • 1046
  • 1047
  • 1048
  • 1049
  • 1050
  • 1051
  • 1052
  • 1053
  • 1054
  • 1055
  • 1056
  • 1057
  • 1058
  • 1059
  • 1060
  • 1061
  • 1062
  • 1063
  • 1064
  • 1065
  • 1066
  • 1067
  • 1068
  • 1069
  • 1070
  • 1071
  • 1072
  • 1073
  • 1074
  • 1075
  • 1076
  • 1077
  • 1078
  • 1079
  • 1080
  • 1081
  • 1082
  • 1083
  • 1084
  • 1085
  • 1086
  • 1087
  • 1088
  • 1089
  • 1090
  • 1091
  • 1092
  • 1093
  • 1094
  • 1095
  • 1096
  • 1097
  • 1098
  • 1099
  • 1100
  • 1101
  • 1102
  • 1103
  • 1104
  • 1105
  • 1106
  • 1107
  • 1108
  • 1109
  • 1110
  • 1111
  • 1112
  • 1113
  • 1114
  • 1115
  • 1116
  • 1117
  • 1118
  • 1119
  • 1120
  • 1121
  • 1122
  • 1123
  • 1124
  • 1125
  • 1126
  • 1127
  • 1128
  • 1129
  • 1130
  • 1131
  • 1132
  • 1133
  • 1134
  • 1135
  • 1136
  • 1137
  • 1138
  • 1139
  • 1140
  • 1141
  • 1142
  • 1143
  • 1144
  • 1145
  • 1146
  • 1147
  • 1148
  • 1149
  • 1150
  • 1151
  • 1152
  • 1153
  • 1154
  • 1155
  • 1156
  • 1157
  • 1158
  • 1159
  • 1160
  • 1161
  • 1162
  • 1163
  • 1164
  • 1165
  • 1166
  • 1167
  • 1168
  • 1169
  • 1170
  • 1171
  • 1172
  • 1173
  • 1174
  • 1175
  • 1176
  • 1177
  • 1178
  • 1179
  • 1180
  • 1181
  • 1182
  • 1183
  • 1184
  • 1185
  • 1186
  • 1187
  • 1188
  • 1189
  • 1190
  • 1191
  • 1192
  • 1193
  • 1194
  • 1195
  • 1196
  • 1197
  • 1198
  • 1199
  • 1200
  • 1201
  • 1202
  • 1203
  • 1204
  • 1205
  • 1206
  • 1207
  • 1208
  • 1209
  • 1210
  • 1211
  • 1212
  • 1213
  • 1214
  • 1215
  • 1216
  • 1217
  • 1218
  • 1219
  • 1220
  • 1221
  • 1222
  • 1223
  • 1224
  • 1225
  • 1226
  • 1227
  • 1228
  • 1229
  • 1230
  • 1231
  • 1232
  • 1233
  • 1234
  • 1235
  • 1236
  • 1237
  • 1238
  • 1239
  • 1240
  • 1241
  • 1242
  • 1243
  • 1244
  • 1245
  • 1246
  • 1247
  • 1248
  • 1249
  • 1250
  • 1251
  • 1252
  • 1253
  • 1254
  • 1255
  • 1256
  • 1257
  • 1258
  • 1259
  • 1260
  • 1261
  • 1262
  • 1263
  • 1264
  • 1265
  • 1266
  • 1267
  • 1268
  • 1269
  • 1270
  • 1271
  • 1272
  • 1273
  • 1274
  • 1275
  • 1276
  • 1277
  • 1278
  • 1279
  • 1280
  • 1281
  • 1282
  • 1283
  • 1284
  • 1285
  • 1286
  • 1287
  • 1288
  • 1289
  • 1290
  • 1291
  • 1292
  • 1293
  • 1294
  • 1295
  • 1296
  • 1297
  • 1298
  • 1299
  • 1300
  • 1301
  • 1302
  • 1303
  • 1304
  • 1305
  • 1306
  • 1307
  • 1308
  • 1309
  • 1310
  • 1311
  • 1312
  • 1313
  • 1314
  • 1315
  • 1316
  • 1317
  • 1318
  • 1319
  • 1320
  • 1321
  • 1322
  • 1323
  • 1324
  • 1325
  • 1326
  • 1327
  • 1328
  • 1329
  • 1330
  • 1331
  • 1332
  • 1333
  • 1334
  • 1335
  • 1336
  • 1337
  • 1338
  • 1339
  • 1340
  • 1341
  • 1342
  • 1343
  • 1344
  • 1345
  • 1346
  • 1347
  • 1348
  • 1349
  • 1350
  • 1351
  • 1352
  • 1353
  • 1354
  • 1355
  • 1356
  • 1357
  • 1358
  • 1359
  • 1360
  • 1361
  • 1362
  • 1363
  • 1364
  • 1365
  • 1366
  • 1367
  • 1368
  • 1369
  • 1370
  • 1371
  • 1372
  • 1373
  • 1374
  • 1375
  • 1376
  • 1377
  • 1378
  • 1379
  • 1380
  • 1381
  • 1382
  • 1383
  • 1384
  • 1385
  • 1386
  • 1387
  • 1388
  • 1389
  • 1390
  • 1391
  • 1392
  • 1393
  • 1394
  • 1395
  • 1396
  • 1397
  • 1398
  • 1399
  • 1400
  • 1401
  • 1402
  • 1403
  • 1404
  • 1405
  • 1406
  • 1407
  • 1408
  • 1409
  • 1410
  • 1411
  • 1412
  • 1413
  • 1414
  • 1415
  • 1416
  • 1417
  • 1418
  • 1419
  • 1420
  • 1421
  • 1422
  • 1423
  • 1424
  • 1425
  • 1426
  • 1427
  • 1428
  • 1429
  • 1430
  • 1431
  • 1432
  • 1433
  • 1434
  • 1435
  • 1436
  • 1437
  • 1438
  • 1439
  • 1440
  • 1441
  • 1442
  • 1443
  • 1444
  • 1445
  • 1446
  • 1447
  • 1448
  • 1449
  • 1450
  • 1451
  • 1452
  • 1453
  • 1454
  • 1455
  • 1456
  • 1457
  • 1458
  • 1459
  • 1460
  • 1461
  • 1462
  • 1463
  • 1464
  • 1465
  • 1466
  • 1467
  • 1468
  • 1469
  • 1470
  • 1471
  • 1472
  • 1473
  • 1474
  • 1475
  • 1476
  • 1477
  • 1478
  • 1479
  • 1480
  • 1481
  • 1482
  • 1483
  • 1484
  • 1485
  • 1486
  • 1487
  • 1488
  • 1489
  • 1490
  • 1491
  • 1492
  • 1493
  • 1494
  • 1495
  • 1496
  • 1497
  • 1498
  • 1499
  • 1500
  • 1501
  • 1502
  • 1503
  • 1504
  • 1505
  • 1506
  • 1507
  • 1508
  • 1509
  • 1510
  • 1511
  • 1512
  • 1513
  • 1514
  • 1515
  • 1516
  • 1517
  • 1518
  • 1519
  • 1520
  • 1521
  • 1522
  • 1523
  • 1524
  • 1525
  • 1526
  • 1527
  • 1528
  • 1529
  • 1530
  • 1531
  • 1532
  • 1533
  • 1534
  • 1535
  • 1536
  • 1537
  • 1538
  • 1539
  • 1540
  • 1541
  • 1542
  • 1543
  • 1544
  • 1545
  • 1546
  • 1547
  • 1548
  • 1549
  • 1550
  • 1551
  • 1552
  • 1553
  • 1554
  • 1555
  • 1556
  • 1557
  • 1558
  • 1559
  • 1560
  • 1561
  • 1562
  • 1563
  • 1564
  • 1565
  • 1566
  • 1567
  • 1568
  • 1569
  • 1570
  • 1571
  • 1572
  • 1573
  • 1574
  • 1575
  • 1576
  • 1577
  • 1578
  • 1579
  • 1580
  • 1581
  • 1582
  • 1583
  • 1584
  • 1585
  • 1586
  • 1587
  • 1588
  • 1589
  • 1590
  • 1591
  • 1592
  • 1593
  • 1594
  • 1595
  • 1596
  • 1597
  • 1598
  • 1599
  • 1600
  • 1601
  • 1602
  • 1603
  • 1604
  • 1605
  • 1606
  • 1607
  • 1608
  • 1609
  • 1610
  • 1611
  • 1612
  • 1613
  • 1614
  • 1615
  • 1616
  • 1617
  • 1618
  • 1619
  • 1620
  • 1621
  • 1622
  • 1623
  • 1624
  • 1625
  • 1626
  • 1627
  • 1628
  • 1629
  • 1630
  • 1631
  • 1632
  • 1633
  • 1634
  • 1635
  • 1636
  • 1637
  • 1638
  • 1639
  • 1640
  • 1641
  • 1642
  • 1643
  • 1644
  • 1645
  • 1646
  • 1647
  • 1648
  • 1649
  • 1650
  • 1651
  • 1652
  • 1653
  • 1654
  • 1655
  • 1656
  • 1657
  • 1658
  • 1659
  • 1660
  • 1661
  • 1662
  • 1663
  • 1664
  • 1665
  • 1666
  • 1667
  • 1668
  • 1669
  • 1670
  • 1671
  • 1672
  • 1673
  • 1674
  • 1675
  • 1676
  • 1677
  • 1678
  • 1679
  • 1680
  • 1681
  • 1682
  • 1683
  • 1684
  • 1685
  • 1686
  • 1687
  • 1688
  • 1689
  • 1690
  • 1691
  • 1692
  • 1693
  • 1694
  • 1695
  • 1696
  • 1697
  • 1698
  • 1699
  • 1700
  • 1701
  • 1702
  • 1703
  • 1704
  • 1705
  • 1706
  • 1707
  • 1708
  • 1709
  • 1710
  • 1711
  • 1712
  • 1713
  • 1714
  • 1715
  • 1716
  • 1717
  • 1718
  • 1719
  • 1720
  • 1721
  • 1722
  • 1723
  • 1724
  • 1725
  • 1726
  • 1727
  • 1728
  • 1729
  • 1730
  • 1731
  • 1732
  • 1733
  • 1734
  • 1735
  • 1736
  • 1737
  • 1738
  • 1739
  • 1740
  • 1741
  • 1742
  • 1743
  • 1744
  • 1745
  • 1746
  • 1747
  • 1748
  • 1749
  • 1750
  • 1751
  • 1752
  • 1753
  • 1754
  • 1755
  • 1756
  • 1757
  • 1758
  • 1759
  • 1760
  • 1761
  • 1762
  • 1763
  • 1764
  • 1765
  • 1766
  • 1767
  • 1768
  • 1769
  • 1770
  • 1771
  • 1772
  • 1773
  • 1774
  • 1775
  • 1776
  • 1777
  • 1778
  • 1779
  • 1780
  • 1781
  • 1782
  • 1783
  • 1784
  • 1785
  • 1786
  • 1787
  • 1788
  • 1789
  • 1790
  • 1791
  • 1792
  • 1793
  • 1794
  • 1795
  • 1796
  • 1797
  • 1798
  • 1799
  • 1800
  • 1801
  • 1802
  • 1803
  • 1804
  • 1805
  • 1806
  • 1807
  • 1808
  • 1809
  • 1810
  • 1811
  • 1812
  • 1813
  • 1814
  • 1815
  • 1816
  • 1817
  • 1818
  • 1819
  • 1820
  • 1821
  • 1822
  • 1823
  • 1824
  • 1825
  • 1826
  • 1827
  • 1828
  • 1829
  • 1830
  • 1831
  • 1832
  • 1833
  • 1834
  • 1835
  • 1836
  • 1837
  • 1838
  • 1839
  • 1840
  • 1841
  • 1842
  • 1843
  • 1844
  • 1845
  • 1846
  • 1847
  • 1848
  • 1849
  • 1850
  • 1851
  • 1852
  • 1853
  • 1854
  • 1855
  • 1856
  • 1857
  • 1858
  • 1859
  • 1860
  • 1861
  • 1862
  • 1863
  • 1864
  • 1865
  • 1866
  • 1867
  • 1868
  • 1869
  • 1870
  • 1871
  • 1872
  • 1873
  • 1874
  • 1875
  • 1876
  • 1877
  • 1878
  • 1879
  • 1880
  • 1881
  • 1882
  • 1883
  • 1884
  • 1885
  • 1886
  • 1887
  • 1888
  • 1889
  • 1890
  • 1891
  • 1892
  • 1893
  • 1894
  • 1895
  • 1896
  • 1897
  • 1898
  • 1899
  • 1900
  • 1901
  • 1902
  • 1903
  • 1904
  • 1905
  • 1906
  • 1907
  • 1908
  • 1909
  • 1910
  • 1911
  • 1912
  • 1913
  • 1914
  • 1915
  • 1916
  • 1917
  • 1918
  • 1919
  • 1920
  • 1921
  • 1922
  • 1923
  • 1924
  • 1925
  • 1926
  • 1927
  • 1928
  • 1929
  • 1930
  • 1931
  • 1932
  • 1933
  • 1934
  • 1935
  • 1936
  • 1937
  • 1938
  • 1939
  • 1940
  • 1941
  • 1942
  • 1943
  • 1944
  • 1945
  • 1946
  • 1947
  • 1948
  • 1949
  • 1950
  • 1951
  • 1952
  • 1953
  • 1954
  • 1955
  • 1956
  • 1957
  • 1958
  • 1959
  • 1960
  • 1961
  • 1962
  • 1963
  • 1964
  • 1965
  • 1966
  • 1967
  • 1968
  • 1969
  • 1970
  • 1971
  • 1972
  • 1973
  • 1974
  • 1975
  • 1976
  • 1977
  • 1978
  • 1979
  • 1980
  • 1981
  • 1982
  • 1983
  • 1984
  • 1985
  • 1986
  • 1987
  • 1988
  • 1989
  • 1990
  • 1991
  • 1992
  • 1993
  • 1994
  • 1995
  • 1996
  • 1997
  • 1998
  • 1999
  • 2000
  • 2001
  • 2002
  • 2003
  • 2004
  • 2005
  • 2006
  • 2007
  • 2008
  • 2009
  • 2010
  • 2011
  • 2012
  • 2013
  • 2014
  • 2015
  • 2016
  • 2017
  • 2018
  • 2019
  • 2020
  • 2021
  • 2022
  • 2023
  • 2024
  • 2025
  • 2026
  • 2027
  • 2028
  • 2029
  • 2030
  • 2031
  • 2032
  • 2033
  • 2034
  • 2035
  • 2036
  • 2037
  • 2038
  • 2039
  • 2040
  • 2041
  • 2042
  • 2043
  • 2044
  • 2045
  • 2046
  • 2047
  • 2048
  • 2049
  • 2050

說明:

在詳細介紹TreeMap的代碼之前,我們先建立一個整體概念。 

TreeMap是通過紅黑樹實現的,TreeMap存儲的是key-value鍵值對,TreeMap的排序是基於對key的排序。 
TreeMap提供了操作“key”、“key-value”、“value”等方法,也提供了對TreeMap這顆樹進行整體操作的方法,如獲取子樹、反向樹。 

後面的解說內容分爲幾部分, 

首先,介紹TreeMap的核心,即紅黑樹相關部分; 
然後,介紹TreeMap的主要函數; 
再次,介紹TreeMap實現的幾個接口; 
最後,補充介紹TreeMap的其它內容。 

TreeMap本質上是一顆紅黑樹。要徹底理解TreeMap,建議讀者先理解紅黑樹。關於紅黑樹的原理,可以參考:紅黑樹(一) 原理和算法詳細介紹

第3.1部分 TreeMap的紅黑樹相關內容

TreeMap中於紅黑樹相關的主要函數有:

1 數據結構

1.1 紅黑樹的節點顏色–紅色
private static final boolean RED = false;
  • 1

1.2 紅黑樹的節點顏色–黑色
private static final boolean BLACK = true;
  • 1

1.3 “紅黑樹的節點”對應的類。

static final class Entry

2 相關操作

2.1 左旋
private void rotateLeft(Entry<K,V> p) { ... }
  • 1

2.2 右旋
private void rotateRight(Entry<K,V> p) { ... }
  • 1

2.3 插入操作
public V put(K key, V value) { ... }
  • 1

2.4 插入修正操作

紅黑樹執行插入操作之後,要執行“插入修正操作”。 
目的是:保紅黑樹在進行插入節點之後,仍然是一顆紅黑樹

private void fixAfterInsertion(Entry<K,V> x) { ... }
  • 1

2.5 刪除操作
private void deleteEntry(Entry<K,V> p) { ... }
  • 1

2.6 刪除修正操作

紅黑樹執行刪除之後,要執行“刪除修正操作”。 
目的是保證:紅黑樹刪除節點之後,仍然是一顆紅黑樹

private void fixAfterDeletion(Entry<K,V> x) { ... }
  • 1

關於紅黑樹部分,這裏主要是指出了TreeMap中那些是紅黑樹的主要相關內容。具體的紅黑樹相關操作API,這裏沒有詳細說明,因爲它們僅僅只是將算法翻譯成代碼。讀者可以參考“紅黑樹(一) 原理和算法詳細介紹”進行了解。

第3.2部分 TreeMap的構造函數

1 默認構造函數

使用默認構造函數構造TreeMap時,使用java的默認的比較器比較Key的大小,從而對TreeMap進行排序。

public TreeMap() {
    comparator = null;
}
  • 1
  • 2
  • 3

2 帶比較器的構造函數
public TreeMap(Comparator<? super K> comparator) {
    this.comparator = comparator;
}
  • 1
  • 2
  • 3

3 帶Map的構造函數,Map會成爲TreeMap的子集
public TreeMap(Map<? extends K, ? extends V> m) {
    comparator = null;
    putAll(m);
}
  • 1
  • 2
  • 3
  • 4

該構造函數會調用putAll()將m中的所有元素添加到TreeMap中。putAll()源碼如下:

public void putAll(Map<? extends K, ? extends V> m) {
    for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
        put(e.getKey(), e.getValue());
}
  • 1
  • 2
  • 3
  • 4

從中,我們可以看出putAll()就是將m中的key-value逐個的添加到TreeMap中。

4 帶SortedMap的構造函數,SortedMap會成爲TreeMap的子集
public TreeMap(SortedMap<K, ? extends V> m) {
    comparator = m.comparator();
    try {
        buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
    } catch (java.io.IOException cannotHappen) {
    } catch (ClassNotFoundException cannotHappen) {
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

該構造函數不同於上一個構造函數,在上一個構造函數中傳入的參數是Map,Map不是有序的,所以要逐個添加。 
而該構造函數的參數是SortedMap是一個有序的Map,我們通過buildFromSorted()來創建對應的Map。 
buildFromSorted涉及到的代碼如下:

 1 // 根據已經一個排好序的map創建一個TreeMap
 2     // 將map中的元素逐個添加到TreeMap中,並返回map的中間元素作爲根節點。
 3     private final Entry<K,V> buildFromSorted(int level, int lo, int hi,
 4                          int redLevel,
 5                          Iterator it,
 6                          java.io.ObjectInputStream str,
 7                          V defaultVal)
 8         throws  java.io.IOException, ClassNotFoundException {
 9 
10         if (hi < lo) return null;
11 
12       
13         // 獲取中間元素
14         int mid = (lo + hi) / 2;
15 
16         Entry<K,V> left  = null;
17         // 若lo小於mid,則遞歸調用獲取(middel的)左孩子。
18         if (lo < mid)
19             left = buildFromSorted(level+1, lo, mid - 1, redLevel,
20                    it, str, defaultVal);
21 
22         // 獲取middle節點對應的key和value
23         K key;
24         V value;
25         if (it != null) {
26             if (defaultVal==null) {
27                 Map.Entry<K,V> entry = (Map.Entry<K,V>)it.next();
28                 key = entry.getKey();
29                 value = entry.getValue();
30             } else {
31                 key = (K)it.next();
32                 value = defaultVal;
33             }
34         } else { // use stream
35             key = (K) str.readObject();
36             value = (defaultVal != null ? defaultVal : (V) str.readObject());
37         }
38 
39         // 創建middle節點
40         Entry<K,V> middle =  new Entry<K,V>(key, value, null);
41 
42         // 若當前節點的深度=紅色節點的深度,則將節點着色爲紅色。
43         if (level == redLevel)
44             middle.color = RED;
45 
46         // 設置middle爲left的父親,left爲middle的左孩子
47         if (left != null) {
48             middle.left = left;
49             left.parent = middle;
50         }
51 
52         if (mid < hi) {
53             // 遞歸調用獲取(middel的)右孩子。
54             Entry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel,
55                            it, str, defaultVal);
56             // 設置middle爲left的父親,left爲middle的左孩子
57             middle.right = right;
58             right.parent = middle;
59         }
60 
61         return middle;
62     }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62

要理解buildFromSorted,重點說明以下幾點:

第一,buildFromSorted是通過遞歸將SortedMap中的元素逐個關聯。 
第二,buildFromSorted返回middle節點(中間節點)作爲root。 
第三,buildFromSorted添加到紅黑樹中時,只將level == redLevel的節點設爲紅色。第level級節點,實際上是buildFromSorted轉換成紅黑樹後的最底端(假設根節點在最上方)的節點;只將紅黑樹最底端的階段着色爲紅色,其餘都是黑色。

第3.3部分 TreeMap的Entry相關函數

TreeMap的 firstEntry()、 lastEntry()、 lowerEntry()、 higherEntry()、 floorEntry()、 ceilingEntry()、 pollFirstEntry() 、 pollLastEntry() 原理都是類似的;下面以firstEntry()來進行詳細說明

我們先看看firstEntry()和getFirstEntry()的代碼:

public Map.Entry<K,V> firstEntry() {
    return exportEntry(getFirstEntry());
}

final Entry<K,V> getFirstEntry() {
    Entry<K,V> p = root;
    if (p != null)
        while (p.left != null)
            p = p.left;
    return p;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

從中,我們可以看出 firstEntry() 和 getFirstEntry() 都是用於獲取第一個節點。 
但是,firstEntry() 是對外接口; getFirstEntry() 是內部接口。而且,firstEntry() 是通過 getFirstEntry() 來實現的。那爲什麼外界不能直接調用 getFirstEntry(),而需要多此一舉的調用 firstEntry() 呢? 
先告訴大家原因,再進行詳細說明。這麼做的目的是:防止用戶修改返回的Entry。getFirstEntry()返回的Entry是可以被修改的,但是經過firstEntry()返回的Entry不能被修改,只可以讀取Entry的key值和value值。下面我們看看到底是如何實現的。 
(01) getFirstEntry()返回的是Entry節點,而Entry是紅黑樹的節點,它的源碼如下:

// 返回“紅黑樹的第一個節點”
final Entry<K,V> getFirstEntry() {
    Entry<K,V> p = root;
    if (p != null)
    while (p.left != null)
            p = p.left;
    return p;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

從中,我們可以調用Entry的getKey()、getValue()來獲取key和value值,以及調用setValue()來修改value的值。

(02) firstEntry()返回的是exportEntry(getFirstEntry())。下面我們看看exportEntry()幹了些什麼?

static

 1 public static class SimpleImmutableEntry<K,V>
 2 implements Entry<K,V>, java.io.Serializable
 3 {
 4     private static final long serialVersionUID = 7138329143949025153L;
 5 
 6     private final K key;
 7     private final V value;
 8 
 9     public SimpleImmutableEntry(K key, V value) {
10         this.key   = key;
11         this.value = value;
12     }
13 
14     public SimpleImmutableEntry(Entry<? extends K, ? extends V> entry) {
15         this.key   = entry.getKey();
16             this.value = entry.getValue();
17     }
18 
19     public K getKey() {
20         return key;
21     }
22 
23     public V getValue() {
24         return value;
25     }
26 
27     public V setValue(V value) {
28             throw new UnsupportedOperationException();
29         }
30 
31     public boolean equals(Object o) {
32         if (!(o instanceof Map.Entry))
33         return false;
34         Map.Entry e = (Map.Entry)o;
35         return eq(key, e.getKey()) && eq(value, e.getValue());
36     }
37 
38     public int hashCode() {
39         return (key   == null ? 0 :   key.hashCode()) ^
40            (value == null ? 0 : value.hashCode());
41     }
42 
43     public String toString() {
44         return key + "=" + value;
45     }
46 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

從中,我們可以看出SimpleImmutableEntry實際上是簡化的key-value節點。 
它只提供了getKey()、getValue()方法類獲取節點的值;但不能修改value的值,因爲調用 setValue() 會拋出異常UnsupportedOperationException();

再回到我們之前的問題:那爲什麼外界不能直接調用 getFirstEntry(),而需要多此一舉的調用 firstEntry() 呢? 
現在我們清晰的瞭解到: 
(01) firstEntry()是對外接口,而getFirstEntry()是內部接口。 
(02) 對firstEntry()返回的Entry對象只能進行getKey()、getValue()等讀取操作;而對getFirstEntry()返回的對象除了可以進行讀取操作之後,還可以通過setValue()修改值。

第3.4部分 TreeMap的key相關函數

TreeMap的firstKey()、lastKey()、lowerKey()、higherKey()、floorKey()、ceilingKey()原理都是類似的;下面以ceilingKey()來進行詳細說明

ceilingKey(K key)的作用是“返回大於/等於key的最小的鍵值對所對應的KEY,沒有的話返回null”,它的代碼如下:

public K ceilingKey(K key) {
    return keyOrNull(getCeilingEntry(key));
}
  • 1
  • 2
  • 3

ceilingKey()是通過getCeilingEntry()實現的。keyOrNull()的代碼很簡單,它是獲取節點的key,沒有的話,返回null。

static <K,V> K keyOrNull(TreeMap.Entry<K,V> e) {
    return e == null? null : e.key;
}
  • 1
  • 2
  • 3

getCeilingEntry(K key)的作用是“獲取TreeMap中大於/等於key的最小的節點,若不存在(即TreeMap中所有節點的鍵都比key大),就返回null”。它的實現代碼如下:

 1 final Entry<K,V> getCeilingEntry(K key) {
 2     Entry<K,V> p = root;
 3     while (p != null) {
 4         int cmp = compare(key, p.key);
 5         // 情況一:若“p的key” > key。
 6         // 若 p 存在左孩子,則設 p=“p的左孩子”;
 7         // 否則,返回p
 8         if (cmp < 0) {
 9             if (p.left != null)
10                 p = p.left;
11             else
12                 return p;
13         // 情況二:若“p的key” < key。
14         } else if (cmp > 0) {
15             // 若 p 存在右孩子,則設 p=“p的右孩子”
16             if (p.right != null) {
17                 p = p.right;
18             } else {
19                 // 若 p 不存在右孩子,則找出 p 的後繼節點,並返回
20                 // 注意:這裏返回的 “p的後繼節點”有2種可能性:第一,null;第二,TreeMap中大於key的最小的節點。
21                 //   理解這一點的核心是,getCeilingEntry是從root開始遍歷的。
22                 //   若getCeilingEntry能走到這一步,那麼,它之前“已經遍歷過的節點的key”都 > key。
23                 //   能理解上面所說的,那麼就很容易明白,爲什麼“p的後繼節點”有2種可能性了。
24                 Entry<K,V> parent = p.parent;
25                 Entry<K,V> ch = p;
26                 while (parent != null && ch == parent.right) {
27                     ch = parent;
28                     parent = parent.parent;
29                 }
30                 return parent;
31             }
32         // 情況三:若“p的key” = key。
33         } else
34             return p;
35     }
36     return null;
37 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

第3.5部分 TreeMap的values()函數

values() 返回“TreeMap中值的集合”

values()的實現代碼如下:

public Collection<V> values() {
    Collection<V> vs = values;
    return (vs != null) ? vs : (values = new Values());
}
  • 1
  • 2
  • 3
  • 4

說明:從中,我們可以發現values()是通過 new Values() 來實現 “返回TreeMap中值的集合”。

那麼Values()是如何實現的呢? 沒錯!由於返回的是值的集合,那麼Values()肯定返回一個集合;而Values()正好是集合類Value的構造函數。Values繼承於AbstractCollection,它的代碼如下:

 1 // ”TreeMap的值的集合“對應的類,它集成於AbstractCollection
 2 class Values extends AbstractCollection<V> {
 3     // 返回迭代器
 4     public Iterator<V> iterator() {
 5         return new ValueIterator(getFirstEntry());
 6     }
 7 
 8     // 返回個數
 9     public int size() {
10         return TreeMap.this.size();
11     }
12 
13     // "TreeMap的值的集合"中是否包含"對象o"
14     public boolean contains(Object o) {
15         return TreeMap.this.containsValue(o);
16     }
17 
18     // 刪除"TreeMap的值的集合"中的"對象o"
19     public boolean remove(Object o) {
20         for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e)) {
21             if (valEquals(e.getValue(), o)) {
22                 deleteEntry(e);
23                 return true;
24             }
25         }
26         return false;
27     }
28 
29     // 清空刪除"TreeMap的值的集合"
30     public void clear() {
31         TreeMap.this.clear();
32     }
33 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

說明:從中,我們可以知道Values類就是一個集合。而 AbstractCollection 實現了除 size() 和 iterator() 之外的其它函數,因此只需要在Values類中實現這兩個函數即可。 
size() 的實現非常簡單,Values集合中元素的個數=該TreeMap的元素個數。(TreeMap每一個元素都有一個值嘛!)

iterator() 則返回一個迭代器,用於遍歷Values。下面,我們一起可以看看iterator()的實現:

public Iterator<V> iterator() {
    return new ValueIterator(getFirstEntry());
}
  • 1
  • 2
  • 3

說明: iterator() 是通過ValueIterator() 返回迭代器的,ValueIterator是一個類。代碼如下:

final class ValueIterator extends PrivateEntryIterator<V> {
    ValueIterator(Entry<K,V> first) {
        super(first);
    }
    public V next() {
        return nextEntry().value;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

說明:ValueIterator的代碼很簡單,它的主要實現應該在它的父類PrivateEntryIterator中。下面我們一起看看PrivateEntryIterator的代碼:

 1 abstract class PrivateEntryIterator<T> implements Iterator<T> {
 2     // 下一節點
 3     Entry<K,V> next;
 4     // 上一次返回的節點
 5     Entry<K,V> lastReturned;
 6     // 修改次數統計數
 7     int expectedModCount;
 8 
 9     PrivateEntryIterator(Entry<K,V> first) {
10         expectedModCount = modCount;
11         lastReturned = null;
12         next = first;
13     }
14 
15     // 是否存在下一個節點
16     public final boolean hasNext() {
17         return next != null;
18     }
19 
20     // 返回下一個節點
21     final Entry<K,V> nextEntry() {
22         Entry<K,V> e = next;
23         if (e == null)
24             throw new NoSuchElementException();
25         if (modCount != expectedModCount)
26             throw new ConcurrentModificationException();
27         next = successor(e);
28         lastReturned = e;
29         return e;
30     }
31 
32     // 返回上一節點
33     final Entry<K,V> prevEntry() {
34         Entry<K,V> e = next;
35         if (e == null)
36             throw new NoSuchElementException();
37         if (modCount != expectedModCount)
38             throw new ConcurrentModificationException();
39         next = predecessor(e);
40         lastReturned = e;
41         return e;
42     }
43 
44     // 刪除當前節點
45     public void remove() {
46         if (lastReturned == null)
47             throw new IllegalStateException();
48         if (modCount != expectedModCount)
49             throw new ConcurrentModificationException();
50         // deleted entries are replaced by their successors
51         if (lastReturned.left != null && lastReturned.right != null)
52             next = lastReturned;
53         deleteEntry(lastReturned);
54         expectedModCount = modCount;
55         lastReturned = null;
56     }
57 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57

說明:PrivateEntryIterator是一個抽象類,它的實現很簡單,只只實現了Iterator的remove()和hasNext()接口,沒有實現next()接口。 
而我們在ValueIterator中已經實現的next()接口。 
至此,我們就瞭解了iterator()的完整實現了。

第3.6部分 TreeMap的entrySet()函數

entrySet() 返回“鍵值對集合”。顧名思義,它返回的是一個集合,集合的元素是“鍵值對”。

下面,我們看看它是如何實現的?entrySet() 的實現代碼如下:

public Set<Map.Entry<K,V>> entrySet() {
    EntrySet es = entrySet;
    return (es != null) ? es : (entrySet = new EntrySet());
}
  • 1
  • 2
  • 3
  • 4

說明:entrySet()返回的是一個EntrySet對象。

下面我們看看EntrySet的代碼:

 1 // EntrySet是“TreeMap的所有鍵值對組成的集合”,
 2 // EntrySet集合的單位是單個“鍵值對”。
 3 class EntrySet extends AbstractSet<Map.Entry<K,V>> {
 4     public Iterator<Map.Entry<K,V>> iterator() {
 5         return new EntryIterator(getFirstEntry());
 6     }
 7 
 8     // EntrySet中是否包含“鍵值對Object”
 9     public boolean contains(Object o) {
10         if (!(o instanceof Map.Entry))
11             return false;
12         Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
13         V value = entry.getValue();
14         Entry<K,V> p = getEntry(entry.getKey());
15         return p != null && valEquals(p.getValue(), value);
16     }
17 
18     // 刪除EntrySet中的“鍵值對Object”
19     public boolean remove(Object o) {
20         if (!(o instanceof Map.Entry))
21             return false;
22         Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
23         V value = entry.getValue();
24         Entry<K,V> p = getEntry(entry.getKey());
25         if (p != null && valEquals(p.getValue(), value)) {
26             deleteEntry(p);
27             return true;
28         }
29         return false;
30     }
31 
32     // 返回EntrySet中元素個數
33     public int size() {
34         return TreeMap.this.size();
35     }
36 
37     // 清空EntrySet
38     public void clear() {
39         TreeMap.this.clear();
40     }
41 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

說明: 
EntrySet是“TreeMap的所有鍵值對組成的集合”,而且它單位是單個“鍵值對”。 
EntrySet是一個集合,它繼承於AbstractSet。而AbstractSet實現了除size() 和 iterator() 之外的其它函數,因此,我們重點了解一下EntrySet的size() 和 iterator() 函數

size() 的實現非常簡單,AbstractSet集合中元素的個數=該TreeMap的元素個數。 
iterator() 則返回一個迭代器,用於遍歷AbstractSet。從上面的源碼中,我們可以發現iterator() 是通過EntryIterator實現的;下面我們看看EntryIterator的源碼:

final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
    EntryIterator(Entry<K,V> first) {
        super(first);
    }
    public Map.Entry<K,V> next() {
        return nextEntry();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

說明:和Values類一樣,EntryIterator也繼承於PrivateEntryIterator類。

第3.7部分 TreeMap實現的Cloneable接口

TreeMap實現了Cloneable接口,即實現了clone()方法。 
clone()方法的作用很簡單,就是克隆一個TreeMap對象並返回。

 1 // 克隆一個TreeMap,並返回Object對象
 2 public Object clone() {
 3     TreeMap<K,V> clone = null;
 4     try {
 5         clone = (TreeMap<K,V>) super.clone();
 6     } catch (CloneNotSupportedException e) {
 7         throw new InternalError();
 8     }
 9 
10     // Put clone into "virgin" state (except for comparator)
11     clone.root = null;
12     clone.size = 0;
13     clone.modCount = 0;
14     clone.entrySet = null;
15     clone.navigableKeySet = null;
16     clone.descendingMap = null;
17 
18     // Initialize clone with our mappings
19     try {
20         clone.buildFromSorted(size, entrySet().iterator(), null, null);
21     } catch (java.io.IOException cannotHappen) {
22     } catch (ClassNotFoundException cannotHappen) {
23     }
24 
25     return clone;
26 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

第3.8部分 TreeMap實現的Serializable接口

TreeMap實現java.io.Serializable,分別實現了串行讀取、寫入功能。 
串行寫入函數是writeObject(),它的作用是將TreeMap的“容量,所有的Entry”都寫入到輸出流中。 
而串行讀取函數是readObject(),它的作用是將TreeMap的“容量、所有的Entry”依次讀出。 
readObject() 和 writeObject() 正好是一對,通過它們,我能實現TreeMap的串行傳輸。

 1 // java.io.Serializable的寫入函數
 2 // 將TreeMap的“容量,所有的Entry”都寫入到輸出流中
 3 private void writeObject(java.io.ObjectOutputStream s)
 4     throws java.io.IOException {
 5     // Write out the Comparator and any hidden stuff
 6     s.defaultWriteObject();
 7 
 8     // Write out size (number of Mappings)
 9     s.writeInt(size);
10 
11     // Write out keys and values (alternating)
12     for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) {
13         Map.Entry<K,V> e = i.next();
14         s.writeObject(e.getKey());
15         s.writeObject(e.getValue());
16     }
17 }
18 
19 
20 // java.io.Serializable的讀取函數:根據寫入方式讀出
21 // 先將TreeMap的“容量、所有的Entry”依次讀出
22 private void readObject(final java.io.ObjectInputStream s)
23     throws java.io.IOException, ClassNotFoundException {
24     // Read in the Comparator and any hidden stuff
25     s.defaultReadObject();
26 
27     // Read in size
28     int size = s.readInt();
29 
30     buildFromSorted(size, null, s, null);
31 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

說到這裏,就順便說一下“關鍵字transient”的作用

transient是Java語言的關鍵字,它被用來表示一個域不是該對象串行化的一部分。 
Java的serialization提供了一種持久化對象實例的機制。當持久化對象時,可能有一個特殊的對象數據成員,我們不想用serialization機制來保存它。爲了在一個特定對象的一個域上關閉serialization,可以在這個域前加上關鍵字transient。 
當一個對象被串行化的時候,transient型變量的值不包括在串行化的表示中,然而非transient型的變量是被包括進去的。

第3.9部分 TreeMap實現的NavigableMap接口

firstKey()、lastKey()、lowerKey()、higherKey()、ceilingKey()、floorKey(); 
firstEntry()、 lastEntry()、 lowerEntry()、 higherEntry()、 floorEntry()、 ceilingEntry()、 pollFirstEntry() 、 pollLastEntry(); 
上面已經講解過這些API了,下面對其它的API進行說明。

1 反向TreeMap

descendingMap() 的作用是返回當前TreeMap的反向的TreeMap。所謂反向,就是排序順序和原始的順序相反。

我們已經知道TreeMap是一顆紅黑樹,而紅黑樹是有序的。 
TreeMap的排序方式是通過比較器,在創建TreeMap的時候,若指定了比較器,則使用該比較器;否則,就使用Java的默認比較器。 
而獲取TreeMap的反向TreeMap的原理就是將比較器反向即可!

理解了descendingMap()的反向原理之後,再講解一下descendingMap()的代碼。

// 獲取TreeMap的降序Map
public NavigableMap<K, V> descendingMap() {
    NavigableMap<K, V> km = descendingMap;
    return (km != null) ? km :
        (descendingMap = new DescendingSubMap(this,
                                              true, null, true,
                                              true, null, true));
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

從中,我們看出descendingMap()實際上是返回DescendingSubMap類的對象。下面,看看DescendingSubMap的源碼:

 1 static final class DescendingSubMap<K,V>  extends NavigableSubMap<K,V> {
 2     private static final long serialVersionUID = 912986545866120460L;
 3     DescendingSubMap(TreeMap<K,V> m,
 4                     boolean fromStart, K lo, boolean loInclusive,
 5                     boolean toEnd,     K hi, boolean hiInclusive) {
 6         super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
 7     }
 8 
 9     // 反轉的比較器:是將原始比較器反轉得到的。
10     private final Comparator<? super K> reverseComparator =
11         Collections.reverseOrder(m.comparator);
12 
13     // 獲取反轉比較器
14     public Comparator<? super K> comparator() {
15         return reverseComparator;
16     }
17 
18     // 獲取“子Map”。
19     // 範圍是從fromKey 到 toKey;fromInclusive是是否包含fromKey的標記,toInclusive是是否包含toKey的標記
20     public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
21                                     K toKey,   boolean toInclusive) {
22         if (!inRange(fromKey, fromInclusive))
23             throw new IllegalArgumentException("fromKey out of range");
24         if (!inRange(toKey, toInclusive))
25             throw new IllegalArgumentException("toKey out of range");
26         return new DescendingSubMap(m,
27                                     false, toKey,   toInclusive,
28                                     false, fromKey, fromInclusive);
29     }
30 
31     // 獲取“Map的頭部”。
32     // 範圍從第一個節點 到 toKey, inclusive是是否包含toKey的標記
33     public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
34         if (!inRange(toKey, inclusive))
35             throw new IllegalArgumentException("toKey out of range");
36         return new DescendingSubMap(m,
37                                     false, toKey, inclusive,
38                                     toEnd, hi,    hiInclusive);
39     }
40 
41     // 獲取“Map的尾部”。
42     // 範圍是從 fromKey 到 最後一個節點,inclusive是是否包含fromKey的標記
43     public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
44         if (!inRange(fromKey, inclusive))
45             throw new IllegalArgumentException("fromKey out of range");
46         return new DescendingSubMap(m,
47                                     fromStart, lo, loInclusive,
48                                     false, fromKey, inclusive);
49     }
50 
51     // 獲取對應的降序Map
52     public NavigableMap<K,V> descendingMap() {
53         NavigableMap<K,V> mv = descendingMapView;
54         return (mv != null) ? mv :
55             (descendingMapView =
56              new AscendingSubMap(m,
57                                  fromStart, lo, loInclusive,
58                                  toEnd,     hi, hiInclusive));
59     }
60 
61     // 返回“升序Key迭代器”
62     Iterator<K> keyIterator() {
63         return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
64     }
65 
66     // 返回“降序Key迭代器”
67     Iterator<K> descendingKeyIterator() {
68         return new SubMapKeyIterator(absLowest(), absHighFence());
69     }
70 
71     // “降序EntrySet集合”類
72     // 實現了iterator()
73     final class DescendingEntrySetView extends EntrySetView {
74         public Iterator<Map.Entry<K,V>> iterator() {
75             return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
76         }
77     }
78 
79     // 返回“降序EntrySet集合”
80     public Set<Map.Entry<K,V>> entrySet() {
81         EntrySetView es = entrySetView;
82         return (es != null) ? es : new DescendingEntrySetView();
83     }
84 
85     TreeMap.Entry<K,V> subLowest()       { return absHighest(); }
86     TreeMap.Entry<K,V> subHighest()      { return absLowest(); }
87     TreeMap.Entry<K,V> subCeiling(K key) { return absFloor(key); }
88     TreeMap.Entry<K,V> subHigher(K key)  { return absLower(key); }
89     TreeMap.Entry<K,V> subFloor(K key)   { return absCeiling(key); }
90     TreeMap.Entry<K,V> subLower(K key)   { return absHigher(key); }
91 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91

從中,我們看出DescendingSubMap是降序的SubMap,它的實現機制是將“SubMap的比較器反轉”。

它繼承於NavigableSubMap。而NavigableSubMap是一個繼承於AbstractMap的抽象類;它包括2個子類——”(升序)AscendingSubMap”和”(降序)DescendingSubMap”。NavigableSubMap爲它的兩個子類實現了許多公共API。 
下面看看NavigableSubMap的源碼。

  1 static abstract class NavigableSubMap<K,V> extends AbstractMap<K,V>
  2     implements NavigableMap<K,V>, java.io.Serializable {
  3     // TreeMap的拷貝
  4     final TreeMap<K,V> m;
  5     // lo是“子Map範圍的最小值”,hi是“子Map範圍的最大值”;
  6     // loInclusive是“是否包含lo的標記”,hiInclusive是“是否包含hi的標記”
  7     // fromStart是“表示是否從第一個節點開始計算”,
  8     // toEnd是“表示是否計算到最後一個節點      ”
  9     final K lo, hi;      
 10     final boolean fromStart, toEnd;
 11     final boolean loInclusive, hiInclusive;
 12 
 13     // 構造函數
 14     NavigableSubMap(TreeMap<K,V> m,
 15                     boolean fromStart, K lo, boolean loInclusive,
 16                     boolean toEnd,     K hi, boolean hiInclusive) {
 17         if (!fromStart && !toEnd) {
 18             if (m.compare(lo, hi) > 0)
 19                 throw new IllegalArgumentException("fromKey > toKey");
 20         } else {
 21             if (!fromStart) // type check
 22                 m.compare(lo, lo);
 23             if (!toEnd)
 24                 m.compare(hi, hi);
 25         }
 26 
 27         this.m = m;
 28         this.fromStart = fromStart;
 29         this.lo = lo;
 30         this.loInclusive = loInclusive;
 31         this.toEnd = toEnd;
 32         this.hi = hi;
 33         this.hiInclusive = hiInclusive;
 34     }
 35 
 36     // 判斷key是否太小
 37     final boolean tooLow(Object key) {
 38         // 若該SubMap不包括“起始節點”,
 39         // 並且,“key小於最小鍵(lo)”或者“key等於最小鍵(lo),但最小鍵卻沒包括在該SubMap內”
 40         // 則判斷key太小。其餘情況都不是太小!
 41         if (!fromStart) {
 42             int c = m.compare(key, lo);
 43             if (c < 0 || (c == 0 && !loInclusive))
 44                 return true;
 45         }
 46         return false;
 47     }
 48 
 49     // 判斷key是否太大
 50     final boolean tooHigh(Object key) {
 51         // 若該SubMap不包括“結束節點”,
 52         // 並且,“key大於最大鍵(hi)”或者“key等於最大鍵(hi),但最大鍵卻沒包括在該SubMap內”
 53         // 則判斷key太大。其餘情況都不是太大!
 54         if (!toEnd) {
 55             int c = m.compare(key, hi);
 56             if (c > 0 || (c == 0 && !hiInclusive))
 57                 return true;
 58         }
 59         return false;
 60     }
 61 
 62     // 判斷key是否在“lo和hi”開區間範圍內
 63     final boolean inRange(Object key) {
 64         return !tooLow(key) && !tooHigh(key);
 65     }
 66 
 67     // 判斷key是否在封閉區間內
 68     final boolean inClosedRange(Object key) {
 69         return (fromStart || m.compare(key, lo) >= 0)
 70             && (toEnd || m.compare(hi, key) >= 0);
 71     }
 72 
 73     // 判斷key是否在區間內, inclusive是區間開關標誌
 74     final boolean inRange(Object key, boolean inclusive) {
 75         return inclusive ? inRange(key) : inClosedRange(key);
 76     }
 77 
 78     // 返回最低的Entry
 79     final TreeMap.Entry<K,V> absLowest() {
 80     // 若“包含起始節點”,則調用getFirstEntry()返回第一個節點
 81     // 否則的話,若包括lo,則調用getCeilingEntry(lo)獲取大於/等於lo的最小的Entry;
 82     //           否則,調用getHigherEntry(lo)獲取大於lo的最小Entry
 83     TreeMap.Entry<K,V> e =
 84             (fromStart ?  m.getFirstEntry() :
 85              (loInclusive ? m.getCeilingEntry(lo) :
 86                             m.getHigherEntry(lo)));
 87         return (e == null || tooHigh(e.key)) ? null : e;
 88     }
 89 
 90     // 返回最高的Entry
 91     final TreeMap.Entry<K,V> absHighest() {
 92     // 若“包含結束節點”,則調用getLastEntry()返回最後一個節點
 93     // 否則的話,若包括hi,則調用getFloorEntry(hi)獲取小於/等於hi的最大的Entry;
 94     //           否則,調用getLowerEntry(hi)獲取大於hi的最大Entry
 95     TreeMap.Entry<K,V> e =
 96     TreeMap.Entry<K,V> e =
 97             (toEnd ?  m.getLastEntry() :
 98              (hiInclusive ?  m.getFloorEntry(hi) :
 99                              m.getLowerEntry(hi)));
100         return (e == null || tooLow(e.key)) ? null : e;
101     }
102 
103     // 返回"大於/等於key的最小的Entry"
104     final TreeMap.Entry<K,V> absCeiling(K key) {
105         // 只有在“key太小”的情況下,absLowest()返回的Entry纔是“大於/等於key的最小Entry”
106         // 其它情況下不行。例如,當包含“起始節點”時,absLowest()返回的是最小Entry了!
107         if (tooLow(key))
108             return absLowest();
109         // 獲取“大於/等於key的最小Entry”
110     TreeMap.Entry<K,V> e = m.getCeilingEntry(key);
111         return (e == null || tooHigh(e.key)) ? null : e;
112     }
113 
114     // 返回"大於key的最小的Entry"
115     final TreeMap.Entry<K,V> absHigher(K key) {
116         // 只有在“key太小”的情況下,absLowest()返回的Entry纔是“大於key的最小Entry”
117         // 其它情況下不行。例如,當包含“起始節點”時,absLowest()返回的是最小Entry了,而不一定是“大於key的最小Entry”!
118         if (tooLow(key))
119             return absLowest();
120         // 獲取“大於key的最小Entry”
121     TreeMap.Entry<K,V> e = m.getHigherEntry(key);
122         return (e == null || tooHigh(e.key)) ? null : e;
123     }
124 
125     // 返回"小於/等於key的最大的Entry"
126     final TreeMap.Entry<K,V> absFloor(K key) {
127         // 只有在“key太大”的情況下,(absHighest)返回的Entry纔是“小於/等於key的最大Entry”
128         // 其它情況下不行。例如,當包含“結束節點”時,absHighest()返回的是最大Entry了!
129         if (tooHigh(key))
130             return absHighest();
131     // 獲取"小於/等於key的最大的Entry"
132     TreeMap.Entry<K,V> e = m.getFloorEntry(key);
133         return (e == null || tooLow(e.key)) ? null : e;
134     }
135 
136     // 返回"小於key的最大的Entry"
137     final TreeMap.Entry<K,V> absLower(K key) {
138         // 只有在“key太大”的情況下,(absHighest)返回的Entry纔是“小於key的最大Entry”
139         // 其它情況下不行。例如,當包含“結束節點”時,absHighest()返回的是最大Entry了,而不一定是“小於key的最大Entry”!
140         if (tooHigh(key))
141             return absHighest();
142     // 獲取"小於key的最大的Entry"
143     TreeMap.Entry<K,V> e = m.getLowerEntry(key);
144         return (e == null || tooLow(e.key)) ? null : e;
145     }
146 
147     // 返回“大於最大節點中的最小節點”,不存在的話,返回null
148     final TreeMap.Entry<K,V> absHighFence() {
149         return (toEnd ? null : (hiInclusive ?
150                                 m.getHigherEntry(hi) :
151                                 m.getCeilingEntry(hi)));
152     }
153 
154     // 返回“小於最小節點中的最大節點”,不存在的話,返回null
155     final TreeMap.Entry<K,V> absLowFence() {
156         return (fromStart ? null : (loInclusive ?
157                                     m.getLowerEntry(lo) :
158                                     m.getFloorEntry(lo)));
159     }
160 
161     // 下面幾個abstract方法是需要NavigableSubMap的實現類實現的方法
162     abstract TreeMap.Entry<K,V> subLowest();
163     abstract TreeMap.Entry<K,V> subHighest();
164     abstract TreeMap.Entry<K,V> subCeiling(K key);
165     abstract TreeMap.Entry<K,V> subHigher(K key);
166     abstract TreeMap.Entry<K,V> subFloor(K key);
167     abstract TreeMap.Entry<K,V> subLower(K key);
168     // 返回“順序”的鍵迭代器
169     abstract Iterator<K> keyIterator();
170     // 返回“逆序”的鍵迭代器
171     abstract Iterator<K> descendingKeyIterator();
172 
173     // 返回SubMap是否爲空。空的話,返回true,否則返回false
174     public boolean isEmpty() {
175         return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty();
176     }
177 
178     // 返回SubMap的大小
179     public int size() {
180         return (fromStart && toEnd) ? m.size() : entrySet().size();
181     }
182 
183     // 返回SubMap是否包含鍵key
184     public final boolean containsKey(Object key) {
185         return inRange(key) && m.containsKey(key);
186     }
187 
188     // 將key-value 插入SubMap中
189     public final V put(K key, V value) {
190         if (!inRange(key))
191             throw new IllegalArgumentException("key out of range");
192         return m.put(key, value);
193     }
194 
195     // 獲取key對應值
196     public final V get(Object key) {
197         return !inRange(key)? null :  m.get(key);
198     }
199 
200     // 刪除key對應的鍵值對
201     public final V remove(Object key) {
202         return !inRange(key)? null  : m.remove(key);
203     }
204 
205     // 獲取“大於/等於key的最小鍵值對”
206     public final Map.Entry<K,V> ceilingEntry(K key) {
207         return exportEntry(subCeiling(key));
208     }
209 
210     // 獲取“大於/等於key的最小鍵”
211     public final K ceilingKey(K key) {
212         return keyOrNull(subCeiling(key));
213     }
214 
215     // 獲取“大於key的最小鍵值對”
216     public final Map.Entry<K,V> higherEntry(K key) {
217         return exportEntry(subHigher(key));
218     }
219 
220     // 獲取“大於key的最小鍵”
221     public final K higherKey(K key) {
222         return keyOrNull(subHigher(key));
223     }
224 
225     // 獲取“小於/等於key的最大鍵值對”
226     public final Map.Entry<K,V> floorEntry(K key) {
227         return exportEntry(subFloor(key));
228     }
229 
230     // 獲取“小於/等於key的最大鍵”
231     public final K floorKey(K key) {
232         return keyOrNull(subFloor(key));
233     }
234 
235     // 獲取“小於key的最大鍵值對”
236     public final Map.Entry<K,V> lowerEntry(K key) {
237         return exportEntry(subLower(key));
238     }
239 
240     // 獲取“小於key的最大鍵”
241     public final K lowerKey(K key) {
242         return keyOrNull(subLower(key));
243     }
244 
245     // 獲取"SubMap的第一個鍵"
246     public final K firstKey() {
247         return key(subLowest());
248     }
249 
250     // 獲取"SubMap的最後一個鍵"
251     public final K lastKey() {
252         return key(subHighest());
253     }
254 
255     // 獲取"SubMap的第一個鍵值對"
256     public final Map.Entry<K,V> firstEntry() {
257         return exportEntry(subLowest());
258     }
259 
260     // 獲取"SubMap的最後一個鍵值對"
261     public final Map.Entry<K,V> lastEntry() {
262         return exportEntry(subHighest());
263     }
264 
265     // 返回"SubMap的第一個鍵值對",並從SubMap中刪除改鍵值對
266     public final Map.Entry<K,V> pollFirstEntry() {
267     TreeMap.Entry<K,V> e = subLowest();
268         Map.Entry<K,V> result = exportEntry(e);
269         if (e != null)
270             m.deleteEntry(e);
271         return result;
272     }
273 
274     // 返回"SubMap的最後一個鍵值對",並從SubMap中刪除改鍵值對
275     public final Map.Entry<K,V> pollLastEntry() {
276     TreeMap.Entry<K,V> e = subHighest();
277         Map.Entry<K,V> result = exportEntry(e);
278         if (e != null)
279             m.deleteEntry(e);
280         return result;
281     }
282 
283     // Views
284     transient NavigableMap<K,V> descendingMapView = null;
285     transient EntrySetView entrySetView = null;
286     transient KeySet<K> navigableKeySetView = null;
287 
288     // 返回NavigableSet對象,實際上返回的是當前對象的"Key集合"。 
289     public final NavigableSet<K> navigableKeySet() {
290         KeySet<K> nksv = navigableKeySetView;
291         return (nksv != null) ? nksv :
292             (navigableKeySetView = new TreeMap.KeySet(this));
293     }
294 
295     // 返回"Key集合"對象
296     public final Set<K> keySet() {
297         return navigableKeySet();
298     }
299 
300     // 返回“逆序”的Key集合
301     public NavigableSet<K> descendingKeySet() {
302         return descendingMap().navigableKeySet();
303     }
304 
305     // 排列fromKey(包含) 到 toKey(不包含) 的子map
306     public final SortedMap<K,V> subMap(K fromKey, K toKey) {
307         return subMap(fromKey, true, toKey, false);
308     }
309 
310     // 返回當前Map的頭部(從第一個節點 到 toKey, 不包括toKey)
311     public final SortedMap<K,V> headMap(K toKey) {
312         return headMap(toKey, false);
313     }
314 
315     // 返回當前Map的尾部[從 fromKey(包括fromKeyKey) 到 最後一個節點]
316     public final SortedMap<K,V> tailMap(K fromKey) {
317         return tailMap(fromKey, true);
318     }
319 
320     // Map的Entry的集合
321     abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
322         private transient int size = -1, sizeModCount;
323 
324         // 獲取EntrySet的大小
325         public int size() {
326             // 若SubMap是從“開始節點”到“結尾節點”,則SubMap大小就是原TreeMap的大小
327             if (fromStart && toEnd)
328                 return m.size();
329             // 若SubMap不是從“開始節點”到“結尾節點”,則調用iterator()遍歷EntrySetView中的元素
330             if (size == -1 || sizeModCount != m.modCount) {
331                 sizeModCount = m.modCount;
332                 size = 0;
333                 Iterator i = iterator();
334                 while (i.hasNext()) {
335                     size++;
336                     i.next();
337                 }
338             }
339             return size;
340         }
341 
342         // 判斷EntrySetView是否爲空
343         public boolean isEmpty() {
344             TreeMap.Entry<K,V> n = absLowest();
345             return n == null || tooHigh(n.key);
346         }
347 
348         // 判斷EntrySetView是否包含Object
349         public boolean contains(Object o) {
350             if (!(o instanceof Map.Entry))
351                 return false;
352             Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
353             K key = entry.getKey();
354             if (!inRange(key))
355                 return false;
356             TreeMap.Entry node = m.getEntry(key);
357             return node != null &&
358                 valEquals(node.getValue(), entry.getValue());
359         }
360 
361         // 從EntrySetView中刪除Object
362         public boolean remove(Object o) {
363             if (!(o instanceof Map.Entry))
364                 return false;
365             Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
366             K key = entry.getKey();
367             if (!inRange(key))
368                 return false;
369             TreeMap.Entry<K,V> node = m.getEntry(key);
370             if (node!=null && valEquals(node.getValue(),entry.getValue())){
371                 m.deleteEntry(node);
372                 return true;
373             }
374             return false;
375         }
376     }
377 
378     // SubMap的迭代器
379     abstract class SubMapIterator<T> implements Iterator<T> {
380         // 上一次被返回的Entry
381         TreeMap.Entry<K,V> lastReturned;
382         // 指向下一個Entry
383         TreeMap.Entry<K,V> next;
384         // “柵欄key”。根據SubMap是“升序”還是“降序”具有不同的意義
385         final K fenceKey;
386         int expectedModCount;
387 
388         // 構造函數
389         SubMapIterator(TreeMap.Entry<K,V> first,
390                        TreeMap.Entry<K,V> fence) {
391             // 每創建一個SubMapIterator時,保存修改次數
392             // 若後面發現expectedModCount和modCount不相等,則拋出ConcurrentModificationException異常。
393             // 這就是所說的fast-fail機制的原理!
394             expectedModCount = m.modCount;
395             lastReturned = null;
396             next = first;
397             fenceKey = fence == null ? null : fence.key;
398         }
399 
400         // 是否存在下一個Entry
401         public final boolean hasNext() {
402             return next != null && next.key != fenceKey;
403         }
404 
405         // 返回下一個Entry
406         final TreeMap.Entry<K,V> nextEntry() {
407             TreeMap.Entry<K,V> e = next;
408             if (e == null || e.key == fenceKey)
409                 throw new NoSuchElementException();
410             if (m.modCount != expectedModCount)
411                 throw new ConcurrentModificationException();
412             // next指向e的後繼節點
413             next = successor(e);
414     lastReturned = e;
415             return e;
416         }
417 
418         // 返回上一個Entry
419         final TreeMap.Entry<K,V> prevEntry() {
420             TreeMap.Entry<K,V> e = next;
421             if (e == null || e.key == fenceKey)
422                 throw new NoSuchElementException();
423             if (m.modCount != expectedModCount)
424                 throw new ConcurrentModificationException();
425             // next指向e的前繼節點
426             next = predecessor(e);
427     lastReturned = e;
428             return e;
429         }
430 
431         // 刪除當前節點(用於“升序的SubMap”)。
432         // 刪除之後,可以繼續升序遍歷;紅黑樹特性沒變。
433         final void removeAscending() {
434             if (lastReturned == null)
435                 throw new IllegalStateException();
436             if (m.modCount != expectedModCount)
437                 throw new ConcurrentModificationException();
438             // 這裏重點強調一下“爲什麼當lastReturned的左右孩子都不爲空時,要將其賦值給next”。
439             // 目的是爲了“刪除lastReturned節點之後,next節點指向的仍然是下一個節點”。
440             //     根據“紅黑樹”的特性可知:
441             //     當被刪除節點有兩個兒子時。那麼,首先把“它的後繼節點的內容”複製給“該節點的內容”;之後,刪除“它的後繼節點”。
442             //     這意味着“當被刪除節點有兩個兒子時,刪除當前節點之後,'新的當前節點'實際上是‘原有的後繼節點(即下一個節點)’”。
443             //     而此時next仍然指向"新的當前節點"。也就是說next是仍然是指向下一個節點;能繼續遍歷紅黑樹。
444             if (lastReturned.left != null && lastReturned.right != null)
445                 next = lastReturned;
446             m.deleteEntry(lastReturned);
447             lastReturned = null;
448             expectedModCount = m.modCount;
449         }
450 
451         // 刪除當前節點(用於“降序的SubMap”)。
452         // 刪除之後,可以繼續降序遍歷;紅黑樹特性沒變。
453         final void removeDescending() {
454             if (lastReturned == null)
455                 throw new IllegalStateException();
456             if (m.modCount != expectedModCount)
457                 throw new ConcurrentModificationException();
458             m.deleteEntry(lastReturned);
459             lastReturned = null;
460             expectedModCount = m.modCount;
461         }
462 
463     }
464 
465     // SubMap的Entry迭代器,它只支持升序操作,繼承於SubMapIterator
466     final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
467         SubMapEntryIterator(TreeMap.Entry<K,V> first,
468                             TreeMap.Entry<K,V> fence) {
469             super(first, fence);
470         }
471         // 獲取下一個節點(升序)
472         public Map.Entry<K,V> next() {
473             return nextEntry();
474         }
475         // 刪除當前節點(升序)
476         public void remove() {
477             removeAscending();
478         }
479     }
480 
481     // SubMap的Key迭代器,它只支持升序操作,繼承於SubMapIterator
482     final class SubMapKeyIterator extends SubMapIterator<K> {
483         SubMapKeyIterator(TreeMap.Entry<K,V> first,
484                           TreeMap.Entry<K,V> fence) {
485             super(first, fence);
486         }
487         // 獲取下一個節點(升序)
488         public K next() {
489             return nextEntry().key;
490         }
491         // 刪除當前節點(升序)
492         public void remove() {
493             removeAscending();
494         }
495     }
496 
497     // 降序SubMap的Entry迭代器,它只支持降序操作,繼承於SubMapIterator
498     final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
499         DescendingSubMapEntryIterator(TreeMap.Entry<K,V> last,
500                                       TreeMap.Entry<K,V> fence) {
501             super(last, fence);
502         }
503 
504         // 獲取下一個節點(降序)
505         public Map.Entry<K,V> next() {
506             return prevEntry();
507         }
508         // 刪除當前節點(降序)
509         public void remove() {
510             removeDescending();
511         }
512     }
513 
514     // 降序SubMap的Key迭代器,它只支持降序操作,繼承於SubMapIterator
515     final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
516         DescendingSubMapKeyIterator(TreeMap.Entry<K,V> last,
517                                     TreeMap.Entry<K,V> fence) {
518             super(last, fence);
519         }
520         // 獲取下一個節點(降序)
521         public K next() {
522             return prevEntry().key;
523         }
524         // 刪除當前節點(降序)
525         public void remove() {
526             removeDescending();
527         }
528     }
529 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358
  • 359
  • 360
  • 361
  • 362
  • 363
  • 364
  • 365
  • 366
  • 367
  • 368
  • 369
  • 370
  • 371
  • 372
  • 373
  • 374
  • 375
  • 376
  • 377
  • 378
  • 379
  • 380
  • 381
  • 382
  • 383
  • 384
  • 385
  • 386
  • 387
  • 388
  • 389
  • 390
  • 391
  • 392
  • 393
  • 394
  • 395
  • 396
  • 397
  • 398
  • 399
  • 400
  • 401
  • 402
  • 403
  • 404
  • 405
  • 406
  • 407
  • 408
  • 409
  • 410
  • 411
  • 412
  • 413
  • 414
  • 415
  • 416
  • 417
  • 418
  • 419
  • 420
  • 421
  • 422
  • 423
  • 424
  • 425
  • 426
  • 427
  • 428
  • 429
  • 430
  • 431
  • 432
  • 433
  • 434
  • 435
  • 436
  • 437
  • 438
  • 439
  • 440
  • 441
  • 442
  • 443
  • 444
  • 445
  • 446
  • 447
  • 448
  • 449
  • 450
  • 451
  • 452
  • 453
  • 454
  • 455
  • 456
  • 457
  • 458
  • 459
  • 460
  • 461
  • 462
  • 463
  • 464
  • 465
  • 466
  • 467
  • 468
  • 469
  • 470
  • 471
  • 472
  • 473
  • 474
  • 475
  • 476
  • 477
  • 478
  • 479
  • 480
  • 481
  • 482
  • 483
  • 484
  • 485
  • 486
  • 487
  • 488
  • 489
  • 490
  • 491
  • 492
  • 493
  • 494
  • 495
  • 496
  • 497
  • 498
  • 499
  • 500
  • 501
  • 502
  • 503
  • 504
  • 505
  • 506
  • 507
  • 508
  • 509
  • 510
  • 511
  • 512
  • 513
  • 514
  • 515
  • 516
  • 517
  • 518
  • 519
  • 520
  • 521
  • 522
  • 523
  • 524
  • 525
  • 526
  • 527
  • 528
  • 529

NavigableSubMap源碼很多,但不難理解;讀者可以通過源碼和註釋進行理解。

其實,讀完NavigableSubMap的源碼後,我們可以得出它的核心思想是:它是一個抽象集合類,爲2個子類——”(升序)AscendingSubMap”和”(降序)DescendingSubMap”而服務;因爲NavigableSubMap實現了許多公共API。它的最終目的是實現下面的一系列函數:

headMap(K toKey, boolean inclusive) 
headMap(K toKey)
subMap(K fromKey, K toKey)
subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)
tailMap(K fromKey)
tailMap(K fromKey, boolean inclusive)
navigableKeySet() 
descendingKeySet()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

第3.10部分 TreeMap其它函數

1 順序遍歷和逆序遍歷

TreeMap的順序遍歷和逆序遍歷原理非常簡單。 
由於TreeMap中的元素是從小到大的順序排列的。因此,順序遍歷,就是從第一個元素開始,逐個向後遍歷;而倒序遍歷則恰恰相反,它是從最後一個元素開始,逐個往前遍歷。

我們可以通過 keyIterator() 和 descendingKeyIterator()來說明! 
keyIterator()的作用是返回順序的KEY的集合, 
descendingKeyIterator()的作用是返回逆序的KEY的集合。

keyIterator() 的代碼如下:

Iterator<K> keyIterator() {
    return new KeyIterator(getFirstEntry());
}
  • 1
  • 2
  • 3

說明:從中我們可以看出keyIterator() 是返回以“第一個節點(getFirstEntry)” 爲其實元素的迭代器。 
KeyIterator的代碼如下:

final class KeyIterator extends PrivateEntryIterator<K> {
    KeyIterator(Entry<K,V> first) {
        super(first);
    }
    public K next() {
        return nextEntry().key;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

說明:KeyIterator繼承於PrivateEntryIterator。當我們通過next()不斷獲取下一個元素的時候,就是執行的順序遍歷了。

descendingKeyIterator()的代碼如下:

Iterator<K> descendingKeyIterator() {
    return new DescendingKeyIterator(getLastEntry());
}
  • 1
  • 2
  • 3

說明:從中我們可以看出descendingKeyIterator() 是返回以“最後一個節點(getLastEntry)” 爲其實元素的迭代器。 
再看看DescendingKeyIterator的代碼:

final class DescendingKeyIterator extends PrivateEntryIterator<K> {
    DescendingKeyIterator(Entry<K,V> first) {
        super(first);
    }
    public K next() {
        return prevEntry().key;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

說明:DescendingKeyIterator繼承於PrivateEntryIterator。當我們通過next()不斷獲取下一個元素的時候,實際上調用的是prevEntry()獲取的上一個節點,這樣它實際上執行的是逆序遍歷了。

至此,TreeMap的相關內容就全部介紹完畢了。若有錯誤或紕漏的地方,歡迎指正!

第4部分 TreeMap遍歷方式

4.1 遍歷TreeMap的鍵值對

第一步:根據entrySet()獲取TreeMap的“鍵值對”的Set集合。 
第二步:通過Iterator迭代器遍歷“第一步”得到的集合。

// 假設map是TreeMap對象
// map中的key是String類型,value是Integer類型
Integer integ = null;
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()) {
    Map.Entry entry = (Map.Entry)iter.next();
    // 獲取key
    key = (String)entry.getKey();
        // 獲取value
    integ = (Integer)entry.getValue();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

4.2 遍歷TreeMap的鍵

第一步:根據keySet()獲取TreeMap的“鍵”的Set集合。 
第二步:通過Iterator迭代器遍歷“第一步”得到的集合。

// 假設map是TreeMap對象
// map中的key是String類型,value是Integer類型
String key = null;
Integer integ = null;
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
        // 獲取key
    key = (String)iter.next();
        // 根據key,獲取value
    integ = (Integer)map.get(key);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

4.3 遍歷TreeMap的值

第一步:根據value()獲取TreeMap的“值”的集合。 
第二步:通過Iterator迭代器遍歷“第一步”得到的集合。

// 假設map是TreeMap對象
// map中的key是String類型,value是Integer類型
Integer value = null;
Collection c = map.values();
Iterator iter= c.iterator();
while (iter.hasNext()) {
    value = (Integer)iter.next();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

TreeMap遍歷測試程序如下:

  1 import java.util.Map;
  2 import java.util.Random;
  3 import java.util.Iterator;
  4 import java.util.TreeMap;
  5 import java.util.HashSet;
  6 import java.util.Map.Entry;
  7 import java.util.Collection;
  8 
  9 /*
 10  * @desc 遍歷TreeMap的測試程序。
 11  *   (01) 通過entrySet()去遍歷key、value,參考實現函數:
 12  *        iteratorTreeMapByEntryset()
 13  *   (02) 通過keySet()去遍歷key、value,參考實現函數:
 14  *        iteratorTreeMapByKeyset()
 15  *   (03) 通過values()去遍歷value,參考實現函數:
 16  *        iteratorTreeMapJustValues()
 17  *
 18  * @author skywang
 19  */
 20 public class TreeMapIteratorTest {
 21 
 22     public static void main(String[] args) {
 23         int val = 0;
 24         String key = null;
 25         Integer value = null;
 26         Random r = new Random();
 27         TreeMap map = new TreeMap();
 28 
 29         for (int i=0; i<12; i++) {
 30             // 隨機獲取一個[0,100)之間的數字
 31             val = r.nextInt(100);
 32             
 33             key = String.valueOf(val);
 34             value = r.nextInt(5);
 35             // 添加到TreeMap中
 36             map.put(key, value);
 37             System.out.println(" key:"+key+" value:"+value);
 38         }
 39         // 通過entrySet()遍歷TreeMap的key-value
 40         iteratorTreeMapByEntryset(map) ;
 41         
 42         // 通過keySet()遍歷TreeMap的key-value
 43         iteratorTreeMapByKeyset(map) ;
 44         
 45         // 單單遍歷TreeMap的value
 46         iteratorTreeMapJustValues(map);        
 47     }
 48     
 49     /*
 50      * 通過entry set遍歷TreeMap
 51      * 效率高!
 52      */
 53     private static void iteratorTreeMapByEntryset(TreeMap map) {
 54         if (map == null)
 55             return ;
 56 
 57         System.out.println("\niterator TreeMap By entryset");
 58         String key = null;
 59         Integer integ = null;
 60         Iterator iter = map.entrySet().iterator();
 61         while(iter.hasNext()) {
 62             Map.Entry entry = (Map.Entry)iter.next();
 63             
 64             key = (String)entry.getKey();
 65             integ = (Integer)entry.getValue();
 66             System.out.println(key+" -- "+integ.intValue());
 67         }
 68     }
 69 
 70     /*
 71      * 通過keyset來遍歷TreeMap
 72      * 效率低!
 73      */
 74     private static void iteratorTreeMapByKeyset(TreeMap map) {
 75         if (map == null)
 76             return ;
 77 
 78         System.out.println("\niterator TreeMap By keyset");
 79         String key = null;
 80         Integer integ = null;
 81         Iterator iter = map.keySet().iterator();
 82         while (iter.hasNext()) {
 83             key = (String)iter.next();
 84             integ = (Integer)map.get(key);
 85             System.out.println(key+" -- "+integ.intValue());
 86         }
 87     }
 88     
 89 
 90     /*
 91      * 遍歷TreeMap的values
 92      */
 93     private static void iteratorTreeMapJustValues(TreeMap map) {
 94         if (map == null)
 95             return ;
 96         
 97         Collection c = map.values();
 98         Iterator iter= c.iterator();
 99         while (iter.hasNext()) {
100             System.out.println(iter.next());
101        }
102     }
103 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103

第5部分 TreeMap示例

下面通過實例來學習如何使用TreeMap

  1 import java.util.*;
  2 
  3 /**
  4  * @desc TreeMap測試程序 
  5  *
  6  * @author skywang
  7  */
  8 public class TreeMapTest  {
  9 
 10     public static void main(String[] args) {
 11         // 測試常用的API
 12         testTreeMapOridinaryAPIs();
 13 
 14         // 測試TreeMap的導航函數
 15         //testNavigableMapAPIs();
 16 
 17         // 測試TreeMap的子Map函數
 18         //testSubMapAPIs();
 19     }
 20 
 21     /**
 22      * 測試常用的API
 23      */
 24     private static void testTreeMapOridinaryAPIs() {
 25         // 初始化隨機種子
 26         Random r = new Random();
 27         // 新建TreeMap
 28         TreeMap tmap = new TreeMap();
 29         // 添加操作
 30         tmap.put("one", r.nextInt(10));
 31         tmap.put("two", r.nextInt(10));
 32         tmap.put("three", r.nextInt(10));
 33 
 34         System.out.printf("\n ---- testTreeMapOridinaryAPIs ----\n");
 35         // 打印出TreeMap
 36         System.out.printf("%s\n",tmap );
 37 
 38         // 通過Iterator遍歷key-value
 39         Iterator iter = tmap.entrySet().iterator();
 40         while(iter.hasNext()) {
 41             Map.Entry entry = (Map.Entry)iter.next();
 42             System.out.printf("next : %s - %s\n", entry.getKey(), entry.getValue());
 43         }
 44 
 45         // TreeMap的鍵值對個數        
 46         System.out.printf("size: %s\n", tmap.size());
 47 
 48         // containsKey(Object key) :是否包含鍵key
 49         System.out.printf("contains key two : %s\n",tmap.containsKey("two"));
 50         System.out.printf("contains key five : %s\n",tmap.containsKey("five"));
 51 
 52         // containsValue(Object value) :是否包含值value
 53         System.out.printf("contains value 0 : %s\n",tmap.containsValue(new Integer(0)));
 54 
 55         // remove(Object key) : 刪除鍵key對應的鍵值對
 56         tmap.remove("three");
 57 
 58         System.out.printf("tmap:%s\n",tmap );
 59 
 60         // clear() : 清空TreeMap
 61         tmap.clear();
 62 
 63         // isEmpty() : TreeMap是否爲空
 64         System.out.printf("%s\n", (tmap.isEmpty()?"tmap is empty":"tmap is not empty") );
 65     }
 66 
 67 
 68     /**
 69      * 測試TreeMap的子Map函數
 70      */
 71     public static void testSubMapAPIs() {
 72         // 新建TreeMap
 73         TreeMap tmap = new TreeMap();
 74         // 添加“鍵值對”
 75         tmap.put("a", 101);
 76         tmap.put("b", 102);
 77         tmap.put("c", 103);
 78         tmap.put("d", 104);
 79         tmap.put("e", 105);
 80 
 81         System.out.printf("\n ---- testSubMapAPIs ----\n");
 82         // 打印出TreeMap
 83         System.out.printf("tmap:\n\t%s\n", tmap);
 84 
 85         // 測試 headMap(K toKey)
 86         System.out.printf("tmap.headMap(\"c\"):\n\t%s\n", tmap.headMap("c"));
 87         // 測試 headMap(K toKey, boolean inclusive) 
 88         System.out.printf("tmap.headMap(\"c\", true):\n\t%s\n", tmap.headMap("c", true));
 89         System.out.printf("tmap.headMap(\"c\", false):\n\t%s\n", tmap.headMap("c", false));
 90 
 91         // 測試 tailMap(K fromKey)
 92         System.out.printf("tmap.tailMap(\"c\"):\n\t%s\n", tmap.tailMap("c"));
 93         // 測試 tailMap(K fromKey, boolean inclusive)
 94         System.out.printf("tmap.tailMap(\"c\", true):\n\t%s\n", tmap.tailMap("c", true));
 95         System.out.printf("tmap.tailMap(\"c\", false):\n\t%s\n", tmap.tailMap("c", false));
 96    
 97         // 測試 subMap(K fromKey, K toKey)
 98         System.out.printf("tmap.subMap(\"a\", \"c\"):\n\t%s\n", tmap.subMap("a", "c"));
 99         // 測試 
100         System.out.printf("tmap.subMap(\"a\", true, \"c\", true):\n\t%s\n", 
101                 tmap.subMap("a", true, "c", true));
102         System.out.printf("tmap.subMap(\"a\", true, \"c\", false):\n\t%s\n", 
103                 tmap.subMap("a", true, "c", false));
104         System.out.printf("tmap.subMap(\"a\", false, \"c\", true):\n\t%s\n", 
105                 tmap.subMap("a", false, "c", true));
106         System.out.printf("tmap.subMap(\"a\", false, \"c\", false):\n\t%s\n", 
107                 tmap.subMap("a", false, "c", false));
108 
109         // 測試 navigableKeySet()
110         System.out.printf("tmap.navigableKeySet():\n\t%s\n", tmap.navigableKeySet());
111         // 測試 descendingKeySet()
112         System.out.printf("tmap.descendingKeySet():\n\t%s\n", tmap.descendingKeySet());
113     }
114 
115     /**
116      * 測試TreeMap的導航函數
117      */
118     public static void testNavigableMapAPIs() {
119         // 新建TreeMap
120         NavigableMap nav = new TreeMap();
121         // 添加“鍵值對”
122         nav.put("aaa", 111);
123         nav.put("bbb", 222);
124         nav.put("eee", 333);
125         nav.put("ccc", 555);
126         nav.put("ddd", 444);
127 
128         System.out.printf("\n ---- testNavigableMapAPIs ----\n");
129         // 打印出TreeMap
130         System.out.printf("Whole list:%s%n", nav);
131 
132         // 獲取第一個key、第一個Entry
133         System.out.printf("First key: %s\tFirst entry: %s%n",nav.firstKey(), nav.firstEntry());
134 
135         // 獲取最後一個key、最後一個Entry
136         System.out.printf("Last key: %s\tLast entry: %s%n",nav.lastKey(), nav.lastEntry());
137 
138         // 獲取“小於/等於bbb”的最大鍵值對
139         System.out.printf("Key floor before bbb: %s%n",nav.floorKey("bbb"));
140 
141         // 獲取“小於bbb”的最大鍵值對
142         System.out.printf("Key lower before bbb: %s%n", nav.lowerKey("bbb"));
143 
144         // 獲取“大於/等於bbb”的最小鍵值對
145         System.out.printf("Key ceiling after ccc: %s%n",nav.ceilingKey("ccc"));
146 
147         // 獲取“大於bbb”的最小鍵值對
148         System.out.printf("Key higher after ccc: %s%n\n",nav.higherKey("ccc"));
149     }
150 
151 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151

運行結果:

{one=8, three=4, two=2}
next : one - 8
next : three - 4
next : two - 2
size: 3
contains key two : true
contains key five : false
contains value 0 : false
tmap:{one=8, two=2}
tmap is empty
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章