摘要:基于紅黑樹實現,在之前篇章中有所涉及,所以本篇重點不在此。費解順帶一提,如果你還記得之前文章中的也用到了紅黑樹,而它先比較的再比值,這比較的是值。在這的作用類似中的,修復紅黑樹性質。
TreeMap基于紅黑樹實現,在之前HashMap篇章中有所涉及,所以本篇重點不在此。上路~containsKey() --> getEntry() --> getEntryUsingComparator()
/** * Returns {@code true} if this map contains a mapping for the specified * key. * * @param key key whose presence in this map is to be tested * @return {@code true} if this map contains a mapping for the * specified key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null * and this map uses natural ordering, or its comparator * does not permit null keys */ public boolean containsKey(Object key) { return getEntry(key) != null; // Key不能為null } /** * Returns this map"s entry for the given key, or {@code null} if the map * does not contain an entry for the key. * * @return this map"s entry for the given key, or {@code null} if the map * does not contain an entry for the key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null * and this map uses natural ordering, or its comparator * does not permit null keys */ final EntrygetEntry(Object key) { // Offload comparator-based version for sake of performance if (comparator != null) return getEntryUsingComparator(key); if (key == null) throw new NullPointerException(); @SuppressWarnings("unchecked") Comparable super K> k = (Comparable super K>) key; Entry p = root; while (p != null) { int cmp = k.compareTo(p.key); if (cmp < 0) p = p.left; else if (cmp > 0) p = p.right; else return p; } return null; } /** * Version of getEntry using comparator. Split off from getEntry * for performance. (This is not worth doing for most methods, * that are less dependent on comparator performance, but is * worthwhile here.) */ final Entry getEntryUsingComparator(Object key) { @SuppressWarnings("unchecked") K k = (K) key; Comparator super K> cpr = comparator; if (cpr != null) { Entry p = root; while (p != null) { int cmp = cpr.compare(k, p.key); if (cmp < 0) p = p.left; else if (cmp > 0) p = p.right; else return p; } } return null; }
雖然明面上是獲取值的方法,本質卻是比出個高低等。這里將Java的java.util.Comparator(比較器排序)、java.lang.Comparable(自然排序)都用到了。順便補了兩者知識點(見文末①)。當然這里好奇的是源碼中將使用comparator比較獨立提成方法,說是能提高性能。why?反向思考下,假使將getEntryUsingComparator()方法內代碼放回getEntry()似乎也就多了一對“{}”。費解- -
順帶一提,如果你還記得之前文章中的HashMap也用到了紅黑樹,而它先比較的hash再比key值,這比較的是key值。
put() --> compare() --> fixAfterInsertion()/** * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for the key, the old * value is replaced. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * * @return the previous value associated with {@code key}, or * {@code null} if there was no mapping for {@code key}. * (A {@code null} return can also indicate that the map * previously associated {@code null} with {@code key}.) * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null * and this map uses natural ordering, or its comparator * does not permit null keys */ public V put(K key, V value) { Entryt = root; if (t == null) { compare(key, key); // type (and possibly null) check root = new Entry<>(key, value, null); size = 1; modCount++; return null; } int cmp; Entry parent; // split comparator and comparable paths Comparator super K> cpr = comparator; if (cpr != null) { do { parent = t; cmp = cpr.compare(key, t.key); if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null); } else { if (key == null) throw new NullPointerException(); @SuppressWarnings("unchecked") Comparable super K> k = (Comparable super K>) key; do { parent = t; cmp = k.compareTo(t.key); if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null); } Entry e = new Entry<>(key, value, parent); if (cmp < 0) parent.left = e; else parent.right = e; fixAfterInsertion(e); size++; modCount++; return null; } /** * Compares two keys using the correct comparison method for this TreeMap. */ @SuppressWarnings("unchecked") final int compare(Object k1, Object k2) { return comparator==null ? ((Comparable super K>)k1).compareTo((K)k2) : comparator.compare((K)k1, (K)k2); } /** From CLR */ private void fixAfterInsertion(Entry x) { x.color = RED; while (x != null && x != root && x.parent.color == RED) { if (parentOf(x) == leftOf(parentOf(parentOf(x)))) { Entry y = rightOf(parentOf(parentOf(x))); if (colorOf(y) == RED) { setColor(parentOf(x), BLACK); setColor(y, BLACK); setColor(parentOf(parentOf(x)), RED); x = parentOf(parentOf(x)); } else { if (x == rightOf(parentOf(x))) { x = parentOf(x); rotateLeft(x); } setColor(parentOf(x), BLACK); setColor(parentOf(parentOf(x)), RED); rotateRight(parentOf(parentOf(x))); } } else { Entry y = leftOf(parentOf(parentOf(x))); if (colorOf(y) == RED) { setColor(parentOf(x), BLACK); setColor(y, BLACK); setColor(parentOf(parentOf(x)), RED); x = parentOf(parentOf(x)); } else { if (x == leftOf(parentOf(x))) { x = parentOf(x); rotateRight(x); } setColor(parentOf(x), BLACK); setColor(parentOf(parentOf(x)), RED); rotateLeft(parentOf(parentOf(x))); } } } root.color = BLACK; }
"compare(key, key);"是一個有意思寫法。從注釋直譯就是類型(為null可能性)檢查。為空檢查很好理解,因為null.xx()肯定跑異常,至于類型檢查筆者理解是要求鍵值實現Comparable接口。
"from CLR"是指Cormen, Leiserson, Rivest,他們是算法導論的作者,也就是說TreeMap里面算法都是參照算法導論的偽代碼。
由于TreeMap的有序性,使其增刪查都是先進行比較,找到合適的位置。fixAfterInsertion()在這的作用類似HashMap中的balanceInsertion(),修復紅黑樹性質。
deleteEntry() --> successor() --> fixAfterDeletion()/** * Delete node p, and then rebalance the tree. */ private void deleteEntry(Entryp) { modCount++; size--; // If strictly internal, copy successor"s element to p and then make p // point to successor. if (p.left != null && p.right != null) { Entry s = successor(p); p.key = s.key; p.value = s.value; p = s; } // p has 2 children // Start fixup at replacement node, if it exists. Entry replacement = (p.left != null ? p.left : p.right); if (replacement != null) { // Link replacement to parent replacement.parent = p.parent; if (p.parent == null) root = replacement; else if (p == p.parent.left) p.parent.left = replacement; else p.parent.right = replacement; // Null out links so they are OK to use by fixAfterDeletion. p.left = p.right = p.parent = null; // Fix replacement if (p.color == BLACK) fixAfterDeletion(replacement); } else if (p.parent == null) { // return if we are the only node. root = null; } else { // No children. Use self as phantom replacement and unlink. if (p.color == BLACK) fixAfterDeletion(p); if (p.parent != null) { if (p == p.parent.left) p.parent.left = null; else if (p == p.parent.right) p.parent.right = null; p.parent = null; } } } /** * Returns the successor of the specified Entry, or null if no such. */ static TreeMap.Entry successor(Entry t) { if (t == null) return null; else if (t.right != null) { // ① ② Entry p = t.right; while (p.left != null) p = p.left; return p; } else { //③ ④ ⑤ Entry p = t.parent; Entry ch = t; while (p != null && ch == p.right) { ch = p; p = p.parent; } return p; } }
successor()可以簡單的理解為“一個升序數組a[index],successor即為a[index+1]”。相對的還有prodecessor()。源碼中可能出現的情況抽象如下圖(while只舉一次循環為例)。
deleteEntry調用successor時,由于right != null,所以不會出現③ ④ ⑤的情況。基本思路就是找到“a[index+1]”(p)替換待刪節點,然后使“a[index+1]”的子節點(replacement)指向其父節點(Link replacement to parent),最后清p、fixAfterDeletion修復紅黑樹性。
如果覺得這個看懂了,可以挑戰下HashMap.TreeNode.removeTreeNode()。
說點什么:TreeMap 有序;非線程安全;key值不支持null...;
實現了NavigableMap接口(見文末②),NavigableMap具有了針對給定搜索目標返回最接近匹配項的導航方法。
如: lowerEntry、floorEntry、ceilingEntry 和 higherEntry 分別返回與小于、小于等于、大于等于、大于給定鍵的 Map.Entry對象,如果不存在這樣的鍵,則返回 null。
實現了SortedMap接口:它用來保持鍵的有序順序,也提供了范圍檢索的一些方法;
如: headMap、subMap、tailMap分別返回小于結束鍵、大于或等于開始和小于結束鍵、大于或等于開始鍵的Map.Entry對象。
添加到SortedMap實現類的元素必須實現Comparable接口,否則您必須給它的構造函數提供一個Comparator接口的實現。TreeMap類是它的唯一一份實現。
更多有意思的內容,歡迎訪問筆者小站: rebey.cn
知識點:①Java中自然排序和比較器排序詳解:Comparable與Comparator;
②計算機程序的思維邏輯 (43) - 剖析TreeMap:方法應用舉例;
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/67159.html
摘要:如今行至于此,當觀賞一方。由于所返回的無執行意義。源碼閱讀總體門檻相對而言比,畢竟大多數底層都由實現了。比心可通過這篇文章理解創建一個實例過程圖工作原理往期線路回顧源碼一帶一路系列之源碼一帶一路系列之源碼一帶一路系列之 本文以jdk1.8中LinkedHashMap.afterNodeAccess()方法為切入點,分析其中難理解、有價值的源碼片段(類似源碼查看是ctrl+鼠標左鍵的過程...
摘要:一路至此,風景過半。與雖然名字各異,源碼實現基本相同,除了增加了線程安全。同時注意溢出情況處理。同時增加了考慮并發問題。此外,源碼中出現了大量泛型如。允許為非線程安全有序。 一路至此,風景過半。ArrayList與Vector雖然名字各異,源碼實現基本相同,除了Vector增加了線程安全。所以作者建議我們在不需要線程安全的情況下盡量使用ArrayList。下面看看在ArrayList源...
摘要:同樣在源碼的與分別見看到老朋友和。這樣做可以降低性能消耗的同時,還可以減少序列化字節流的大小,從而減少網絡開銷框架中。使用了反射來尋找是否聲明了這兩個方法。十進制和,通過返回值能反應當前狀態。 Map篇暫告段落,卻并非離我們而去。這不在本篇中你就能經常見到她。HashSet、LinkedHashSet、TreeSet各自基于對應Map實現,各自源碼內容較少,因此歸納為一篇。 HashS...
摘要:本篇涉及少許以下簡稱新特性,請驢友們系好安全帶,準備開車。觀光線路圖是在中新增的一個方法,相對而言較為陌生。其作用是把的計算結果關聯到上即返回值作為新。實際上,乃縮寫,即二元函數之意類似。 本文以jdk1.8中HashMap.compute()方法為切入點,分析其中難理解、有價值的源碼片段(類似源碼查看是ctrl+鼠標左鍵的過程)。本篇涉及少許Java8(以下簡稱J8)新特性,請驢友們...
摘要:觀光線路圖將涉及到的源碼全局變量哈希表初始化長度默認值是負載因子默認表示的填滿程度。根據是否為零將原鏈表拆分成個鏈表,一部分仍保留在原鏈表中不需要移動,一部分移動到原索引的新鏈表中。 前言 本文以jdk1.8中HashMap.putAll()方法為切入點,分析其中難理解、有價值的源碼片段(類似ctrl+鼠標左鍵查看的源碼過程)。?觀光線路圖:putAll() --> putMapEnt...
閱讀 3577·2021-10-15 09:43
閱讀 3498·2021-09-02 15:21
閱讀 2210·2021-08-11 11:23
閱讀 3249·2019-08-30 15:54
閱讀 1940·2019-08-30 13:54
閱讀 3210·2019-08-29 18:35
閱讀 680·2019-08-29 16:58
閱讀 1757·2019-08-29 12:49