PageRenderTime 54ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/hack/pypy-hack/jvm/test_classes/TreeMap.java

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