PageRenderTime 61ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/gcc-4.2.1/libjava/classpath/java/util/TreeMap.java

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

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