PageRenderTime 29ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/branches/ot3/external/gridsim/trunk/source/gridsim/parallel/profile/LinkedTreeMap.java

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