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

/libjava/classpath/java/util/TreeMap.java

https://bitbucket.org/vaporoid/gcc
Java | 3322 lines | 1936 code | 365 blank | 1021 comment | 284 complexity | 4614b8d64f5e1f7e44f6e69797259dfb MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, LGPL-2.0, GPL-2.0, LGPL-2.1, AGPL-1.0

Large files files are truncated, but you can click here to view the full file

  1. /* TreeMap.java -- a class providing a basic Red-Black Tree data structure,
  2. mapping Object --> Object
  3. Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006 Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.util;
  33. import gnu.java.lang.CPStringBuilder;
  34. import java.io.IOException;
  35. import java.io.ObjectInputStream;
  36. import java.io.ObjectOutputStream;
  37. import java.io.Serializable;
  38. /**
  39. * This class provides a red-black tree implementation of the SortedMap
  40. * interface. Elements in the Map will be sorted by either a user-provided
  41. * Comparator object, or by the natural ordering of the keys.
  42. *
  43. * The algorithms are adopted from Corman, Leiserson, and Rivest's
  44. * <i>Introduction to Algorithms.</i> TreeMap guarantees O(log n)
  45. * insertion and deletion of elements. That being said, there is a large
  46. * enough constant coefficient in front of that "log n" (overhead involved
  47. * in keeping the tree balanced), that TreeMap may not be the best choice
  48. * for small collections. If something is already sorted, you may want to
  49. * just use a LinkedHashMap to maintain the order while providing O(1) access.
  50. *
  51. * TreeMap is a part of the JDK1.2 Collections API. Null keys are allowed
  52. * only if a Comparator is used which can deal with them; natural ordering
  53. * cannot cope with null. Null values are always allowed. Note that the
  54. * ordering must be <i>consistent with equals</i> to correctly implement
  55. * the Map interface. If this condition is violated, the map is still
  56. * well-behaved, but you may have suprising results when comparing it to
  57. * other maps.<p>
  58. *
  59. * This implementation is not synchronized. If you need to share this between
  60. * multiple threads, do something like:<br>
  61. * <code>SortedMap m
  62. * = Collections.synchronizedSortedMap(new TreeMap(...));</code><p>
  63. *
  64. * The iterators are <i>fail-fast</i>, meaning that any structural
  65. * modification, except for <code>remove()</code> called on the iterator
  66. * itself, cause the iterator to throw a
  67. * <code>ConcurrentModificationException</code> rather than exhibit
  68. * non-deterministic behavior.
  69. *
  70. * @author Jon Zeppieri
  71. * @author Bryce McKinlay
  72. * @author Eric Blake (ebb9@email.byu.edu)
  73. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  74. * @see Map
  75. * @see HashMap
  76. * @see Hashtable
  77. * @see LinkedHashMap
  78. * @see Comparable
  79. * @see Comparator
  80. * @see Collection
  81. * @see Collections#synchronizedSortedMap(SortedMap)
  82. * @since 1.2
  83. * @status updated to 1.6
  84. */
  85. public class TreeMap<K, V> extends AbstractMap<K, V>
  86. implements NavigableMap<K, V>, Cloneable, Serializable
  87. {
  88. // Implementation note:
  89. // A red-black tree is a binary search tree with the additional properties
  90. // that all paths to a leaf node visit the same number of black nodes,
  91. // and no red node has red children. To avoid some null-pointer checks,
  92. // we use the special node nil which is always black, has no relatives,
  93. // and has key and value of null (but is not equal to a mapping of null).
  94. /**
  95. * Compatible with JDK 1.2.
  96. */
  97. private static final long serialVersionUID = 919286545866124006L;
  98. /**
  99. * Color status of a node. Package visible for use by nested classes.
  100. */
  101. static final int RED = -1,
  102. BLACK = 1;
  103. /**
  104. * Sentinal node, used to avoid null checks for corner cases and make the
  105. * delete rebalance code simpler. The rebalance code must never assign
  106. * the parent, left, or right of nil, but may safely reassign the color
  107. * to be black. This object must never be used as a key in a TreeMap, or
  108. * it will break bounds checking of a SubMap.
  109. */
  110. static final Node nil = new Node(null, null, BLACK);
  111. static
  112. {
  113. // Nil is self-referential, so we must initialize it after creation.
  114. nil.parent = nil;
  115. nil.left = nil;
  116. nil.right = nil;
  117. }
  118. /**
  119. * The root node of this TreeMap.
  120. */
  121. private transient Node root;
  122. /**
  123. * The size of this TreeMap. Package visible for use by nested classes.
  124. */
  125. transient int size;
  126. /**
  127. * The cache for {@link #entrySet()}.
  128. */
  129. private transient Set<Map.Entry<K,V>> entries;
  130. /**
  131. * The cache for {@link #descendingMap()}.
  132. */
  133. private transient NavigableMap<K,V> descendingMap;
  134. /**
  135. * The cache for {@link #navigableKeySet()}.
  136. */
  137. private transient NavigableSet<K> nKeys;
  138. /**
  139. * Counts the number of modifications this TreeMap has undergone, used
  140. * by Iterators to know when to throw ConcurrentModificationExceptions.
  141. * Package visible for use by nested classes.
  142. */
  143. transient int modCount;
  144. /**
  145. * This TreeMap's comparator, or null for natural ordering.
  146. * Package visible for use by nested classes.
  147. * @serial the comparator ordering this tree, or null
  148. */
  149. final Comparator<? super K> comparator;
  150. /**
  151. * Class to represent an entry in the tree. Holds a single key-value pair,
  152. * plus pointers to parent and child nodes.
  153. *
  154. * @author Eric Blake (ebb9@email.byu.edu)
  155. */
  156. private static final class Node<K, V> extends AbstractMap.SimpleEntry<K, V>
  157. {
  158. // All fields package visible for use by nested classes.
  159. /** The color of this node. */
  160. int color;
  161. /** The left child node. */
  162. Node<K, V> left = nil;
  163. /** The right child node. */
  164. Node<K, V> right = nil;
  165. /** The parent node. */
  166. Node<K, V> parent = nil;
  167. /**
  168. * Simple constructor.
  169. * @param key the key
  170. * @param value the value
  171. */
  172. Node(K key, V value, int color)
  173. {
  174. super(key, value);
  175. this.color = color;
  176. }
  177. }
  178. /**
  179. * Instantiate a new TreeMap with no elements, using the keys' natural
  180. * ordering to sort. All entries in the map must have a key which implements
  181. * Comparable, and which are <i>mutually comparable</i>, otherwise map
  182. * operations may throw a {@link ClassCastException}. Attempts to use
  183. * a null key will throw a {@link NullPointerException}.
  184. *
  185. * @see Comparable
  186. */
  187. public TreeMap()
  188. {
  189. this((Comparator) null);
  190. }
  191. /**
  192. * Instantiate a new TreeMap with no elements, using the provided comparator
  193. * to sort. All entries in the map must have keys which are mutually
  194. * comparable by the Comparator, otherwise map operations may throw a
  195. * {@link ClassCastException}.
  196. *
  197. * @param c the sort order for the keys of this map, or null
  198. * for the natural order
  199. */
  200. public TreeMap(Comparator<? super K> c)
  201. {
  202. comparator = c;
  203. fabricateTree(0);
  204. }
  205. /**
  206. * Instantiate a new TreeMap, initializing it with all of the elements in
  207. * the provided Map. The elements will be sorted using the natural
  208. * ordering of the keys. This algorithm runs in n*log(n) time. All entries
  209. * in the map must have keys which implement Comparable and are mutually
  210. * comparable, otherwise map operations may throw a
  211. * {@link ClassCastException}.
  212. *
  213. * @param map a Map, whose entries will be put into this TreeMap
  214. * @throws ClassCastException if the keys in the provided Map are not
  215. * comparable
  216. * @throws NullPointerException if map is null
  217. * @see Comparable
  218. */
  219. public TreeMap(Map<? extends K, ? extends V> map)
  220. {
  221. this((Comparator) null);
  222. putAll(map);
  223. }
  224. /**
  225. * Instantiate a new TreeMap, initializing it with all of the elements in
  226. * the provided SortedMap. The elements will be sorted using the same
  227. * comparator as in the provided SortedMap. This runs in linear time.
  228. *
  229. * @param sm a SortedMap, whose entries will be put into this TreeMap
  230. * @throws NullPointerException if sm is null
  231. */
  232. public TreeMap(SortedMap<K, ? extends V> sm)
  233. {
  234. this(sm.comparator());
  235. int pos = sm.size();
  236. Iterator itr = sm.entrySet().iterator();
  237. fabricateTree(pos);
  238. Node node = firstNode();
  239. while (--pos >= 0)
  240. {
  241. Map.Entry me = (Map.Entry) itr.next();
  242. node.key = me.getKey();
  243. node.value = me.getValue();
  244. node = successor(node);
  245. }
  246. }
  247. /**
  248. * Clears the Map so it has no keys. This is O(1).
  249. */
  250. public void clear()
  251. {
  252. if (size > 0)
  253. {
  254. modCount++;
  255. root = nil;
  256. size = 0;
  257. }
  258. }
  259. /**
  260. * Returns a shallow clone of this TreeMap. The Map itself is cloned,
  261. * but its contents are not.
  262. *
  263. * @return the clone
  264. */
  265. public Object clone()
  266. {
  267. TreeMap copy = null;
  268. try
  269. {
  270. copy = (TreeMap) super.clone();
  271. }
  272. catch (CloneNotSupportedException x)
  273. {
  274. }
  275. copy.entries = null;
  276. copy.fabricateTree(size);
  277. Node node = firstNode();
  278. Node cnode = copy.firstNode();
  279. while (node != nil)
  280. {
  281. cnode.key = node.key;
  282. cnode.value = node.value;
  283. node = successor(node);
  284. cnode = copy.successor(cnode);
  285. }
  286. return copy;
  287. }
  288. /**
  289. * Return the comparator used to sort this map, or null if it is by
  290. * natural order.
  291. *
  292. * @return the map's comparator
  293. */
  294. public Comparator<? super K> comparator()
  295. {
  296. return comparator;
  297. }
  298. /**
  299. * Returns true if the map contains a mapping for the given key.
  300. *
  301. * @param key the key to look for
  302. * @return true if the key has a mapping
  303. * @throws ClassCastException if key is not comparable to map elements
  304. * @throws NullPointerException if key is null and the comparator is not
  305. * tolerant of nulls
  306. */
  307. public boolean containsKey(Object key)
  308. {
  309. return getNode((K) key) != nil;
  310. }
  311. /**
  312. * Returns true if the map contains at least one mapping to the given value.
  313. * This requires linear time.
  314. *
  315. * @param value the value to look for
  316. * @return true if the value appears in a mapping
  317. */
  318. public boolean containsValue(Object value)
  319. {
  320. Node node = firstNode();
  321. while (node != nil)
  322. {
  323. if (equals(value, node.value))
  324. return true;
  325. node = successor(node);
  326. }
  327. return false;
  328. }
  329. /**
  330. * Returns a "set view" of this TreeMap's entries. The set is backed by
  331. * the TreeMap, so changes in one show up in the other. The set supports
  332. * element removal, but not element addition.<p>
  333. *
  334. * Note that the iterators for all three views, from keySet(), entrySet(),
  335. * and values(), traverse the TreeMap in sorted sequence.
  336. *
  337. * @return a set view of the entries
  338. * @see #keySet()
  339. * @see #values()
  340. * @see Map.Entry
  341. */
  342. public Set<Map.Entry<K,V>> entrySet()
  343. {
  344. if (entries == null)
  345. // Create an AbstractSet with custom implementations of those methods
  346. // that can be overriden easily and efficiently.
  347. entries = new NavigableEntrySet();
  348. return entries;
  349. }
  350. /**
  351. * Returns the first (lowest) key in the map.
  352. *
  353. * @return the first key
  354. * @throws NoSuchElementException if the map is empty
  355. */
  356. public K firstKey()
  357. {
  358. if (root == nil)
  359. throw new NoSuchElementException();
  360. return firstNode().key;
  361. }
  362. /**
  363. * Return the value in this TreeMap associated with the supplied key,
  364. * or <code>null</code> if the key maps to nothing. NOTE: Since the value
  365. * could also be null, you must use containsKey to see if this key
  366. * actually maps to something.
  367. *
  368. * @param key the key for which to fetch an associated value
  369. * @return what the key maps to, if present
  370. * @throws ClassCastException if key is not comparable to elements in the map
  371. * @throws NullPointerException if key is null but the comparator does not
  372. * tolerate nulls
  373. * @see #put(Object, Object)
  374. * @see #containsKey(Object)
  375. */
  376. public V get(Object key)
  377. {
  378. // Exploit fact that nil.value == null.
  379. return getNode((K) key).value;
  380. }
  381. /**
  382. * Returns a view of this Map including all entries with keys less than
  383. * <code>toKey</code>. The returned map is backed by the original, so changes
  384. * in one appear in the other. The submap will throw an
  385. * {@link IllegalArgumentException} for any attempt to access or add an
  386. * element beyond the specified cutoff. The returned map does not include
  387. * the endpoint; if you want inclusion, pass the successor element
  388. * or call <code>headMap(toKey, true)</code>. This is equivalent to
  389. * calling <code>headMap(toKey, false)</code>.
  390. *
  391. * @param toKey the (exclusive) cutoff point
  392. * @return a view of the map less than the cutoff
  393. * @throws ClassCastException if <code>toKey</code> is not compatible with
  394. * the comparator (or is not Comparable, for natural ordering)
  395. * @throws NullPointerException if toKey is null, but the comparator does not
  396. * tolerate null elements
  397. */
  398. public SortedMap<K, V> headMap(K toKey)
  399. {
  400. return headMap(toKey, false);
  401. }
  402. /**
  403. * Returns a view of this Map including all entries with keys less than
  404. * (or equal to, if <code>inclusive</code> is true) <code>toKey</code>.
  405. * The returned map is backed by the original, so changes in one appear
  406. * in the other. The submap will throw an {@link IllegalArgumentException}
  407. * for any attempt to access or add an element beyond the specified cutoff.
  408. *
  409. * @param toKey the cutoff point
  410. * @param inclusive true if the cutoff point should be included.
  411. * @return a view of the map less than (or equal to, if <code>inclusive</code>
  412. * is true) the cutoff.
  413. * @throws ClassCastException if <code>toKey</code> is not compatible with
  414. * the comparator (or is not Comparable, for natural ordering)
  415. * @throws NullPointerException if toKey is null, but the comparator does not
  416. * tolerate null elements
  417. */
  418. public NavigableMap<K, V> headMap(K toKey, boolean inclusive)
  419. {
  420. return new SubMap((K)(Object)nil, inclusive
  421. ? successor(getNode(toKey)).key : toKey);
  422. }
  423. /**
  424. * Returns a "set view" of this TreeMap's keys. The set is backed by the
  425. * TreeMap, so changes in one show up in the other. The set supports
  426. * element removal, but not element addition.
  427. *
  428. * @return a set view of the keys
  429. * @see #values()
  430. * @see #entrySet()
  431. */
  432. public Set<K> keySet()
  433. {
  434. if (keys == null)
  435. // Create an AbstractSet with custom implementations of those methods
  436. // that can be overriden easily and efficiently.
  437. keys = new KeySet();
  438. return keys;
  439. }
  440. /**
  441. * Returns the last (highest) key in the map.
  442. *
  443. * @return the last key
  444. * @throws NoSuchElementException if the map is empty
  445. */
  446. public K lastKey()
  447. {
  448. if (root == nil)
  449. throw new NoSuchElementException("empty");
  450. return lastNode().key;
  451. }
  452. /**
  453. * Puts the supplied value into the Map, mapped by the supplied key.
  454. * The value may be retrieved by any object which <code>equals()</code>
  455. * this key. NOTE: Since the prior value could also be null, you must
  456. * first use containsKey if you want to see if you are replacing the
  457. * key's mapping.
  458. *
  459. * @param key the key used to locate the value
  460. * @param value the value to be stored in the Map
  461. * @return the prior mapping of the key, or null if there was none
  462. * @throws ClassCastException if key is not comparable to current map keys
  463. * @throws NullPointerException if key is null, but the comparator does
  464. * not tolerate nulls
  465. * @see #get(Object)
  466. * @see Object#equals(Object)
  467. */
  468. public V put(K key, V value)
  469. {
  470. Node<K,V> current = root;
  471. Node<K,V> parent = nil;
  472. int comparison = 0;
  473. // Find new node's parent.
  474. while (current != nil)
  475. {
  476. parent = current;
  477. comparison = compare(key, current.key);
  478. if (comparison > 0)
  479. current = current.right;
  480. else if (comparison < 0)
  481. current = current.left;
  482. else // Key already in tree.
  483. return current.setValue(value);
  484. }
  485. // Set up new node.
  486. Node n = new Node(key, value, RED);
  487. n.parent = parent;
  488. // Insert node in tree.
  489. modCount++;
  490. size++;
  491. if (parent == nil)
  492. {
  493. // Special case inserting into an empty tree.
  494. root = n;
  495. return null;
  496. }
  497. if (comparison > 0)
  498. parent.right = n;
  499. else
  500. parent.left = n;
  501. // Rebalance after insert.
  502. insertFixup(n);
  503. return null;
  504. }
  505. /**
  506. * Copies all elements of the given map into this TreeMap. If this map
  507. * already has a mapping for a key, the new mapping replaces the current
  508. * one.
  509. *
  510. * @param m the map to be added
  511. * @throws ClassCastException if a key in m is not comparable with keys
  512. * in the map
  513. * @throws NullPointerException if a key in m is null, and the comparator
  514. * does not tolerate nulls
  515. */
  516. public void putAll(Map<? extends K, ? extends V> m)
  517. {
  518. Iterator itr = m.entrySet().iterator();
  519. int pos = m.size();
  520. while (--pos >= 0)
  521. {
  522. Map.Entry<K,V> e = (Map.Entry<K,V>) itr.next();
  523. put(e.getKey(), e.getValue());
  524. }
  525. }
  526. /**
  527. * Removes from the TreeMap and returns the value which is mapped by the
  528. * supplied key. If the key maps to nothing, then the TreeMap remains
  529. * unchanged, and <code>null</code> is returned. NOTE: Since the value
  530. * could also be null, you must use containsKey to see if you are
  531. * actually removing a mapping.
  532. *
  533. * @param key the key used to locate the value to remove
  534. * @return whatever the key mapped to, if present
  535. * @throws ClassCastException if key is not comparable to current map keys
  536. * @throws NullPointerException if key is null, but the comparator does
  537. * not tolerate nulls
  538. */
  539. public V remove(Object key)
  540. {
  541. Node<K, V> n = getNode((K)key);
  542. if (n == nil)
  543. return null;
  544. // Note: removeNode can alter the contents of n, so save value now.
  545. V result = n.value;
  546. removeNode(n);
  547. return result;
  548. }
  549. /**
  550. * Returns the number of key-value mappings currently in this Map.
  551. *
  552. * @return the size
  553. */
  554. public int size()
  555. {
  556. return size;
  557. }
  558. /**
  559. * Returns a view of this Map including all entries with keys greater or
  560. * equal to <code>fromKey</code> and less than <code>toKey</code> (a
  561. * half-open interval). The returned map is backed by the original, so
  562. * changes in one appear in the other. The submap will throw an
  563. * {@link IllegalArgumentException} for any attempt to access or add an
  564. * element beyond the specified cutoffs. The returned map includes the low
  565. * endpoint but not the high; if you want to reverse this behavior on
  566. * either end, pass in the successor element or call
  567. * {@link #subMap(K,boolean,K,boolean)}. This call is equivalent to
  568. * <code>subMap(fromKey, true, toKey, false)</code>.
  569. *
  570. * @param fromKey the (inclusive) low cutoff point
  571. * @param toKey the (exclusive) high cutoff point
  572. * @return a view of the map between the cutoffs
  573. * @throws ClassCastException if either cutoff is not compatible with
  574. * the comparator (or is not Comparable, for natural ordering)
  575. * @throws NullPointerException if fromKey or toKey is null, but the
  576. * comparator does not tolerate null elements
  577. * @throws IllegalArgumentException if fromKey is greater than toKey
  578. */
  579. public SortedMap<K, V> subMap(K fromKey, K toKey)
  580. {
  581. return subMap(fromKey, true, toKey, false);
  582. }
  583. /**
  584. * Returns a view of this Map including all entries with keys greater (or
  585. * equal to, if <code>fromInclusive</code> is true) <code>fromKey</code> and
  586. * less than (or equal to, if <code>toInclusive</code> is true)
  587. * <code>toKey</code>. The returned map is backed by the original, so
  588. * changes in one appear in the other. The submap will throw an
  589. * {@link IllegalArgumentException} for any attempt to access or add an
  590. * element beyond the specified cutoffs.
  591. *
  592. * @param fromKey the low cutoff point
  593. * @param fromInclusive true if the low cutoff point should be included.
  594. * @param toKey the high cutoff point
  595. * @param toInclusive true if the high cutoff point should be included.
  596. * @return a view of the map for the specified range.
  597. * @throws ClassCastException if either cutoff is not compatible with
  598. * the comparator (or is not Comparable, for natural ordering)
  599. * @throws NullPointerException if fromKey or toKey is null, but the
  600. * comparator does not tolerate null elements
  601. * @throws IllegalArgumentException if fromKey is greater than toKey
  602. */
  603. public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive,
  604. K toKey, boolean toInclusive)
  605. {
  606. return new SubMap(fromInclusive ? fromKey : successor(getNode(fromKey)).key,
  607. toInclusive ? successor(getNode(toKey)).key : toKey);
  608. }
  609. /**
  610. * Returns a view of this Map including all entries with keys greater or
  611. * equal to <code>fromKey</code>. The returned map is backed by the
  612. * original, so changes in one appear in the other. The submap will throw an
  613. * {@link IllegalArgumentException} for any attempt to access or add an
  614. * element beyond the specified cutoff. The returned map includes the
  615. * endpoint; if you want to exclude it, pass in the successor element.
  616. * This is equivalent to calling <code>tailMap(fromKey, true)</code>.
  617. *
  618. * @param fromKey the (inclusive) low cutoff point
  619. * @return a view of the map above the cutoff
  620. * @throws ClassCastException if <code>fromKey</code> is not compatible with
  621. * the comparator (or is not Comparable, for natural ordering)
  622. * @throws NullPointerException if fromKey is null, but the comparator
  623. * does not tolerate null elements
  624. */
  625. public SortedMap<K, V> tailMap(K fromKey)
  626. {
  627. return tailMap(fromKey, true);
  628. }
  629. /**
  630. * Returns a view of this Map including all entries with keys greater or
  631. * equal to <code>fromKey</code>. The returned map is backed by the
  632. * original, so changes in one appear in the other. The submap will throw an
  633. * {@link IllegalArgumentException} for any attempt to access or add an
  634. * element beyond the specified cutoff. The returned map includes the
  635. * endpoint; if you want to exclude it, pass in the successor element.
  636. *
  637. * @param fromKey the low cutoff point
  638. * @param inclusive true if the cutoff point should be included.
  639. * @return a view of the map above the cutoff
  640. * @throws ClassCastException if <code>fromKey</code> is not compatible with
  641. * the comparator (or is not Comparable, for natural ordering)
  642. * @throws NullPointerException if fromKey is null, but the comparator
  643. * does not tolerate null elements
  644. */
  645. public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive)
  646. {
  647. return new SubMap(inclusive ? fromKey : successor(getNode(fromKey)).key,
  648. (K)(Object)nil);
  649. }
  650. /**
  651. * Returns a "collection view" (or "bag view") of this TreeMap's values.
  652. * The collection is backed by the TreeMap, so changes in one show up
  653. * in the other. The collection supports element removal, but not element
  654. * addition.
  655. *
  656. * @return a bag view of the values
  657. * @see #keySet()
  658. * @see #entrySet()
  659. */
  660. public Collection<V> values()
  661. {
  662. if (values == null)
  663. // We don't bother overriding many of the optional methods, as doing so
  664. // wouldn't provide any significant performance advantage.
  665. values = new AbstractCollection<V>()
  666. {
  667. public int size()
  668. {
  669. return size;
  670. }
  671. public Iterator<V> iterator()
  672. {
  673. return new TreeIterator(VALUES);
  674. }
  675. public void clear()
  676. {
  677. TreeMap.this.clear();
  678. }
  679. };
  680. return values;
  681. }
  682. /**
  683. * Compares two elements by the set comparator, or by natural ordering.
  684. * Package visible for use by nested classes.
  685. *
  686. * @param o1 the first object
  687. * @param o2 the second object
  688. * @throws ClassCastException if o1 and o2 are not mutually comparable,
  689. * or are not Comparable with natural ordering
  690. * @throws NullPointerException if o1 or o2 is null with natural ordering
  691. */
  692. final int compare(K o1, K o2)
  693. {
  694. return (comparator == null
  695. ? ((Comparable) o1).compareTo(o2)
  696. : comparator.compare(o1, o2));
  697. }
  698. /**
  699. * Maintain red-black balance after deleting a node.
  700. *
  701. * @param node the child of the node just deleted, possibly nil
  702. * @param parent the parent of the node just deleted, never nil
  703. */
  704. private void deleteFixup(Node<K,V> node, Node<K,V> parent)
  705. {
  706. // if (parent == nil)
  707. // throw new InternalError();
  708. // If a black node has been removed, we need to rebalance to avoid
  709. // violating the "same number of black nodes on any path" rule. If
  710. // node is red, we can simply recolor it black and all is well.
  711. while (node != root && node.color == BLACK)
  712. {
  713. if (node == parent.left)
  714. {
  715. // Rebalance left side.
  716. Node<K,V> sibling = parent.right;
  717. // if (sibling == nil)
  718. // throw new InternalError();
  719. if (sibling.color == RED)
  720. {
  721. // Case 1: Sibling is red.
  722. // Recolor sibling and parent, and rotate parent left.
  723. sibling.color = BLACK;
  724. parent.color = RED;
  725. rotateLeft(parent);
  726. sibling = parent.right;
  727. }
  728. if (sibling.left.color == BLACK && sibling.right.color == BLACK)
  729. {
  730. // Case 2: Sibling has no red children.
  731. // Recolor sibling, and move to parent.
  732. sibling.color = RED;
  733. node = parent;
  734. parent = parent.parent;
  735. }
  736. else
  737. {
  738. if (sibling.right.color == BLACK)
  739. {
  740. // Case 3: Sibling has red left child.
  741. // Recolor sibling and left child, rotate sibling right.
  742. sibling.left.color = BLACK;
  743. sibling.color = RED;
  744. rotateRight(sibling);
  745. sibling = parent.right;
  746. }
  747. // Case 4: Sibling has red right child. Recolor sibling,
  748. // right child, and parent, and rotate parent left.
  749. sibling.color = parent.color;
  750. parent.color = BLACK;
  751. sibling.right.color = BLACK;
  752. rotateLeft(parent);
  753. node = root; // Finished.
  754. }
  755. }
  756. else
  757. {
  758. // Symmetric "mirror" of left-side case.
  759. Node<K,V> sibling = parent.left;
  760. // if (sibling == nil)
  761. // throw new InternalError();
  762. if (sibling.color == RED)
  763. {
  764. // Case 1: Sibling is red.
  765. // Recolor sibling and parent, and rotate parent right.
  766. sibling.color = BLACK;
  767. parent.color = RED;
  768. rotateRight(parent);
  769. sibling = parent.left;
  770. }
  771. if (sibling.right.color == BLACK && sibling.left.color == BLACK)
  772. {
  773. // Case 2: Sibling has no red children.
  774. // Recolor sibling, and move to parent.
  775. sibling.color = RED;
  776. node = parent;
  777. parent = parent.parent;
  778. }
  779. else
  780. {
  781. if (sibling.left.color == BLACK)
  782. {
  783. // Case 3: Sibling has red right child.
  784. // Recolor sibling and right child, rotate sibling left.
  785. sibling.right.color = BLACK;
  786. sibling.color = RED;
  787. rotateLeft(sibling);
  788. sibling = parent.left;
  789. }
  790. // Case 4: Sibling has red left child. Recolor sibling,
  791. // left child, and parent, and rotate parent right.
  792. sibling.color = parent.color;
  793. parent.color = BLACK;
  794. sibling.left.color = BLACK;
  795. rotateRight(parent);
  796. node = root; // Finished.
  797. }
  798. }
  799. }
  800. node.color = BLACK;
  801. }
  802. /**
  803. * Construct a perfectly balanced tree consisting of n "blank" nodes. This
  804. * permits a tree to be generated from pre-sorted input in linear time.
  805. *
  806. * @param count the number of blank nodes, non-negative
  807. */
  808. private void fabricateTree(final int count)
  809. {
  810. if (count == 0)
  811. {
  812. root = nil;
  813. size = 0;
  814. return;
  815. }
  816. // We color every row of nodes black, except for the overflow nodes.
  817. // I believe that this is the optimal arrangement. We construct the tree
  818. // in place by temporarily linking each node to the next node in the row,
  819. // then updating those links to the children when working on the next row.
  820. // Make the root node.
  821. root = new Node(null, null, BLACK);
  822. size = count;
  823. Node row = root;
  824. int rowsize;
  825. // Fill each row that is completely full of nodes.
  826. for (rowsize = 2; rowsize + rowsize <= count; rowsize <<= 1)
  827. {
  828. Node parent = row;
  829. Node last = null;
  830. for (int i = 0; i < rowsize; i += 2)
  831. {
  832. Node left = new Node(null, null, BLACK);
  833. Node right = new Node(null, null, BLACK);
  834. left.parent = parent;
  835. left.right = right;
  836. right.parent = parent;
  837. parent.left = left;
  838. Node next = parent.right;
  839. parent.right = right;
  840. parent = next;
  841. if (last != null)
  842. last.right = left;
  843. last = right;
  844. }
  845. row = row.left;
  846. }
  847. // Now do the partial final row in red.
  848. int overflow = count - rowsize;
  849. Node parent = row;
  850. int i;
  851. for (i = 0; i < overflow; i += 2)
  852. {
  853. Node left = new Node(null, null, RED);
  854. Node right = new Node(null, null, RED);
  855. left.parent = parent;
  856. right.parent = parent;
  857. parent.left = left;
  858. Node next = parent.right;
  859. parent.right = right;
  860. parent = next;
  861. }
  862. // Add a lone left node if necessary.
  863. if (i - overflow == 0)
  864. {
  865. Node left = new Node(null, null, RED);
  866. left.parent = parent;
  867. parent.left = left;
  868. parent = parent.right;
  869. left.parent.right = nil;
  870. }
  871. // Unlink the remaining nodes of the previous row.
  872. while (parent != nil)
  873. {
  874. Node next = parent.right;
  875. parent.right = nil;
  876. parent = next;
  877. }
  878. }
  879. /**
  880. * Returns the first sorted node in the map, or nil if empty. Package
  881. * visible for use by nested classes.
  882. *
  883. * @return the first node
  884. */
  885. final Node<K, V> firstNode()
  886. {
  887. // Exploit fact that nil.left == nil.
  888. Node node = root;
  889. while (node.left != nil)
  890. node = node.left;
  891. return node;
  892. }
  893. /**
  894. * Return the TreeMap.Node associated with key, or the nil node if no such
  895. * node exists in the tree. Package visible for use by nested classes.
  896. *
  897. * @param key the key to search for
  898. * @return the node where the key is found, or nil
  899. */
  900. final Node<K, V> getNode(K key)
  901. {
  902. Node<K,V> current = root;
  903. while (current != nil)
  904. {
  905. int comparison = compare(key, current.key);
  906. if (comparison > 0)
  907. current = current.right;
  908. else if (comparison < 0)
  909. current = current.left;
  910. else
  911. return current;
  912. }
  913. return current;
  914. }
  915. /**
  916. * Find the "highest" node which is &lt; key. If key is nil, return last
  917. * node. Package visible for use by nested classes.
  918. *
  919. * @param key the upper bound, exclusive
  920. * @return the previous node
  921. */
  922. final Node<K,V> highestLessThan(K key)
  923. {
  924. return highestLessThan(key, false);
  925. }
  926. /**
  927. * Find the "highest" node which is &lt; (or equal to,
  928. * if <code>equal</code> is true) key. If key is nil,
  929. * return last node. Package visible for use by nested
  930. * classes.
  931. *
  932. * @param key the upper bound, exclusive
  933. * @param equal true if the key should be returned if found.
  934. * @return the previous node
  935. */
  936. final Node<K,V> highestLessThan(K key, boolean equal)
  937. {
  938. if (key == nil)
  939. return lastNode();
  940. Node<K,V> last = nil;
  941. Node<K,V> current = root;
  942. int comparison = 0;
  943. while (current != nil)
  944. {
  945. last = current;
  946. comparison = compare(key, current.key);
  947. if (comparison > 0)
  948. current = current.right;
  949. else if (comparison < 0)
  950. current = current.left;
  951. else // Exact match.
  952. return (equal ? last : predecessor(last));
  953. }
  954. return comparison < 0 ? predecessor(last) : last;
  955. }
  956. /**
  957. * Maintain red-black balance after inserting a new node.
  958. *
  959. * @param n the newly inserted node
  960. */
  961. private void insertFixup(Node<K,V> n)
  962. {
  963. // Only need to rebalance when parent is a RED node, and while at least
  964. // 2 levels deep into the tree (ie: node has a grandparent). Remember
  965. // that nil.color == BLACK.
  966. while (n.parent.color == RED && n.parent.parent != nil)
  967. {
  968. if (n.parent == n.parent.parent.left)
  969. {
  970. Node uncle = n.parent.parent.right;
  971. // Uncle may be nil, in which case it is BLACK.
  972. if (uncle.color == RED)
  973. {
  974. // Case 1. Uncle is RED: Change colors of parent, uncle,
  975. // and grandparent, and move n to grandparent.
  976. n.parent.color = BLACK;
  977. uncle.color = BLACK;
  978. uncle.parent.color = RED;
  979. n = uncle.parent;
  980. }
  981. else
  982. {
  983. if (n == n.parent.right)
  984. {
  985. // Case 2. Uncle is BLACK and x is right child.
  986. // Move n to parent, and rotate n left.
  987. n = n.parent;
  988. rotateLeft(n);
  989. }
  990. // Case 3. Uncle is BLACK and x is left child.
  991. // Recolor parent, grandparent, and rotate grandparent right.
  992. n.parent.color = BLACK;
  993. n.parent.parent.color = RED;
  994. rotateRight(n.parent.parent);
  995. }
  996. }
  997. else
  998. {
  999. // Mirror image of above code.
  1000. Node uncle = n.parent.parent.left;
  1001. // Uncle may be nil, in which case it is BLACK.
  1002. if (uncle.color == RED)
  1003. {
  1004. // Case 1. Uncle is RED: Change colors of parent, uncle,
  1005. // and grandparent, and move n to grandparent.
  1006. n.parent.color = BLACK;
  1007. uncle.color = BLACK;
  1008. uncle.parent.color = RED;
  1009. n = uncle.parent;
  1010. }
  1011. else
  1012. {
  1013. if (n == n.parent.left)
  1014. {
  1015. // Case 2. Uncle is BLACK and x is left child.
  1016. // Move n to parent, and rotate n right.
  1017. n = n.parent;
  1018. rotateRight(n);
  1019. }
  1020. // Case 3. Uncle is BLACK and x is right child.
  1021. // Recolor parent, grandparent, and rotate grandparent left.
  1022. n.parent.color = BLACK;
  1023. n.parent.parent.color = RED;
  1024. rotateLeft(n.parent.parent);
  1025. }
  1026. }
  1027. }
  1028. root.color = BLACK;
  1029. }
  1030. /**
  1031. * Returns the last sorted node in the map, or nil if empty.
  1032. *
  1033. * @return the last node
  1034. */
  1035. private Node<K,V> lastNode()
  1036. {
  1037. // Exploit fact that nil.right == nil.
  1038. Node node = root;
  1039. while (node.right != nil)
  1040. node = node.right;
  1041. return node;
  1042. }
  1043. /**
  1044. * Find the "lowest" node which is &gt;= key. If key is nil, return either
  1045. * nil or the first node, depending on the parameter first. Package visible
  1046. * for use by nested classes.
  1047. *
  1048. * @param key the lower bound, inclusive
  1049. * @param first true to return the first element instead of nil for nil key
  1050. * @return the next node
  1051. */
  1052. final Node<K,V> lowestGreaterThan(K key, boolean first)
  1053. {
  1054. return lowestGreaterThan(key, first, true);
  1055. }
  1056. /**
  1057. * Find the "lowest" node which is &gt; (or equal to, if <code>equal</code>
  1058. * is true) key. If key is nil, return either nil or the first node, depending
  1059. * on the parameter first. Package visible for use by nested classes.
  1060. *
  1061. * @param key the lower bound, inclusive
  1062. * @param first true to return the first element instead of nil for nil key
  1063. * @param equal true if the key should be returned if found.
  1064. * @return the next node
  1065. */
  1066. final Node<K,V> lowestGreaterThan(K key, boolean first, boolean equal)
  1067. {
  1068. if (key == nil)
  1069. return first ? firstNode() : nil;
  1070. Node<K,V> last = nil;
  1071. Node<K,V> current = root;
  1072. int comparison = 0;
  1073. while (current != nil)
  1074. {
  1075. last = current;
  1076. comparison = compare(key, current.key);
  1077. if (comparison > 0)
  1078. current = current.right;
  1079. else if (comparison < 0)
  1080. current = current.left;
  1081. else
  1082. return (equal ? current : successor(current));
  1083. }
  1084. return comparison > 0 ? successor(last) : last;
  1085. }
  1086. /**
  1087. * Return the node preceding the given one, or nil if there isn't one.
  1088. *
  1089. * @param node the current node, not nil
  1090. * @return the prior node in sorted order
  1091. */
  1092. private Node<K,V> predecessor(Node<K,V> node)
  1093. {
  1094. if (node.left != nil)
  1095. {
  1096. node = node.left;
  1097. while (node.right != nil)
  1098. node = node.right;
  1099. return node;
  1100. }
  1101. Node parent = node.parent;
  1102. // Exploit fact that nil.left == nil and node is non-nil.
  1103. while (node == parent.left)
  1104. {
  1105. node = parent;
  1106. parent = node.parent;
  1107. }
  1108. return parent;
  1109. }
  1110. /**
  1111. * Construct a tree from sorted keys in linear time. Package visible for
  1112. * use by TreeSet.
  1113. *
  1114. * @param s the stream to read from
  1115. * @param count the number of keys to read
  1116. * @param readValues true to read values, false to insert "" as the value
  1117. * @throws ClassNotFoundException if the underlying stream fails
  1118. * @throws IOException if the underlying stream fails
  1119. * @see #readObject(ObjectInputStream)
  1120. * @see TreeSet#readObject(ObjectInputStream)
  1121. */
  1122. final void putFromObjStream(ObjectInputStream s, int count,
  1123. boolean readValues)
  1124. throws IOException, ClassNotFoundException
  1125. {
  1126. fabricateTree(count);
  1127. Node node = firstNode();
  1128. while (--count >= 0)
  1129. {
  1130. node.key = s.readObject();
  1131. node.value = readValues ? s.readObject() : "";
  1132. node = successor(node);
  1133. }
  1134. }
  1135. /**
  1136. * Construct a tree from sorted keys in linear time, with values of "".
  1137. * Package visible for use by TreeSet, which uses a value type of String.
  1138. *
  1139. * @param keys the iterator over the sorted keys
  1140. * @param count the number of nodes to insert
  1141. * @see TreeSet#TreeSet(SortedSet)
  1142. */
  1143. final void putKeysLinear(Iterator<K> keys, int count)
  1144. {
  1145. fabricateTree(count);
  1146. Node<K,V> node = firstNode();
  1147. while (--count >= 0)
  1148. {
  1149. node.key = keys.next();
  1150. node.value = (V) "";
  1151. node = successor(node);
  1152. }
  1153. }
  1154. /**
  1155. * Deserializes this object from the given stream.
  1156. *
  1157. * @param s the stream to read from
  1158. * @throws ClassNotFoundException if the underlying stream fails
  1159. * @throws IOException if the underlying stream fails
  1160. * @serialData the <i>size</i> (int), followed by key (Object) and value
  1161. * (Object) pairs in sorted order
  1162. */
  1163. private void readObject(ObjectInputStream s)
  1164. throws IOException, ClassNotFoundException
  1165. {
  1166. s.defaultReadObject();
  1167. int size = s.readInt();
  1168. putFromObjStream(s, size, true);
  1169. }
  1170. /**
  1171. * Remove node from tree. This will increment modCount and decrement size.
  1172. * Node must exist in the tree. Package visible for use by nested classes.
  1173. *
  1174. * @param node the node to remove
  1175. */
  1176. final void removeNode(Node<K,V> node)
  1177. {
  1178. Node<K,V> splice;
  1179. Node<K,V> child;
  1180. modCount++;
  1181. size--;
  1182. // Find splice, the node at the position to actually remove from the tree.
  1183. if (node.left == nil)
  1184. {
  1185. // Node to be deleted has 0 or 1 children.
  1186. splice = node;
  1187. child = node.right;
  1188. }
  1189. else if (node.right == nil)
  1190. {
  1191. // Node to be deleted has 1 child.
  1192. splice = node;
  1193. child = node.left;
  1194. }
  1195. else
  1196. {
  1197. // Node has 2 children. Splice is node's predecessor, and we swap
  1198. // its contents into node.
  1199. splice = node.left;
  1200. while (splice.right != nil)
  1201. splice = splice.right;
  1202. child = splice.left;
  1203. node.key = splice.key;
  1204. node.value = splice.value;
  1205. }
  1206. // Unlink splice from the tree.
  1207. Node parent = splice.parent;
  1208. if (child != nil)
  1209. child.parent = parent;
  1210. if (parent == nil)
  1211. {
  1212. // Special case for 0 or 1 node remaining.
  1213. root = child;
  1214. return;
  1215. }
  1216. if (splice == parent.left)
  1217. parent.left = child;
  1218. else
  1219. parent.right = child;
  1220. if (splice.color == BLACK)
  1221. deleteFixup(child, parent);
  1222. }
  1223. /**
  1224. * Rotate node n to the left.
  1225. *
  1226. * @param node the node to rotate
  1227. */
  1228. private void rotateLeft(Node<K,V> node)
  1229. {
  1230. Node child = node.right;
  1231. // if (node == nil || child == nil)
  1232. // throw new InternalError();
  1233. // Establish node.right link.
  1234. node.right = child.left;
  1235. if (child.left != nil)
  1236. child.left.parent = node;
  1237. // Establish child->parent link.
  1238. child.parent = node.parent;
  1239. if (node.parent != nil)
  1240. {
  1241. if (node == node.parent.left)
  1242. node.parent.left = child;
  1243. else
  1244. node.parent.right = child;
  1245. }
  1246. else
  1247. root = child;
  1248. // Link n and child.
  1249. child.left = node;
  1250. node.parent = child;
  1251. }
  1252. /**
  1253. * Rotate node n to the right.
  1254. *
  1255. * @param node the node to rotate
  1256. */
  1257. private void rotateRight(Node<K,V> node)
  1258. {
  1259. Node child = node.left;
  1260. // if (node == nil || child == nil)
  1261. // throw new InternalError();
  1262. // Establish node.left link.
  1263. node.left = child.right;
  1264. if (child.right != nil)
  1265. child.right.parent = node;
  1266. // Establish child->parent link.
  1267. child.parent = node.parent;
  1268. if (node.parent != nil)
  1269. {
  1270. if (node == node.parent.right)
  1271. node.parent.right = child;
  1272. else
  1273. node.parent.left = child;
  1274. }
  1275. else
  1276. root = child;
  1277. // Link n and child.
  1278. child.right = node;
  1279. node.parent = child;
  1280. }
  1281. /**
  1282. * Return the node following the given one, or nil if there isn't one.
  1283. * Package visible for use by nested classes.
  1284. *
  1285. * @param node the current node, not nil
  1286. * @return the next node in sorted order
  1287. */
  1288. final Node<K,V> successor(Node<K,V> node)
  1289. {
  1290. if (node.right != nil)
  1291. {
  1292. node = node.right;
  1293. while (node.left != nil)
  1294. node = node.left;
  1295. return node;
  1296. }
  1297. Node<K,V> parent = node.parent;
  1298. // Exploit fact that nil.right == nil and node is non-nil.
  1299. while (node == parent.right)
  1300. {
  1301. node = parent;
  1302. parent = parent.parent;
  1303. }
  1304. return parent;
  1305. }
  1306. /**
  1307. * Serializes this object to the given stream.
  1308. *
  1309. * @param s the stream to write to
  1310. * @throws IOException if the underlying stream fails
  1311. * @serialData the <i>size</i> (int), followed by key (Object) and value
  1312. * (Object) pairs in sorted order
  1313. */
  1314. private void writeObject(ObjectOutputStream s) throws IOException
  1315. {
  1316. s.defaultWriteObject();
  1317. Node node = firstNode();
  1318. s.writeInt(size);
  1319. while (node != nil)
  1320. {
  1321. s.writeObject(node.key);
  1322. s.writeObject(node.value);
  1323. node = successor(node);
  1324. }
  1325. }
  1326. /**
  1327. * Iterate over TreeMap's entries. This implementation is parameterized
  1328. * to give a sequential view of keys, values, or entries.
  1329. *
  1330. * @author Eric Blake (ebb9@email.byu.edu)
  1331. */
  1332. private final class TreeIterator implements Iterator
  1333. {
  1334. /**
  1335. * The type of this Iterator: {@link #KEYS}, {@link #VALUES},
  1336. * or {@link #ENTRIES}.
  1337. */
  1338. private final int type;
  1339. /** The number of modifications to the backing Map that we know about. */
  1340. private int knownMod = modCount;
  1341. /** The last Entry returned by a next() call. */
  1342. private Node last;
  1343. /** The next entry that should be returned by next(). */
  1344. private Node next;
  1345. /**
  1346. * The last node visible to this iterator. This is used when iterating
  1347. * on a SubMap.
  1348. */
  1349. private final Node max;
  1350. /**
  1351. * Construct a new TreeIterator with the supplied type.
  1352. * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
  1353. */
  1354. TreeIterator(int type)
  1355. {
  1356. this(type, firstNode(), nil);
  1357. }
  1358. /**
  1359. * Construct a new TreeIterator with the supplied type. Iteration will
  1360. * be from "first" (inclusive) to "max" (exclusive).
  1361. *
  1362. * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
  1363. * @param first where to start iteration, nil for empty iterator
  1364. * @param max the cutoff for iteration, nil for all remaining nodes
  1365. */
  1366. TreeIterator(int type, Node first, Node max)
  1367. {
  1368. this.type = type;
  1369. this.next = first;
  1370. this.max = max;
  1371. }
  1372. /**
  1373. * Returns true if the Iterator has more elements.
  1374. * @return true if there are more elements
  1375. */
  1376. public boolean hasNext()
  1377. {
  1378. return next != max;
  1379. }
  1380. /**
  1381. * Returns the next element in the Iterator's sequential view.
  1382. * @return the next element
  1383. * @throws ConcurrentModificationException if the TreeMap was modified
  1384. * @throws NoSuchElementException if there is none
  1385. */
  1386. public Object next()
  1387. {
  1388. if (knownMod != modCount)
  1389. throw new ConcurrentModificationException();
  1390. if (next == max)
  1391. throw new NoSuchElementException();
  1392. last = next;
  1393. next = successor(last);
  1394. if (type == VALUES)
  1395. return last.value;
  1396. else if (type == KEYS)
  1397. return last.key;
  1398. return last;
  1399. }
  1400. /**
  1401. * Removes from the backing TreeMap the last element which was fetched
  1402. * with the <code>next()</code> method.
  1403. * @throws ConcurrentModificationException if the TreeMap was modified
  1404. * @throws IllegalStateException if called when there is no last element
  1405. */
  1406. public void remove()
  1407. {
  1408. if (last == null)
  1409. throw new IllegalStateException();
  1410. if (knownMod != modCount)
  1411. throw new ConcurrentModificationException();
  1412. removeNode(last);
  1413. last = null;
  1414. knownMod++;
  1415. }
  1416. } // class TreeIterator
  1417. /**
  1418. * Implementation of {@link #subMap(Object, Object)} and other map
  1419. * ranges. This class provides a view of a portion of the original backing
  1420. * map, and throws {@link IllegalArgumentException} for attempts to
  1421. * access beyond that range.
  1422. *
  1423. * @author Eric Blake (ebb9@email.byu.edu)
  1424. */
  1425. private final class SubMap
  1426. extends AbstractMap<K,V>
  1427. implements NavigableMap<K,V>
  1428. {
  1429. /**
  1430. * The lower range of this view, inclusive, or nil for unbounded.
  1431. * Package visible for use by nested classes.
  1432. */
  1433. final K minKey;
  1434. /**
  1435. * The upper range of this view, exclusive, or nil for unbounded.
  1436. * Package visible for use by nested classes.
  1437. */
  1438. final K maxKey;
  1439. /**
  1440. * The cache for {@link #entrySet()}.
  1441. */
  1442. private Set<Map.Entry<K,V>> entries;
  1443. /**
  1444. * The cache for {@link #descendingMap()}.
  1445. */
  1446. private NavigableMap<K,V> descendingMap;
  1447. /**
  1448. * The cache for {@link #navigableKeySet()}.
  1449. */
  1450. private NavigableSet<K> nKeys;
  1451. /**
  1452. * Create a SubMap representing the elements between minKey (inclusive)
  1453. * and maxKey (exclusive). If minKey is nil, SubMap has no lower bound
  1454. * (headMap). If maxKey is nil, the SubMap has no upper bound (tailMap).
  1455. *
  1456. * @param minKey the lower bound
  1457. * @param maxKey the upper bound
  1458. * @throws IllegalArgumentException if minKey &gt; maxKey
  1459. */
  1460. SubMap(K minKey, K maxKey)
  1461. {
  1462. if (minKey != nil && maxKey != nil && compare(minKey, maxKey) > 0)
  1463. throw new IllegalArgumentException("fromKey > toKey");
  1464. this.minKey = minKey;
  1465. this.maxKey = maxKey;
  1466. }

Large files files are truncated, but you can click here to view the full file