1. /*
  2. * @(#)TreeMap.java 1.65 04/02/19
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util;
  8. /**
  9. * Red-Black tree based implementation of the <tt>SortedMap</tt> interface.
  10. * This class guarantees that the map will be in ascending key order, sorted
  11. * according to the <i>natural order</i> for the key's class (see
  12. * <tt>Comparable</tt>), or by the comparator provided at creation time,
  13. * depending on which constructor is used.<p>
  14. *
  15. * This implementation provides guaranteed log(n) time cost for the
  16. * <tt>containsKey</tt>, <tt>get</tt>, <tt>put</tt> and <tt>remove</tt>
  17. * operations. Algorithms are adaptations of those in Cormen, Leiserson, and
  18. * Rivest's <I>Introduction to Algorithms</I>.<p>
  19. *
  20. * Note that the ordering maintained by a sorted map (whether or not an
  21. * explicit comparator is provided) must be <i>consistent with equals</i> if
  22. * this sorted map is to correctly implement the <tt>Map</tt> interface. (See
  23. * <tt>Comparable</tt> or <tt>Comparator</tt> for a precise definition of
  24. * <i>consistent with equals</i>.) This is so because the <tt>Map</tt>
  25. * interface is defined in terms of the equals operation, but a map performs
  26. * all key comparisons using its <tt>compareTo</tt> (or <tt>compare</tt>)
  27. * method, so two keys that are deemed equal by this method are, from the
  28. * standpoint of the sorted map, equal. The behavior of a sorted map
  29. * <i>is</i> well-defined even if its ordering is inconsistent with equals; it
  30. * just fails to obey the general contract of the <tt>Map</tt> interface.<p>
  31. *
  32. * <b>Note that this implementation is not synchronized.</b> If multiple
  33. * threads access a map concurrently, and at least one of the threads modifies
  34. * the map structurally, it <i>must</i> be synchronized externally. (A
  35. * structural modification is any operation that adds or deletes one or more
  36. * mappings; merely changing the value associated with an existing key is not
  37. * a structural modification.) This is typically accomplished by
  38. * synchronizing on some object that naturally encapsulates the map. If no
  39. * such object exists, the map should be "wrapped" using the
  40. * <tt>Collections.synchronizedMap</tt> method. This is best done at creation
  41. * time, to prevent accidental unsynchronized access to the map:
  42. * <pre>
  43. * Map m = Collections.synchronizedMap(new TreeMap(...));
  44. * </pre><p>
  45. *
  46. * The iterators returned by all of this class's "collection view methods" are
  47. * <i>fail-fast</i>: if the map is structurally modified at any time after the
  48. * iterator is created, in any way except through the iterator's own
  49. * <tt>remove</tt> or <tt>add</tt> methods, the iterator throws a
  50. * <tt>ConcurrentModificationException</tt>. Thus, in the face of concurrent
  51. * modification, the iterator fails quickly and cleanly, rather than risking
  52. * arbitrary, non-deterministic behavior at an undetermined time in the
  53. * future.
  54. *
  55. * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
  56. * as it is, generally speaking, impossible to make any hard guarantees in the
  57. * presence of unsynchronized concurrent modification. Fail-fast iterators
  58. * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
  59. * Therefore, it would be wrong to write a program that depended on this
  60. * exception for its correctness: <i>the fail-fast behavior of iterators
  61. * should be used only to detect bugs.</i><p>
  62. *
  63. * This class is a member of the
  64. * <a href="{@docRoot}/../guide/collections/index.html">
  65. * Java Collections Framework</a>.
  66. *
  67. * @author Josh Bloch and Doug Lea
  68. * @version 1.65, 02/19/04
  69. * @see Map
  70. * @see HashMap
  71. * @see Hashtable
  72. * @see Comparable
  73. * @see Comparator
  74. * @see Collection
  75. * @see Collections#synchronizedMap(Map)
  76. * @since 1.2
  77. */
  78. public class TreeMap<K,V>
  79. extends AbstractMap<K,V>
  80. implements SortedMap<K,V>, Cloneable, java.io.Serializable
  81. {
  82. /**
  83. * The Comparator used to maintain order in this TreeMap, or
  84. * null if this TreeMap uses its elements natural ordering.
  85. *
  86. * @serial
  87. */
  88. private Comparator<? super K> comparator = null;
  89. private transient Entry<K,V> root = null;
  90. /**
  91. * The number of entries in the tree
  92. */
  93. private transient int size = 0;
  94. /**
  95. * The number of structural modifications to the tree.
  96. */
  97. private transient int modCount = 0;
  98. private void incrementSize() { modCount++; size++; }
  99. private void decrementSize() { modCount++; size--; }
  100. /**
  101. * Constructs a new, empty map, sorted according to the keys' natural
  102. * order. All keys inserted into the map must implement the
  103. * <tt>Comparable</tt> interface. Furthermore, all such keys must be
  104. * <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw a
  105. * ClassCastException for any elements <tt>k1</tt> and <tt>k2</tt> in the
  106. * map. If the user attempts to put a key into the map that violates this
  107. * constraint (for example, the user attempts to put a string key into a
  108. * map whose keys are integers), the <tt>put(Object key, Object
  109. * value)</tt> call will throw a <tt>ClassCastException</tt>.
  110. *
  111. * @see Comparable
  112. */
  113. public TreeMap() {
  114. }
  115. /**
  116. * Constructs a new, empty map, sorted according to the given comparator.
  117. * All keys inserted into the map must be <i>mutually comparable</i> by
  118. * the given comparator: <tt>comparator.compare(k1, k2)</tt> must not
  119. * throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and
  120. * <tt>k2</tt> in the map. If the user attempts to put a key into the
  121. * map that violates this constraint, the <tt>put(Object key, Object
  122. * value)</tt> call will throw a <tt>ClassCastException</tt>.
  123. *
  124. * @param c the comparator that will be used to sort this map. A
  125. * <tt>null</tt> value indicates that the keys' <i>natural
  126. * ordering</i> should be used.
  127. */
  128. public TreeMap(Comparator<? super K> c) {
  129. this.comparator = c;
  130. }
  131. /**
  132. * Constructs a new map containing the same mappings as the given map,
  133. * sorted according to the keys' <i>natural order</i>. All keys inserted
  134. * into the new map must implement the <tt>Comparable</tt> interface.
  135. * Furthermore, all such keys must be <i>mutually comparable</i>:
  136. * <tt>k1.compareTo(k2)</tt> must not throw a <tt>ClassCastException</tt>
  137. * for any elements <tt>k1</tt> and <tt>k2</tt> in the map. This method
  138. * runs in n*log(n) time.
  139. *
  140. * @param m the map whose mappings are to be placed in this map.
  141. * @throws ClassCastException the keys in t are not Comparable, or
  142. * are not mutually comparable.
  143. * @throws NullPointerException if the specified map is null.
  144. */
  145. public TreeMap(Map<? extends K, ? extends V> m) {
  146. putAll(m);
  147. }
  148. /**
  149. * Constructs a new map containing the same mappings as the given
  150. * <tt>SortedMap</tt>, sorted according to the same ordering. This method
  151. * runs in linear time.
  152. *
  153. * @param m the sorted map whose mappings are to be placed in this map,
  154. * and whose comparator is to be used to sort this map.
  155. * @throws NullPointerException if the specified sorted map is null.
  156. */
  157. public TreeMap(SortedMap<K, ? extends V> m) {
  158. comparator = m.comparator();
  159. try {
  160. buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
  161. } catch (java.io.IOException cannotHappen) {
  162. } catch (ClassNotFoundException cannotHappen) {
  163. }
  164. }
  165. // Query Operations
  166. /**
  167. * Returns the number of key-value mappings in this map.
  168. *
  169. * @return the number of key-value mappings in this map.
  170. */
  171. public int size() {
  172. return size;
  173. }
  174. /**
  175. * Returns <tt>true</tt> if this map contains a mapping for the specified
  176. * key.
  177. *
  178. * @param key key whose presence in this map is to be tested.
  179. *
  180. * @return <tt>true</tt> if this map contains a mapping for the
  181. * specified key.
  182. * @throws ClassCastException if the key cannot be compared with the keys
  183. * currently in the map.
  184. * @throws NullPointerException key is <tt>null</tt> and this map uses
  185. * natural ordering, or its comparator does not tolerate
  186. * <tt>null</tt> keys.
  187. */
  188. public boolean containsKey(Object key) {
  189. return getEntry(key) != null;
  190. }
  191. /**
  192. * Returns <tt>true</tt> if this map maps one or more keys to the
  193. * specified value. More formally, returns <tt>true</tt> if and only if
  194. * this map contains at least one mapping to a value <tt>v</tt> such
  195. * that <tt>(value==null ? v==null : value.equals(v))</tt>. This
  196. * operation will probably require time linear in the Map size for most
  197. * implementations of Map.
  198. *
  199. * @param value value whose presence in this Map is to be tested.
  200. * @return <tt>true</tt> if a mapping to <tt>value</tt> exists;
  201. * <tt>false</tt> otherwise.
  202. * @since 1.2
  203. */
  204. public boolean containsValue(Object value) {
  205. return (root==null ? false :
  206. (value==null ? valueSearchNull(root)
  207. : valueSearchNonNull(root, value)));
  208. }
  209. private boolean valueSearchNull(Entry n) {
  210. if (n.value == null)
  211. return true;
  212. // Check left and right subtrees for value
  213. return (n.left != null && valueSearchNull(n.left)) ||
  214. (n.right != null && valueSearchNull(n.right));
  215. }
  216. private boolean valueSearchNonNull(Entry n, Object value) {
  217. // Check this node for the value
  218. if (value.equals(n.value))
  219. return true;
  220. // Check left and right subtrees for value
  221. return (n.left != null && valueSearchNonNull(n.left, value)) ||
  222. (n.right != null && valueSearchNonNull(n.right, value));
  223. }
  224. /**
  225. * Returns the value to which this map maps the specified key. Returns
  226. * <tt>null</tt> if the map contains no mapping for this key. A return
  227. * value of <tt>null</tt> does not <i>necessarily</i> indicate that the
  228. * map contains no mapping for the key; it's also possible that the map
  229. * explicitly maps the key to <tt>null</tt>. The <tt>containsKey</tt>
  230. * operation may be used to distinguish these two cases.
  231. *
  232. * @param key key whose associated value is to be returned.
  233. * @return the value to which this map maps the specified key, or
  234. * <tt>null</tt> if the map contains no mapping for the key.
  235. * @throws ClassCastException key cannot be compared with the keys
  236. * currently in the map.
  237. * @throws NullPointerException key is <tt>null</tt> and this map uses
  238. * natural ordering, or its comparator does not tolerate
  239. * <tt>null</tt> keys.
  240. *
  241. * @see #containsKey(Object)
  242. */
  243. public V get(Object key) {
  244. Entry<K,V> p = getEntry(key);
  245. return (p==null ? null : p.value);
  246. }
  247. /**
  248. * Returns the comparator used to order this map, or <tt>null</tt> if this
  249. * map uses its keys' natural order.
  250. *
  251. * @return the comparator associated with this sorted map, or
  252. * <tt>null</tt> if it uses its keys' natural sort method.
  253. */
  254. public Comparator<? super K> comparator() {
  255. return comparator;
  256. }
  257. /**
  258. * Returns the first (lowest) key currently in this sorted map.
  259. *
  260. * @return the first (lowest) key currently in this sorted map.
  261. * @throws NoSuchElementException Map is empty.
  262. */
  263. public K firstKey() {
  264. return key(firstEntry());
  265. }
  266. /**
  267. * Returns the last (highest) key currently in this sorted map.
  268. *
  269. * @return the last (highest) key currently in this sorted map.
  270. * @throws NoSuchElementException Map is empty.
  271. */
  272. public K lastKey() {
  273. return key(lastEntry());
  274. }
  275. /**
  276. * Copies all of the mappings from the specified map to this map. These
  277. * mappings replace any mappings that this map had for any of the keys
  278. * currently in the specified map.
  279. *
  280. * @param map mappings to be stored in this map.
  281. * @throws ClassCastException class of a key or value in the specified
  282. * map prevents it from being stored in this map.
  283. *
  284. * @throws NullPointerException if the given map is <tt>null</tt> or
  285. * this map does not permit <tt>null</tt> keys and a
  286. * key in the specified map is <tt>null</tt>.
  287. */
  288. public void putAll(Map<? extends K, ? extends V> map) {
  289. int mapSize = map.size();
  290. if (size==0 && mapSize!=0 && map instanceof SortedMap) {
  291. Comparator c = ((SortedMap)map).comparator();
  292. if (c == comparator || (c != null && c.equals(comparator))) {
  293. ++modCount;
  294. try {
  295. buildFromSorted(mapSize, map.entrySet().iterator(),
  296. null, null);
  297. } catch (java.io.IOException cannotHappen) {
  298. } catch (ClassNotFoundException cannotHappen) {
  299. }
  300. return;
  301. }
  302. }
  303. super.putAll(map);
  304. }
  305. /**
  306. * Returns this map's entry for the given key, or <tt>null</tt> if the map
  307. * does not contain an entry for the key.
  308. *
  309. * @return this map's entry for the given key, or <tt>null</tt> if the map
  310. * does not contain an entry for the key.
  311. * @throws ClassCastException if the key cannot be compared with the keys
  312. * currently in the map.
  313. * @throws NullPointerException key is <tt>null</tt> and this map uses
  314. * natural order, or its comparator does not tolerate *
  315. * <tt>null</tt> keys.
  316. */
  317. private Entry<K,V> getEntry(Object key) {
  318. Entry<K,V> p = root;
  319. K k = (K) key;
  320. while (p != null) {
  321. int cmp = compare(k, p.key);
  322. if (cmp == 0)
  323. return p;
  324. else if (cmp < 0)
  325. p = p.left;
  326. else
  327. p = p.right;
  328. }
  329. return null;
  330. }
  331. /**
  332. * Gets the entry corresponding to the specified key; if no such entry
  333. * exists, returns the entry for the least key greater than the specified
  334. * key; if no such entry exists (i.e., the greatest key in the Tree is less
  335. * than the specified key), returns <tt>null</tt>.
  336. */
  337. private Entry<K,V> getCeilEntry(K key) {
  338. Entry<K,V> p = root;
  339. if (p==null)
  340. return null;
  341. while (true) {
  342. int cmp = compare(key, p.key);
  343. if (cmp == 0) {
  344. return p;
  345. } else if (cmp < 0) {
  346. if (p.left != null)
  347. p = p.left;
  348. else
  349. return p;
  350. } else {
  351. if (p.right != null) {
  352. p = p.right;
  353. } else {
  354. Entry<K,V> parent = p.parent;
  355. Entry<K,V> ch = p;
  356. while (parent != null && ch == parent.right) {
  357. ch = parent;
  358. parent = parent.parent;
  359. }
  360. return parent;
  361. }
  362. }
  363. }
  364. }
  365. /**
  366. * Returns the entry for the greatest key less than the specified key; if
  367. * no such entry exists (i.e., the least key in the Tree is greater than
  368. * the specified key), returns <tt>null</tt>.
  369. */
  370. private Entry<K,V> getPrecedingEntry(K key) {
  371. Entry<K,V> p = root;
  372. if (p==null)
  373. return null;
  374. while (true) {
  375. int cmp = compare(key, p.key);
  376. if (cmp > 0) {
  377. if (p.right != null)
  378. p = p.right;
  379. else
  380. return p;
  381. } else {
  382. if (p.left != null) {
  383. p = p.left;
  384. } else {
  385. Entry<K,V> parent = p.parent;
  386. Entry<K,V> ch = p;
  387. while (parent != null && ch == parent.left) {
  388. ch = parent;
  389. parent = parent.parent;
  390. }
  391. return parent;
  392. }
  393. }
  394. }
  395. }
  396. /**
  397. * Returns the key corresponding to the specified Entry. Throw
  398. * NoSuchElementException if the Entry is <tt>null</tt>.
  399. */
  400. private static <K> K key(Entry<K,?> e) {
  401. if (e==null)
  402. throw new NoSuchElementException();
  403. return e.key;
  404. }
  405. /**
  406. * Associates the specified value with the specified key in this map.
  407. * If the map previously contained a mapping for this key, the old
  408. * value is replaced.
  409. *
  410. * @param key key with which the specified value is to be associated.
  411. * @param value value to be associated with the specified key.
  412. *
  413. * @return previous value associated with specified key, or <tt>null</tt>
  414. * if there was no mapping for key. A <tt>null</tt> return can
  415. * also indicate that the map previously associated <tt>null</tt>
  416. * with the specified key.
  417. * @throws ClassCastException key cannot be compared with the keys
  418. * currently in the map.
  419. * @throws NullPointerException key is <tt>null</tt> and this map uses
  420. * natural order, or its comparator does not tolerate
  421. * <tt>null</tt> keys.
  422. */
  423. public V put(K key, V value) {
  424. Entry<K,V> t = root;
  425. if (t == null) {
  426. incrementSize();
  427. root = new Entry<K,V>(key, value, null);
  428. return null;
  429. }
  430. while (true) {
  431. int cmp = compare(key, t.key);
  432. if (cmp == 0) {
  433. return t.setValue(value);
  434. } else if (cmp < 0) {
  435. if (t.left != null) {
  436. t = t.left;
  437. } else {
  438. incrementSize();
  439. t.left = new Entry<K,V>(key, value, t);
  440. fixAfterInsertion(t.left);
  441. return null;
  442. }
  443. } else { // cmp > 0
  444. if (t.right != null) {
  445. t = t.right;
  446. } else {
  447. incrementSize();
  448. t.right = new Entry<K,V>(key, value, t);
  449. fixAfterInsertion(t.right);
  450. return null;
  451. }
  452. }
  453. }
  454. }
  455. /**
  456. * Removes the mapping for this key from this TreeMap if present.
  457. *
  458. * @param key key for which mapping should be removed
  459. * @return previous value associated with specified key, or <tt>null</tt>
  460. * if there was no mapping for key. A <tt>null</tt> return can
  461. * also indicate that the map previously associated
  462. * <tt>null</tt> with the specified key.
  463. *
  464. * @throws ClassCastException key cannot be compared with the keys
  465. * currently in the map.
  466. * @throws NullPointerException key is <tt>null</tt> and this map uses
  467. * natural order, or its comparator does not tolerate
  468. * <tt>null</tt> keys.
  469. */
  470. public V remove(Object key) {
  471. Entry<K,V> p = getEntry(key);
  472. if (p == null)
  473. return null;
  474. V oldValue = p.value;
  475. deleteEntry(p);
  476. return oldValue;
  477. }
  478. /**
  479. * Removes all mappings from this TreeMap.
  480. */
  481. public void clear() {
  482. modCount++;
  483. size = 0;
  484. root = null;
  485. }
  486. /**
  487. * Returns a shallow copy of this <tt>TreeMap</tt> instance. (The keys and
  488. * values themselves are not cloned.)
  489. *
  490. * @return a shallow copy of this Map.
  491. */
  492. public Object clone() {
  493. TreeMap<K,V> clone = null;
  494. try {
  495. clone = (TreeMap<K,V>) super.clone();
  496. } catch (CloneNotSupportedException e) {
  497. throw new InternalError();
  498. }
  499. // Put clone into "virgin" state (except for comparator)
  500. clone.root = null;
  501. clone.size = 0;
  502. clone.modCount = 0;
  503. clone.entrySet = null;
  504. // Initialize clone with our mappings
  505. try {
  506. clone.buildFromSorted(size, entrySet().iterator(), null, null);
  507. } catch (java.io.IOException cannotHappen) {
  508. } catch (ClassNotFoundException cannotHappen) {
  509. }
  510. return clone;
  511. }
  512. // Views
  513. /**
  514. * This field is initialized to contain an instance of the entry set
  515. * view the first time this view is requested. The view is stateless,
  516. * so there's no reason to create more than one.
  517. */
  518. private transient volatile Set<Map.Entry<K,V>> entrySet = null;
  519. /**
  520. * Returns a Set view of the keys contained in this map. The set's
  521. * iterator will return the keys in ascending order. The map is backed by
  522. * this <tt>TreeMap</tt> instance, so changes to this map are reflected in
  523. * the Set, and vice-versa. The Set supports element removal, which
  524. * removes the corresponding mapping from the map, via the
  525. * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, <tt>removeAll</tt>,
  526. * <tt>retainAll</tt>, and <tt>clear</tt> operations. It does not support
  527. * the <tt>add</tt> or <tt>addAll</tt> operations.
  528. *
  529. * @return a set view of the keys contained in this TreeMap.
  530. */
  531. public Set<K> keySet() {
  532. if (keySet == null) {
  533. keySet = new AbstractSet<K>() {
  534. public Iterator<K> iterator() {
  535. return new KeyIterator();
  536. }
  537. public int size() {
  538. return TreeMap.this.size();
  539. }
  540. public boolean contains(Object o) {
  541. return containsKey(o);
  542. }
  543. public boolean remove(Object o) {
  544. int oldSize = size;
  545. TreeMap.this.remove(o);
  546. return size != oldSize;
  547. }
  548. public void clear() {
  549. TreeMap.this.clear();
  550. }
  551. };
  552. }
  553. return keySet;
  554. }
  555. /**
  556. * Returns a collection view of the values contained in this map. The
  557. * collection's iterator will return the values in the order that their
  558. * corresponding keys appear in the tree. The collection is backed by
  559. * this <tt>TreeMap</tt> instance, so changes to this map are reflected in
  560. * the collection, and vice-versa. The collection supports element
  561. * removal, which removes the corresponding mapping from the map through
  562. * the <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
  563. * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
  564. * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
  565. *
  566. * @return a collection view of the values contained in this map.
  567. */
  568. public Collection<V> values() {
  569. if (values == null) {
  570. values = new AbstractCollection<V>() {
  571. public Iterator<V> iterator() {
  572. return new ValueIterator();
  573. }
  574. public int size() {
  575. return TreeMap.this.size();
  576. }
  577. public boolean contains(Object o) {
  578. for (Entry<K,V> e = firstEntry(); e != null; e = successor(e))
  579. if (valEquals(e.getValue(), o))
  580. return true;
  581. return false;
  582. }
  583. public boolean remove(Object o) {
  584. for (Entry<K,V> e = firstEntry(); e != null; e = successor(e)) {
  585. if (valEquals(e.getValue(), o)) {
  586. deleteEntry(e);
  587. return true;
  588. }
  589. }
  590. return false;
  591. }
  592. public void clear() {
  593. TreeMap.this.clear();
  594. }
  595. };
  596. }
  597. return values;
  598. }
  599. /**
  600. * Returns a set view of the mappings contained in this map. The set's
  601. * iterator returns the mappings in ascending key order. Each element in
  602. * the returned set is a <tt>Map.Entry</tt>. The set is backed by this
  603. * map, so changes to this map are reflected in the set, and vice-versa.
  604. * The set supports element removal, which removes the corresponding
  605. * mapping from the TreeMap, through the <tt>Iterator.remove</tt>,
  606. * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
  607. * <tt>clear</tt> operations. It does not support the <tt>add</tt> or
  608. * <tt>addAll</tt> operations.
  609. *
  610. * @return a set view of the mappings contained in this map.
  611. * @see Map.Entry
  612. */
  613. public Set<Map.Entry<K,V>> entrySet() {
  614. if (entrySet == null) {
  615. entrySet = new AbstractSet<Map.Entry<K,V>>() {
  616. public Iterator<Map.Entry<K,V>> iterator() {
  617. return new EntryIterator();
  618. }
  619. public boolean contains(Object o) {
  620. if (!(o instanceof Map.Entry))
  621. return false;
  622. Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
  623. V value = entry.getValue();
  624. Entry<K,V> p = getEntry(entry.getKey());
  625. return p != null && valEquals(p.getValue(), value);
  626. }
  627. public boolean remove(Object o) {
  628. if (!(o instanceof Map.Entry))
  629. return false;
  630. Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
  631. V value = entry.getValue();
  632. Entry<K,V> p = getEntry(entry.getKey());
  633. if (p != null && valEquals(p.getValue(), value)) {
  634. deleteEntry(p);
  635. return true;
  636. }
  637. return false;
  638. }
  639. public int size() {
  640. return TreeMap.this.size();
  641. }
  642. public void clear() {
  643. TreeMap.this.clear();
  644. }
  645. };
  646. }
  647. return entrySet;
  648. }
  649. /**
  650. * Returns a view of the portion of this map whose keys range from
  651. * <tt>fromKey</tt>, inclusive, to <tt>toKey</tt>, exclusive. (If
  652. * <tt>fromKey</tt> and <tt>toKey</tt> are equal, the returned sorted map
  653. * is empty.) The returned sorted map is backed by this map, so changes
  654. * in the returned sorted map are reflected in this map, and vice-versa.
  655. * The returned sorted map supports all optional map operations.<p>
  656. *
  657. * The sorted map returned by this method will throw an
  658. * <tt>IllegalArgumentException</tt> if the user attempts to insert a key
  659. * less than <tt>fromKey</tt> or greater than or equal to
  660. * <tt>toKey</tt>.<p>
  661. *
  662. * Note: this method always returns a <i>half-open range</i> (which
  663. * includes its low endpoint but not its high endpoint). If you need a
  664. * <i>closed range</i> (which includes both endpoints), and the key type
  665. * allows for calculation of the successor a given key, merely request the
  666. * subrange from <tt>lowEndpoint</tt> to <tt>successor(highEndpoint)</tt>.
  667. * For example, suppose that <tt>m</tt> is a sorted map whose keys are
  668. * strings. The following idiom obtains a view containing all of the
  669. * key-value mappings in <tt>m</tt> whose keys are between <tt>low</tt>
  670. * and <tt>high</tt>, inclusive:
  671. * <pre> SortedMap sub = m.submap(low, high+"\0");</pre>
  672. * A similar technique can be used to generate an <i>open range</i> (which
  673. * contains neither endpoint). The following idiom obtains a view
  674. * containing all of the key-value mappings in <tt>m</tt> whose keys are
  675. * between <tt>low</tt> and <tt>high</tt>, exclusive:
  676. * <pre> SortedMap sub = m.subMap(low+"\0", high);</pre>
  677. *
  678. * @param fromKey low endpoint (inclusive) of the subMap.
  679. * @param toKey high endpoint (exclusive) of the subMap.
  680. *
  681. * @return a view of the portion of this map whose keys range from
  682. * <tt>fromKey</tt>, inclusive, to <tt>toKey</tt>, exclusive.
  683. *
  684. * @throws ClassCastException if <tt>fromKey</tt> and <tt>toKey</tt>
  685. * cannot be compared to one another using this map's comparator
  686. * (or, if the map has no comparator, using natural ordering).
  687. * @throws IllegalArgumentException if <tt>fromKey</tt> is greater than
  688. * <tt>toKey</tt>.
  689. * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
  690. * <tt>null</tt> and this map uses natural order, or its
  691. * comparator does not tolerate <tt>null</tt> keys.
  692. */
  693. public SortedMap<K,V> subMap(K fromKey, K toKey) {
  694. return new SubMap(fromKey, toKey);
  695. }
  696. /**
  697. * Returns a view of the portion of this map whose keys are strictly less
  698. * than <tt>toKey</tt>. The returned sorted map is backed by this map, so
  699. * changes in the returned sorted map are reflected in this map, and
  700. * vice-versa. The returned sorted map supports all optional map
  701. * operations.<p>
  702. *
  703. * The sorted map returned by this method will throw an
  704. * <tt>IllegalArgumentException</tt> if the user attempts to insert a key
  705. * greater than or equal to <tt>toKey</tt>.<p>
  706. *
  707. * Note: this method always returns a view that does not contain its
  708. * (high) endpoint. If you need a view that does contain this endpoint,
  709. * and the key type allows for calculation of the successor a given key,
  710. * merely request a headMap bounded by <tt>successor(highEndpoint)</tt>.
  711. * For example, suppose that suppose that <tt>m</tt> is a sorted map whose
  712. * keys are strings. The following idiom obtains a view containing all of
  713. * the key-value mappings in <tt>m</tt> whose keys are less than or equal
  714. * to <tt>high</tt>:
  715. * <pre>
  716. * SortedMap head = m.headMap(high+"\0");
  717. * </pre>
  718. *
  719. * @param toKey high endpoint (exclusive) of the headMap.
  720. * @return a view of the portion of this map whose keys are strictly
  721. * less than <tt>toKey</tt>.
  722. *
  723. * @throws ClassCastException if <tt>toKey</tt> is not compatible
  724. * with this map's comparator (or, if the map has no comparator,
  725. * if <tt>toKey</tt> does not implement <tt>Comparable</tt>).
  726. * @throws IllegalArgumentException if this map is itself a subMap,
  727. * headMap, or tailMap, and <tt>toKey</tt> is not within the
  728. * specified range of the subMap, headMap, or tailMap.
  729. * @throws NullPointerException if <tt>toKey</tt> is <tt>null</tt> and
  730. * this map uses natural order, or its comparator does not
  731. * tolerate <tt>null</tt> keys.
  732. */
  733. public SortedMap<K,V> headMap(K toKey) {
  734. return new SubMap(toKey, true);
  735. }
  736. /**
  737. * Returns a view of the portion of this map whose keys are greater than
  738. * or equal to <tt>fromKey</tt>. The returned sorted map is backed by
  739. * this map, so changes in the returned sorted map are reflected in this
  740. * map, and vice-versa. The returned sorted map supports all optional map
  741. * operations.<p>
  742. *
  743. * The sorted map returned by this method will throw an
  744. * <tt>IllegalArgumentException</tt> if the user attempts to insert a key
  745. * less than <tt>fromKey</tt>.<p>
  746. *
  747. * Note: this method always returns a view that contains its (low)
  748. * endpoint. If you need a view that does not contain this endpoint, and
  749. * the element type allows for calculation of the successor a given value,
  750. * merely request a tailMap bounded by <tt>successor(lowEndpoint)</tt>.
  751. * For example, suppose that <tt>m</tt> is a sorted map whose keys
  752. * are strings. The following idiom obtains a view containing
  753. * all of the key-value mappings in <tt>m</tt> whose keys are strictly
  754. * greater than <tt>low</tt>: <pre>
  755. * SortedMap tail = m.tailMap(low+"\0");
  756. * </pre>
  757. *
  758. * @param fromKey low endpoint (inclusive) of the tailMap.
  759. * @return a view of the portion of this map whose keys are greater
  760. * than or equal to <tt>fromKey</tt>.
  761. * @throws ClassCastException if <tt>fromKey</tt> is not compatible
  762. * with this map's comparator (or, if the map has no comparator,
  763. * if <tt>fromKey</tt> does not implement <tt>Comparable</tt>).
  764. * @throws IllegalArgumentException if this map is itself a subMap,
  765. * headMap, or tailMap, and <tt>fromKey</tt> is not within the
  766. * specified range of the subMap, headMap, or tailMap.
  767. * @throws NullPointerException if <tt>fromKey</tt> is <tt>null</tt> and
  768. * this map uses natural order, or its comparator does not
  769. * tolerate <tt>null</tt> keys.
  770. */
  771. public SortedMap<K,V> tailMap(K fromKey) {
  772. return new SubMap(fromKey, false);
  773. }
  774. private class SubMap
  775. extends AbstractMap<K,V>
  776. implements SortedMap<K,V>, java.io.Serializable {
  777. private static final long serialVersionUID = -6520786458950516097L;
  778. /**
  779. * fromKey is significant only if fromStart is false. Similarly,
  780. * toKey is significant only if toStart is false.
  781. */
  782. private boolean fromStart = false, toEnd = false;
  783. private K fromKey, toKey;
  784. SubMap(K fromKey, K toKey) {
  785. if (compare(fromKey, toKey) > 0)
  786. throw new IllegalArgumentException("fromKey > toKey");
  787. this.fromKey = fromKey;
  788. this.toKey = toKey;
  789. }
  790. SubMap(K key, boolean headMap) {
  791. compare(key, key); // Type-check key
  792. if (headMap) {
  793. fromStart = true;
  794. toKey = key;
  795. } else {
  796. toEnd = true;
  797. fromKey = key;
  798. }
  799. }
  800. SubMap(boolean fromStart, K fromKey, boolean toEnd, K toKey) {
  801. this.fromStart = fromStart;
  802. this.fromKey= fromKey;
  803. this.toEnd = toEnd;
  804. this.toKey = toKey;
  805. }
  806. public boolean isEmpty() {
  807. return entrySet.isEmpty();
  808. }
  809. public boolean containsKey(Object key) {
  810. return inRange((K) key) && TreeMap.this.containsKey(key);
  811. }
  812. public V get(Object key) {
  813. if (!inRange((K) key))
  814. return null;
  815. return TreeMap.this.get(key);
  816. }
  817. public V put(K key, V value) {
  818. if (!inRange(key))
  819. throw new IllegalArgumentException("key out of range");
  820. return TreeMap.this.put(key, value);
  821. }
  822. public Comparator<? super K> comparator() {
  823. return comparator;
  824. }
  825. public K firstKey() {
  826. TreeMap.Entry<K,V> e = fromStart ? firstEntry() : getCeilEntry(fromKey);
  827. K first = key(e);
  828. if (!toEnd && compare(first, toKey) >= 0)
  829. throw(new NoSuchElementException());
  830. return first;
  831. }
  832. public K lastKey() {
  833. TreeMap.Entry<K,V> e = toEnd ? lastEntry() : getPrecedingEntry(toKey);
  834. K last = key(e);
  835. if (!fromStart && compare(last, fromKey) < 0)
  836. throw(new NoSuchElementException());
  837. return last;
  838. }
  839. private transient Set<Map.Entry<K,V>> entrySet = new EntrySetView();
  840. public Set<Map.Entry<K,V>> entrySet() {
  841. return entrySet;
  842. }
  843. private class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
  844. private transient int size = -1, sizeModCount;
  845. public int size() {
  846. if (size == -1 || sizeModCount != TreeMap.this.modCount) {
  847. size = 0; sizeModCount = TreeMap.this.modCount;
  848. Iterator i = iterator();
  849. while (i.hasNext()) {
  850. size++;
  851. i.next();
  852. }
  853. }
  854. return size;
  855. }
  856. public boolean isEmpty() {
  857. return !iterator().hasNext();
  858. }
  859. public boolean contains(Object o) {
  860. if (!(o instanceof Map.Entry))
  861. return false;
  862. Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
  863. K key = entry.getKey();
  864. if (!inRange(key))
  865. return false;
  866. TreeMap.Entry node = getEntry(key);
  867. return node != null &&
  868. valEquals(node.getValue(), entry.getValue());
  869. }
  870. public boolean remove(Object o) {
  871. if (!(o instanceof Map.Entry))
  872. return false;
  873. Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
  874. K key = entry.getKey();
  875. if (!inRange(key))
  876. return false;
  877. TreeMap.Entry<K,V> node = getEntry(key);
  878. if (node!=null && valEquals(node.getValue(),entry.getValue())){
  879. deleteEntry(node);
  880. return true;
  881. }
  882. return false;
  883. }
  884. public Iterator<Map.Entry<K,V>> iterator() {
  885. return new SubMapEntryIterator(
  886. (fromStart ? firstEntry() : getCeilEntry(fromKey)),
  887. (toEnd ? null : getCeilEntry(toKey)));
  888. }
  889. }
  890. public SortedMap<K,V> subMap(K fromKey, K toKey) {
  891. if (!inRange2(fromKey))
  892. throw new IllegalArgumentException("fromKey out of range");
  893. if (!inRange2(toKey))
  894. throw new IllegalArgumentException("toKey out of range");
  895. return new SubMap(fromKey, toKey);
  896. }
  897. public SortedMap<K,V> headMap(K toKey) {
  898. if (!inRange2(toKey))
  899. throw new IllegalArgumentException("toKey out of range");
  900. return new SubMap(fromStart, fromKey, false, toKey);
  901. }
  902. public SortedMap<K,V> tailMap(K fromKey) {
  903. if (!inRange2(fromKey))
  904. throw new IllegalArgumentException("fromKey out of range");
  905. return new SubMap(false, fromKey, toEnd, toKey);
  906. }
  907. private boolean inRange(K key) {
  908. return (fromStart || compare(key, fromKey) >= 0) &&
  909. (toEnd || compare(key, toKey) < 0);
  910. }
  911. // This form allows the high endpoint (as well as all legit keys)
  912. private boolean inRange2(K key) {
  913. return (fromStart || compare(key, fromKey) >= 0) &&
  914. (toEnd || compare(key, toKey) <= 0);
  915. }
  916. }
  917. /**
  918. * TreeMap Iterator.
  919. */
  920. private abstract class PrivateEntryIterator<T> implements Iterator<T> {
  921. private int expectedModCount = TreeMap.this.modCount;
  922. private Entry<K,V> lastReturned = null;
  923. Entry<K,V> next;
  924. PrivateEntryIterator() {
  925. next = firstEntry();
  926. }
  927. // Used by SubMapEntryIterator
  928. PrivateEntryIterator(Entry<K,V> first) {
  929. next = first;
  930. }
  931. public boolean hasNext() {
  932. return next != null;
  933. }
  934. final Entry<K,V> nextEntry() {
  935. if (next == null)
  936. throw new NoSuchElementException();
  937. if (modCount != expectedModCount)
  938. throw new ConcurrentModificationException();
  939. lastReturned = next;
  940. next = successor(next);
  941. return lastReturned;
  942. }
  943. public void remove() {
  944. if (lastReturned == null)
  945. throw new IllegalStateException();
  946. if (modCount != expectedModCount)
  947. throw new ConcurrentModificationException();
  948. if (lastReturned.left != null && lastReturned.right != null)
  949. next = lastReturned;
  950. deleteEntry(lastReturned);
  951. expectedModCount++;
  952. lastReturned = null;
  953. }
  954. }
  955. private class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
  956. public Map.Entry<K,V> next() {
  957. return nextEntry();
  958. }
  959. }
  960. private class KeyIterator extends PrivateEntryIterator<K> {
  961. public K next() {
  962. return nextEntry().key;
  963. }
  964. }
  965. private class ValueIterator extends PrivateEntryIterator<V> {
  966. public V next() {
  967. return nextEntry().value;
  968. }
  969. }
  970. private class SubMapEntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
  971. private final K firstExcludedKey;
  972. SubMapEntryIterator(Entry<K,V> first, Entry<K,V> firstExcluded) {
  973. super(first);
  974. firstExcludedKey = (firstExcluded == null
  975. ? null
  976. : firstExcluded.key);
  977. }
  978. public boolean hasNext() {
  979. return next != null && next.key != firstExcludedKey;
  980. }
  981. public Map.Entry<K,V> next() {
  982. if (next == null || next.key == firstExcludedKey)
  983. throw new NoSuchElementException();
  984. return nextEntry();
  985. }
  986. }
  987. /**
  988. * Compares two keys using the correct comparison method for this TreeMap.
  989. */
  990. private int compare(K k1, K k2) {
  991. return (comparator==null ? ((Comparable</*-*/K>)k1).compareTo(k2)
  992. : comparator.compare((K)k1, (K)k2));
  993. }
  994. /**
  995. * Test two values for equality. Differs from o1.equals(o2) only in
  996. * that it copes with <tt>null</tt> o1 properly.
  997. */
  998. private static boolean valEquals(Object o1, Object o2) {
  999. return (o1==null ? o2==null : o1.equals(o2));
  1000. }
  1001. private static final boolean RED = false;
  1002. private static final boolean BLACK = true;
  1003. /**
  1004. * Node in the Tree. Doubles as a means to pass key-value pairs back to
  1005. * user (see Map.Entry).
  1006. */
  1007. static class Entry<K,V> implements Map.Entry<K,V> {
  1008. K key;
  1009. V value;
  1010. Entry<K,V> left = null;
  1011. Entry<K,V> right = null;
  1012. Entry<K,V> parent;
  1013. boolean color = BLACK;
  1014. /**
  1015. * Make a new cell with given key, value, and parent, and with
  1016. * <tt>null</tt> child links, and BLACK color.
  1017. */
  1018. Entry(K key, V value, Entry<K,V> parent) {
  1019. this.key = key;
  1020. this.value = value;
  1021. this.parent = parent;
  1022. }
  1023. /**
  1024. * Returns the key.
  1025. *
  1026. * @return the key.
  1027. */
  1028. public K getKey() {
  1029. return key;
  1030. }
  1031. /**
  1032. * Returns the value associated with the key.
  1033. *
  1034. * @return the value associated with the key.
  1035. */
  1036. public V getValue() {
  1037. return value;
  1038. }
  1039. /**
  1040. * Replaces the value currently associated with the key with the given
  1041. * value.
  1042. *
  1043. * @return the value associated with the key before this method was
  1044. * called.
  1045. */
  1046. public V setValue(V value) {
  1047. V oldValue = this.value;
  1048. this.value = value;
  1049. return oldValue;
  1050. }
  1051. public boolean equals(Object o) {
  1052. if (!(o instanceof Map.Entry))
  1053. return false;
  1054. Map.Entry e = (Map.Entry)o;
  1055. return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
  1056. }
  1057. public int hashCode() {
  1058. int keyHash = (key==null ? 0 : key.hashCode());
  1059. int valueHash = (value==null ? 0 : value.hashCode());
  1060. return keyHash ^ valueHash;
  1061. }
  1062. public String toString() {
  1063. return key + "=" + value;
  1064. }
  1065. }
  1066. /**
  1067. * Returns the first Entry in the TreeMap (according to the TreeMap's
  1068. * key-sort function). Returns null if the TreeMap is empty.
  1069. */
  1070. private Entry<K,V> firstEntry() {
  1071. Entry<K,V> p = root;
  1072. if (p != null)
  1073. while (p.left != null)
  1074. p = p.left;
  1075. return p;
  1076. }
  1077. /**
  1078. * Returns the last Entry in the TreeMap (according to the TreeMap's
  1079. * key-sort function). Returns null if the TreeMap is empty.
  1080. */
  1081. private Entry<K,V> lastEntry() {
  1082. Entry<K,V> p = root;
  1083. if (p != null)
  1084. while (p.right != null)
  1085. p = p.right;
  1086. return p;
  1087. }
  1088. /**
  1089. * Returns the successor of the specified Entry, or null if no such.
  1090. */
  1091. private Entry<K,V> successor(Entry<K,V> t) {
  1092. if (t == null)
  1093. return null;
  1094. else if (t.right != null) {
  1095. Entry<K,V> p = t.right;
  1096. while (p.left != null)
  1097. p = p.left;
  1098. return p;
  1099. } else {
  1100. Entry<K,V> p = t.parent;
  1101. Entry<K,V> ch = t;
  1102. while (p != null && ch == p.right) {
  1103. ch = p;
  1104. p = p.parent;
  1105. }
  1106. return p;
  1107. }
  1108. }
  1109. /**
  1110. * Balancing operations.
  1111. *
  1112. * Implementations of rebalancings during insertion and deletion are
  1113. * slightly different than the CLR version. Rather than using dummy
  1114. * nilnodes, we use a set of accessors that deal properly with null. They
  1115. * are used to avoid messiness surrounding nullness checks in the main
  1116. * algorithms.
  1117. */
  1118. private static <K,V> boolean colorOf(Entry<K,V> p) {
  1119. return (p == null ? BLACK : p.color);
  1120. }
  1121. private static <K,V> Entry<K,V> parentOf(Entry<K,V> p) {
  1122. return (p == null ? null: p.parent);
  1123. }
  1124. private static <K,V> void setColor(Entry<K,V> p, boolean c) {
  1125. if (p != null)
  1126. p.color = c;
  1127. }
  1128. private static <K,V> Entry<K,V> leftOf(Entry<K,V> p) {
  1129. return (p == null) ? null: p.left;
  1130. }
  1131. private static <K,V> Entry<K,V> rightOf(Entry<K,V> p) {
  1132. return (p == null) ? null: p.right;
  1133. }
  1134. /** From CLR **/
  1135. private void rotateLeft(Entry<K,V> p) {
  1136. Entry<K,V> r = p.right;
  1137. p.right = r.left;
  1138. if (r.left != null)
  1139. r.left.parent = p;
  1140. r.parent = p.parent;
  1141. if (p.parent == null)
  1142. root = r;
  1143. else if (p.parent.left == p)
  1144. p.parent.left = r;
  1145. else
  1146. p.parent.right = r;
  1147. r.left = p;
  1148. p.parent = r;
  1149. }
  1150. /** From CLR **/
  1151. private void rotateRight(Entry<K,V> p) {
  1152. Entry<K,V> l = p.left;
  1153. p.left = l.right;
  1154. if (l.right != null) l.right.parent = p;
  1155. l.parent = p.parent;
  1156. if (p.parent == null)
  1157. root = l;
  1158. else if (p.parent.right == p)
  1159. p.parent.right = l;
  1160. else p.parent.left = l;
  1161. l.right = p;
  1162. p.parent = l;
  1163. }
  1164. /** From CLR **/
  1165. private void fixAfterInsertion(Entry<K,V> x) {
  1166. x.color = RED;
  1167. while (x != null && x != root && x.parent.color == RED) {
  1168. if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
  1169. Entry<K,V> y = rightOf(parentOf(parentOf(x)));
  1170. if (colorOf(y) == RED) {
  1171. setColor(parentOf(x), BLACK);
  1172. setColor(y, BLACK);
  1173. setColor(parentOf(parentOf(x)), RED);
  1174. x = parentOf(parentOf(x));
  1175. } else {
  1176. if (x == rightOf(parentOf(x))) {
  1177. x = parentOf(x);
  1178. rotateLeft(x);
  1179. }
  1180. setColor(parentOf(x), BLACK);
  1181. setColor(parentOf(parentOf(x)), RED);
  1182. if (parentOf(parentOf(x)) != null)
  1183. rotateRight(parentOf(parentOf(x)));
  1184. }
  1185. } else {
  1186. Entry<K,V> y = leftOf(parentOf(parentOf(x)));
  1187. if (colorOf(y) == RED) {
  1188. setColor(parentOf(x), BLACK);
  1189. setColor(y, BLACK);
  1190. setColor(parentOf(parentOf(x)), RED);
  1191. x = parentOf(parentOf(x));
  1192. } else {
  1193. if (x == leftOf(parentOf(x))) {
  1194. x = parentOf(x);
  1195. rotateRight(x);
  1196. }
  1197. setColor(parentOf(x), BLACK);
  1198. setColor(parentOf(parentOf(x)), RED);
  1199. if (parentOf(parentOf(x)) != null)
  1200. rotateLeft(parentOf(parentOf(x)));
  1201. }
  1202. }
  1203. }
  1204. root.color = BLACK;
  1205. }
  1206. /**
  1207. * Delete node p, and then rebalance the tree.
  1208. */
  1209. private void deleteEntry(Entry<K,V> p) {
  1210. decrementSize();
  1211. // If strictly internal, copy successor's element to p and then make p
  1212. // point to successor.
  1213. if (p.left != null && p.right != null) {
  1214. Entry<K,V> s = successor (p);
  1215. p.key = s.key;
  1216. p.value = s.value;
  1217. p = s;
  1218. } // p has 2 children
  1219. // Start fixup at replacement node, if it exists.
  1220. Entry<K,V> replacement = (p.left != null ? p.left : p.right);
  1221. if (replacement != null) {
  1222. // Link replacement to parent
  1223. replacement.parent = p.parent;
  1224. if (p.parent == null)
  1225. root = replacement;
  1226. else if (p == p.parent.left)
  1227. p.parent.left = replacement;
  1228. else
  1229. p.parent.right = replacement;
  1230. // Null out links so they are OK to use by fixAfterDeletion.
  1231. p.left = p.right = p.parent = null;
  1232. // Fix replacement
  1233. if (p.color == BLACK)
  1234. fixAfterDeletion(replacement);
  1235. } else if (p.parent == null) { // return if we are the only node.
  1236. root = null;
  1237. } else { // No children. Use self as phantom replacement and unlink.
  1238. if (p.color == BLACK)
  1239. fixAfterDeletion(p);
  1240. if (p.parent != null) {
  1241. if (p == p.parent.left)
  1242. p.parent.left = null;
  1243. else if (p == p.parent.right)
  1244. p.parent.right = null;
  1245. p.parent = null;
  1246. }
  1247. }
  1248. }
  1249. /** From CLR **/
  1250. private void fixAfterDeletion(Entry<K,V> x) {
  1251. while (x != root && colorOf(x) == BLACK) {
  1252. if (x == leftOf(parentOf(x))) {
  1253. Entry<K,V> sib = rightOf(parentOf(x));
  1254. if (colorOf(sib) == RED) {
  1255. setColor(sib, BLACK);
  1256. setColor(parentOf(x), RED);
  1257. rotateLeft(parentOf(x));
  1258. sib = rightOf(parentOf(x));
  1259. }
  1260. if (colorOf(leftOf(sib)) == BLACK &&
  1261. colorOf(rightOf(sib)) == BLACK) {
  1262. setColor(sib, RED);
  1263. x = parentOf(x);
  1264. } else {
  1265. if (colorOf(rightOf(sib)) == BLACK) {
  1266. setColor(leftOf(sib), BLACK);
  1267. setColor(sib, RED);
  1268. rotateRight(sib);
  1269. sib = rightOf(parentOf(x));
  1270. }
  1271. setColor(sib, colorOf(parentOf(x)));
  1272. setColor(parentOf(x), BLACK);
  1273. setColor(rightOf(sib), BLACK);
  1274. rotateLeft(parentOf(x));
  1275. x = root;
  1276. }
  1277. } else { // symmetric
  1278. Entry<K,V> sib = leftOf(parentOf(x));
  1279. if (colorOf(sib) == RED) {
  1280. setColor(sib, BLACK);
  1281. setColor(parentOf(x), RED);
  1282. rotateRight(parentOf(x));
  1283. sib = leftOf(parentOf(x));
  1284. }
  1285. if (colorOf(rightOf(sib)) == BLACK &&
  1286. colorOf(leftOf(sib)) == BLACK) {
  1287. setColor(sib, RED);
  1288. x = parentOf(x);
  1289. } else {
  1290. if (colorOf(leftOf(sib)) == BLACK) {
  1291. setColor(rightOf(sib), BLACK);
  1292. setColor(sib, RED);
  1293. rotateLeft(sib);
  1294. sib = leftOf(parentOf(x));
  1295. }
  1296. setColor(sib, colorOf(parentOf(x)));
  1297. setColor(parentOf(x), BLACK);
  1298. setColor(leftOf(sib), BLACK);
  1299. rotateRight(parentOf(x));
  1300. x = root;
  1301. }
  1302. }
  1303. }
  1304. setColor(x, BLACK);
  1305. }
  1306. private static final long serialVersionUID = 919286545866124006L;
  1307. /**
  1308. * Save the state of the <tt>TreeMap</tt> instance to a stream (i.e.,
  1309. * serialize it).
  1310. *
  1311. * @serialData The <i>size</i> of the TreeMap (the number of key-value
  1312. * mappings) is emitted (int), followed by the key (Object)
  1313. * and value (Object) for each key-value mapping represented
  1314. * by the TreeMap. The key-value mappings are emitted in
  1315. * key-order (as determined by the TreeMap's Comparator,
  1316. * or by the keys' natural ordering if the TreeMap has no
  1317. * Comparator).
  1318. */
  1319. private void writeObject(java.io.ObjectOutputStream s)
  1320. throws java.io.IOException {
  1321. // Write out the Comparator and any hidden stuff
  1322. s.defaultWriteObject();
  1323. // Write out size (number of Mappings)
  1324. s.writeInt(size);
  1325. // Write out keys and values (alternating)
  1326. for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) {
  1327. Map.Entry<K,V> e = i.next();
  1328. s.writeObject(e.getKey());
  1329. s.writeObject(e.getValue());
  1330. }
  1331. }
  1332. /**
  1333. * Reconstitute the <tt>TreeMap</tt> instance from a stream (i.e.,
  1334. * deserialize it).
  1335. */
  1336. private void readObject(final java.io.ObjectInputStream s)
  1337. throws java.io.IOException, ClassNotFoundException {
  1338. // Read in the Comparator and any hidden stuff
  1339. s.defaultReadObject();
  1340. // Read in size
  1341. int size = s.readInt();
  1342. buildFromSorted(size, null, s, null);
  1343. }
  1344. /** Intended to be called only from TreeSet.readObject **/
  1345. void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
  1346. throws java.io.IOException, ClassNotFoundException {
  1347. buildFromSorted(size, null, s, defaultVal);
  1348. }
  1349. /** Intended to be called only from TreeSet.addAll **/
  1350. void addAllForTreeSet(SortedSet<Map.Entry<K,V>> set, V defaultVal) {
  1351. try {
  1352. buildFromSorted(set.size(), set.iterator(), null, defaultVal);
  1353. } catch (java.io.IOException cannotHappen) {
  1354. } catch (ClassNotFoundException cannotHappen) {
  1355. }
  1356. }
  1357. /**
  1358. * Linear time tree building algorithm from sorted data. Can accept keys
  1359. * and/or values from iterator or stream. This leads to too many
  1360. * parameters, but seems better than alternatives. The four formats
  1361. * that this method accepts are:
  1362. *
  1363. * 1) An iterator of Map.Entries. (it != null, defaultVal == null).
  1364. * 2) An iterator of keys. (it != null, defaultVal != null).
  1365. * 3) A stream of alternating serialized keys and values.
  1366. * (it == null, defaultVal == null).
  1367. * 4) A stream of serialized keys. (it == null, defaultVal != null).
  1368. *
  1369. * It is assumed that the comparator of the TreeMap is already set prior
  1370. * to calling this method.
  1371. *
  1372. * @param size the number of keys (or key-value pairs) to be read from
  1373. * the iterator or stream.
  1374. * @param it If non-null, new entries are created from entries
  1375. * or keys read from this iterator.
  1376. * @param str If non-null, new entries are created from keys and
  1377. * possibly values read from this stream in serialized form.
  1378. * Exactly one of it and str should be non-null.
  1379. * @param defaultVal if non-null, this default value is used for
  1380. * each value in the map. If null, each value is read from
  1381. * iterator or stream, as described above.
  1382. * @throws IOException propagated from stream reads. This cannot
  1383. * occur if str is null.
  1384. * @throws ClassNotFoundException propagated from readObject.
  1385. * This cannot occur if str is null.
  1386. */
  1387. private
  1388. void buildFromSorted(int size, Iterator it,
  1389. java.io.ObjectInputStream str,
  1390. V defaultVal)
  1391. throws java.io.IOException, ClassNotFoundException {
  1392. this.size = size;
  1393. root =
  1394. buildFromSorted(0, 0, size-1, computeRedLevel(size),
  1395. it, str, defaultVal);
  1396. }
  1397. /**
  1398. * Recursive "helper method" that does the real work of the
  1399. * of the previous method. Identically named parameters have
  1400. * identical definitions. Additional parameters are documented below.
  1401. * It is assumed that the comparator and size fields of the TreeMap are
  1402. * already set prior to calling this method. (It ignores both fields.)
  1403. *
  1404. * @param level the current level of tree. Initial call should be 0.
  1405. * @param lo the first element index of this subtree. Initial should be 0.
  1406. * @param hi the last element index of this subtree. Initial should be
  1407. * size-1.
  1408. * @param redLevel the level at which nodes should be red.
  1409. * Must be equal to computeRedLevel for tree of this size.
  1410. */
  1411. private final Entry<K,V> buildFromSorted(int level, int lo, int hi,
  1412. int redLevel,
  1413. Iterator it,
  1414. java.io.ObjectInputStream str,
  1415. V defaultVal)
  1416. throws java.io.IOException, ClassNotFoundException {
  1417. /*
  1418. * Strategy: The root is the middlemost element. To get to it, we
  1419. * have to first recursively construct the entire left subtree,
  1420. * so as to grab all of its elements. We can then proceed with right
  1421. * subtree.
  1422. *
  1423. * The lo and hi arguments are the minimum and maximum
  1424. * indices to pull out of the iterator or stream for current subtree.
  1425. * They are not actually indexed, we just proceed sequentially,
  1426. * ensuring that items are extracted in corresponding order.
  1427. */
  1428. if (hi < lo) return null;
  1429. int mid = (lo + hi) / 2;
  1430. Entry<K,V> left = null;
  1431. if (lo < mid)
  1432. left = buildFromSorted(level+1, lo, mid - 1, redLevel,
  1433. it, str, defaultVal);
  1434. // extract key and/or value from iterator or stream
  1435. K key;
  1436. V value;
  1437. if (it != null) {
  1438. if (defaultVal==null) {
  1439. Map.Entry<K,V> entry = (Map.Entry<K,V>)it.next();
  1440. key = entry.getKey();
  1441. value = entry.getValue();
  1442. } else {
  1443. key = (K)it.next();
  1444. value = defaultVal;
  1445. }
  1446. } else { // use stream
  1447. key = (K) str.readObject();
  1448. value = (defaultVal != null ? defaultVal : (V) str.readObject());
  1449. }
  1450. Entry<K,V> middle = new Entry<K,V>(key, value, null);
  1451. // color nodes in non-full bottommost level red
  1452. if (level == redLevel)
  1453. middle.color = RED;
  1454. if (left != null) {
  1455. middle.left = left;
  1456. left.parent = middle;
  1457. }
  1458. if (mid < hi) {
  1459. Entry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel,
  1460. it, str, defaultVal);
  1461. middle.right = right;
  1462. right.parent = middle;
  1463. }
  1464. return middle;
  1465. }
  1466. /**
  1467. * Find the level down to which to assign all nodes BLACK. This is the
  1468. * last `full' level of the complete binary tree produced by
  1469. * buildTree. The remaining nodes are colored RED. (This makes a `nice'
  1470. * set of color assignments wrt future insertions.) This level number is
  1471. * computed by finding the number of splits needed to reach the zeroeth
  1472. * node. (The answer is ~lg(N), but in any case must be computed by same
  1473. * quick O(lg(N)) loop.)
  1474. */
  1475. private static int computeRedLevel(int sz) {
  1476. int level = 0;
  1477. for (int m = sz - 1; m >= 0; m = m / 2 - 1)
  1478. level++;
  1479. return level;
  1480. }
  1481. }