PageRenderTime 62ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/Intervals/erco_test/hedc/java/util/TreeMap.java

http://github.com/nikomatsakiseth/eth-intervals-java
Java | 1410 lines | 1028 code | 163 blank | 219 comment | 293 complexity | 44fa02e2dd4ff9cf6b1e2d1ca27f4354 MD5 | raw 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 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., 59 Temple Place, Suite 330, Boston, MA
  16. 02111-1307 USA.
  17. As a special exception, if you link this library with other files to
  18. produce an executable, this library does not by itself cause the
  19. resulting executable to be covered by the GNU General Public License.
  20. This exception does not however invalidate any other reasons why the
  21. executable file might be covered by the GNU General Public License. */
  22. package java.util;
  23. import java.io.Serializable;
  24. import java.io.IOException;
  25. /**
  26. * This class provides a red-black tree implementation of the SortedMap
  27. * interface. Elements in the Map will be sorted by either a user-provided
  28. * Comparator object, or by the natural ordering of the keys.
  29. *
  30. * The algorithms are adopted from Corman, Leiserson,
  31. * and Rivest's <i>Introduction to Algorithms.</i> In other words,
  32. * I cribbed from the same pseudocode as Sun. <em>Any similarity
  33. * between my code and Sun's (if there is any -- I have never looked
  34. * at Sun's) is a result of this fact.</em>
  35. *
  36. * TreeMap guarantees O(log n) insertion and deletion of elements. That
  37. * being said, there is a large enough constant coefficient in front of
  38. * that "log n" (overhead involved in keeping the tree
  39. * balanced), that TreeMap may not be the best choice for small
  40. * collections.
  41. *
  42. * TreeMap is a part of the JDK1.2 Collections API. Null keys are allowed
  43. * only if a Comparator is used which can deal with them. Null values are
  44. * always allowed.
  45. *
  46. * @author Jon Zeppieri
  47. * @author Bryce McKinlay
  48. */
  49. public class TreeMap extends AbstractMap
  50. implements SortedMap, Cloneable, Serializable
  51. {
  52. private static final int RED = -1,
  53. BLACK = 1;
  54. /** Sentinal node, used to avoid null checks for corner cases and make the
  55. delete rebalance code simpler. Note that this must not be static, due
  56. to thread-safety concerns. */
  57. transient Node nil = new Node(null, null);
  58. /** The root node of this TreeMap */
  59. transient Node root = nil;
  60. /** The size of this TreeMap */
  61. transient int size = 0;
  62. /** Number of modifications */
  63. transient int modCount = 0;
  64. /** This TreeMap's comparator, if any. */
  65. Comparator comparator = null;
  66. static final long serialVersionUID = 919286545866124006L;
  67. private static class Node extends BasicMapEntry implements Map.Entry
  68. {
  69. int color;
  70. Node left;
  71. Node right;
  72. Node parent;
  73. Node(Object key, Object value)
  74. {
  75. super(key, value);
  76. this.color = BLACK;
  77. }
  78. }
  79. /**
  80. * Instantiate a new TreeMap with no elements, using the keys'
  81. * natural ordering to sort.
  82. *
  83. * @see java.lang.Comparable
  84. */
  85. public TreeMap()
  86. {
  87. }
  88. /**
  89. * Instantiate a new TreeMap with no elements, using the provided
  90. * comparator to sort.
  91. *
  92. * @param oComparator a Comparator object, used to sort
  93. * the keys of this SortedMap
  94. */
  95. public TreeMap(Comparator c)
  96. {
  97. comparator = c;
  98. }
  99. /**
  100. * Instantiate a new TreeMap, initializing it with all of the
  101. * elements in the provided Map. The elements will be sorted
  102. * using the natural ordering of the keys.
  103. *
  104. * @param map a Map, whose keys will be put into
  105. * this TreeMap
  106. *
  107. * @throws ClassCastException if the keys in the provided
  108. * Map do not implement
  109. * Comparable
  110. *
  111. * @see java.lang.Comparable
  112. */
  113. public TreeMap(Map map)
  114. {
  115. putAll(map);
  116. }
  117. /**
  118. * Instantiate a new TreeMap, initializing it with all of the
  119. * elements in the provided SortedMap. The elements will be sorted
  120. * using the same method as in the provided SortedMap.
  121. */
  122. public TreeMap(SortedMap sm)
  123. {
  124. this(sm.comparator());
  125. int sm_size = sm.size();
  126. Iterator itr = sm.entrySet().iterator();
  127. fabricateTree(sm_size);
  128. Node node = firstNode();
  129. for (int i = 0; i < sm_size; i++)
  130. {
  131. Map.Entry me = (Map.Entry) itr.next();
  132. node.key = me.getKey();
  133. node.value = me.getValue();
  134. node = successor(node);
  135. }
  136. }
  137. public int size()
  138. {
  139. return size;
  140. }
  141. public void clear()
  142. {
  143. modCount++;
  144. root = nil;
  145. // nil node could have a residual parent reference, clear it for GC.
  146. nil.parent = null;
  147. size = 0;
  148. }
  149. public Object clone()
  150. {
  151. TreeMap copy = null;
  152. try
  153. {
  154. copy = (TreeMap) super.clone();
  155. }
  156. catch (CloneNotSupportedException x)
  157. {
  158. }
  159. // Each instance must have a unique sentinal.
  160. copy.nil = new Node(null, null);
  161. copy.fabricateTree(size);
  162. Node node = firstNode();
  163. Node cnode = copy.firstNode();
  164. while (node != nil)
  165. {
  166. cnode.key = node.key;
  167. cnode.value = node.value;
  168. node = successor(node);
  169. cnode = copy.successor(cnode);
  170. }
  171. return copy;
  172. }
  173. public Comparator comparator()
  174. {
  175. return comparator;
  176. }
  177. public boolean containsKey(Object key)
  178. {
  179. return getNode(key) != nil;
  180. }
  181. public boolean containsValue(Object value)
  182. {
  183. Node node = firstNode();
  184. Object currentVal;
  185. while (node != nil)
  186. {
  187. currentVal = node.getValue();
  188. if (value == null ? currentVal == null : value.equals (currentVal))
  189. return true;
  190. node = successor(node);
  191. }
  192. return false;
  193. }
  194. public Set entrySet()
  195. {
  196. // Create an AbstractSet with custom implementations of those methods that
  197. // can be overriden easily and efficiently.
  198. return new AbstractSet()
  199. {
  200. public int size()
  201. {
  202. return size;
  203. }
  204. public Iterator iterator()
  205. {
  206. return new TreeIterator(TreeIterator.ENTRIES);
  207. }
  208. public void clear()
  209. {
  210. TreeMap.this.clear();
  211. }
  212. public boolean contains(Object o)
  213. {
  214. if (!(o instanceof Map.Entry))
  215. return false;
  216. Map.Entry me = (Map.Entry) o;
  217. Node n = getNode(me.getKey());
  218. return (n != nil && me.getValue().equals(n.value));
  219. }
  220. public boolean remove(Object o)
  221. {
  222. if (!(o instanceof Map.Entry))
  223. return false;
  224. Map.Entry me = (Map.Entry) o;
  225. Node n = getNode(me.getKey());
  226. if (n != nil && me.getValue().equals(n.value))
  227. {
  228. removeNode(n);
  229. return true;
  230. }
  231. return false;
  232. }
  233. };
  234. }
  235. public Object firstKey()
  236. {
  237. if (root == nil)
  238. throw new NoSuchElementException("empty");
  239. return firstNode().getKey();
  240. }
  241. private Node firstNode()
  242. {
  243. if (root == nil)
  244. return nil;
  245. Node node = root;
  246. while (node.left != nil)
  247. node = node.left;
  248. return node;
  249. }
  250. public Object lastKey()
  251. {
  252. if (root == nil)
  253. throw new NoSuchElementException("empty");
  254. return lastNode().getKey();
  255. }
  256. private Node lastNode()
  257. {
  258. if (root == nil)
  259. return nil;
  260. Node node = root;
  261. while (node.right != nil)
  262. node = node.right;
  263. return node;
  264. }
  265. public Object get(Object key)
  266. {
  267. return getNode(key).value;
  268. }
  269. /** Return the TreeMap.Node associated with KEY, or the nil node if no such
  270. node exists in the tree. */
  271. private Node getNode(Object key)
  272. {
  273. int comparison;
  274. Node current = root;
  275. while (current != nil)
  276. {
  277. comparison = compare(key, current.key);
  278. if (comparison > 0)
  279. current = current.right;
  280. else if (comparison < 0)
  281. current = current.left;
  282. else
  283. return current;
  284. }
  285. return current;
  286. }
  287. public Set keySet()
  288. {
  289. // Create an AbstractSet with custom implementations of those methods that
  290. // can be overriden easily and efficiently.
  291. return new AbstractSet()
  292. {
  293. public int size()
  294. {
  295. return size;
  296. }
  297. public Iterator iterator()
  298. {
  299. return new TreeIterator(TreeIterator.KEYS);
  300. }
  301. public void clear()
  302. {
  303. TreeMap.this.clear();
  304. }
  305. public boolean contains(Object o)
  306. {
  307. return TreeMap.this.containsKey(o);
  308. }
  309. public boolean remove(Object key)
  310. {
  311. Node n = getNode(key);
  312. if (n == nil)
  313. return false;
  314. TreeMap.this.removeNode(n);
  315. return true;
  316. }
  317. };
  318. }
  319. public Object put(Object key, Object value)
  320. {
  321. modCount++;
  322. Node current = root;
  323. Node parent = nil;
  324. int comparison = 0;
  325. // Find new node's parent.
  326. while (current != nil)
  327. {
  328. parent = current;
  329. comparison = compare(key, current.key);
  330. if (comparison > 0)
  331. current = current.right;
  332. else if (comparison < 0)
  333. current = current.left;
  334. else
  335. {
  336. // Key already in tree.
  337. Object r = current.value;
  338. current.value = value;
  339. return r;
  340. }
  341. }
  342. // Set up new node.
  343. Node n = new Node(key, value);
  344. n.color = RED;
  345. n.parent = parent;
  346. n.left = nil;
  347. n.right = nil;
  348. // Insert node in tree.
  349. size++;
  350. if (parent == nil)
  351. {
  352. // Special case: inserting into an empty tree.
  353. root = n;
  354. n.color = BLACK;
  355. return null;
  356. }
  357. else if (comparison > 0)
  358. parent.right = n;
  359. else
  360. parent.left = n;
  361. // Rebalance after insert.
  362. insertFixup(n);
  363. //verifyTree();
  364. return null;
  365. }
  366. /** Maintain red-black balance after inserting a new node. */
  367. private void insertFixup(Node n)
  368. {
  369. // Only need to rebalance when parent is a RED node, and while at least
  370. // 2 levels deep into the tree (ie: node has a grandparent).
  371. while (n != root && n.parent.parent != nil && n.parent.color == RED)
  372. {
  373. if (n.parent == n.parent.parent.left)
  374. {
  375. Node uncle = n.parent.parent.right;
  376. if (uncle != nil && uncle.color == RED)
  377. {
  378. n.parent.color = BLACK;
  379. uncle.color = BLACK;
  380. n.parent.parent.color = RED;
  381. n = n.parent.parent;
  382. }
  383. else // Uncle is BLACK.
  384. {
  385. if (n == n.parent.right)
  386. {
  387. // Make n a left child.
  388. n = n.parent;
  389. rotateLeft(n);
  390. }
  391. // Recolor and rotate.
  392. n.parent.color = BLACK;
  393. n.parent.parent.color = RED;
  394. rotateRight(n.parent.parent);
  395. }
  396. }
  397. else
  398. {
  399. // Mirror image of above code.
  400. Node uncle = n.parent.parent.left;
  401. if (uncle != nil && uncle.color == RED)
  402. {
  403. n.parent.color = BLACK;
  404. uncle.color = BLACK;
  405. n.parent.parent.color = RED;
  406. n = n.parent.parent;
  407. }
  408. else
  409. {
  410. if (n == n.parent.left)
  411. {
  412. n = n.parent;
  413. rotateRight(n);
  414. }
  415. n.parent.color = BLACK;
  416. n.parent.parent.color = RED;
  417. rotateLeft(n.parent.parent);
  418. }
  419. }
  420. }
  421. root.color = BLACK;
  422. }
  423. public void putAll(Map m)
  424. {
  425. Iterator itr = m.entrySet().iterator();
  426. int msize = m.size();
  427. Map.Entry e;
  428. for (int i = 0; i < msize; i++)
  429. {
  430. e = (Map.Entry) itr.next();
  431. put(e.getKey(), e.getValue());
  432. }
  433. }
  434. public Object remove(Object key)
  435. {
  436. Node n = getNode(key);
  437. if (n != nil)
  438. {
  439. removeNode(n);
  440. return n.value;
  441. }
  442. return null;
  443. }
  444. // Remove node from tree. This will increment modCount and decrement size.
  445. // Node must exist in the tree.
  446. private void removeNode(Node node) // z
  447. {
  448. Node splice; // y
  449. Node child; // x
  450. modCount++;
  451. size--;
  452. // Find splice, the node at the position to actually remove from the tree.
  453. if (node.left == nil || node.right == nil)
  454. {
  455. // Node to be deleted has 0 or 1 children.
  456. splice = node;
  457. if (node.left == nil)
  458. child = node.right;
  459. else
  460. child = node.left;
  461. }
  462. else
  463. {
  464. // Node has 2 children. Splice is node's successor, and will be
  465. // swapped with node since we can't remove node directly.
  466. splice = node.right;
  467. while (splice.left != nil)
  468. splice = splice.left;
  469. child = splice.right;
  470. }
  471. // Unlink splice from the tree.
  472. Node parent = splice.parent;
  473. child.parent = parent;
  474. if (parent != nil)
  475. {
  476. if (splice == parent.left)
  477. parent.left = child;
  478. else
  479. parent.right = child;
  480. }
  481. else
  482. root = child;
  483. // Keep track of splice's color in case it gets changed in the swap.
  484. int spliceColor = splice.color;
  485. /*
  486. if (splice != node)
  487. {
  488. node.key = splice.key;
  489. node.value = splice.value;
  490. }
  491. */
  492. if (splice != node)
  493. {
  494. // Swap SPLICE for NODE. Some implementations optimize here by simply
  495. // swapping the values, but we can't do that: if an iterator was
  496. // referencing a node in its "next" field, and that node got swapped,
  497. // things would get confused.
  498. if (node == root)
  499. {
  500. root = splice;
  501. }
  502. else
  503. {
  504. if (node.parent.left == node)
  505. node.parent.left = splice;
  506. else
  507. node.parent.right = splice;
  508. }
  509. splice.parent = node.parent;
  510. splice.left = node.left;
  511. splice.right = node.right;
  512. splice.left.parent = splice;
  513. splice.right.parent = splice;
  514. splice.color = node.color;
  515. }
  516. if (spliceColor == BLACK)
  517. deleteFixup (child);
  518. //verifyTree();
  519. }
  520. /** Maintain red-black balance after deleting a node. */
  521. private void deleteFixup (Node node)
  522. {
  523. // A black node has been removed, so we need to rebalance to avoid
  524. // violating the "same number of black nodes on any path" rule. If
  525. // node is red, we can simply recolor it black and all is well.
  526. while (node != root && node.color == BLACK)
  527. {
  528. if (node == node.parent.left)
  529. {
  530. // Rebalance left side.
  531. Node sibling = node.parent.right;
  532. if (sibling.color == RED)
  533. {
  534. sibling.color = BLACK;
  535. node.parent.color = RED;
  536. rotateLeft(node.parent);
  537. sibling = node.parent.right;
  538. }
  539. if (sibling.left.color == BLACK && sibling.right.color == BLACK)
  540. {
  541. // Case 2: Sibling has no red children.
  542. sibling.color = RED;
  543. // Black height has been decreased, so move up the tree and
  544. // repeat.
  545. node = node.parent;
  546. }
  547. else
  548. {
  549. if (sibling.right.color == BLACK)
  550. {
  551. // Case 3: Sibling has red left child.
  552. sibling.left.color = BLACK;
  553. sibling.color = RED;
  554. rotateRight(sibling);
  555. sibling = node.parent.right;
  556. }
  557. // Case 4: Sibling has red right child.
  558. sibling.color = sibling.parent.color;
  559. sibling.parent.color = BLACK;
  560. sibling.right.color = BLACK;
  561. rotateLeft(node.parent);
  562. node = root; // Finished.
  563. }
  564. }
  565. else
  566. {
  567. // Symmetric "mirror" of left-side case.
  568. Node sibling = node.parent.left;
  569. if (sibling.color == RED)
  570. {
  571. sibling.color = BLACK;
  572. node.parent.color = RED;
  573. rotateRight(node.parent);
  574. sibling = node.parent.left;
  575. }
  576. if (sibling.left.color == BLACK && sibling.right.color == BLACK)
  577. {
  578. sibling.color = RED;
  579. node = node.parent;
  580. }
  581. else
  582. {
  583. if (sibling.left.color == BLACK)
  584. {
  585. sibling.right.color = BLACK;
  586. sibling.color = RED;
  587. rotateLeft(sibling);
  588. sibling = node.parent.left;
  589. }
  590. sibling.color = sibling.parent.color;
  591. sibling.parent.color = BLACK;
  592. sibling.left.color = BLACK;
  593. rotateRight(node.parent);
  594. node = root;
  595. }
  596. }
  597. }
  598. node.color = BLACK;
  599. }
  600. public SortedMap subMap(Object fromKey, Object toKey)
  601. {
  602. if (compare(fromKey, toKey) <= 0)
  603. return new SubMap(fromKey, toKey);
  604. else
  605. throw new IllegalArgumentException("fromKey > toKey");
  606. }
  607. public SortedMap headMap(Object toKey)
  608. {
  609. return new SubMap(nil, toKey);
  610. }
  611. public SortedMap tailMap(Object fromKey)
  612. {
  613. return new SubMap(fromKey, nil);
  614. }
  615. /** Returns a "collection view" (or "bag view") of this TreeMap's values. */
  616. public Collection values()
  617. {
  618. // We don't bother overriding many of the optional methods, as doing so
  619. // wouldn't provide any significant performance advantage.
  620. return new AbstractCollection()
  621. {
  622. public int size()
  623. {
  624. return size;
  625. }
  626. public Iterator iterator()
  627. {
  628. return new TreeIterator(TreeIterator.VALUES);
  629. }
  630. public void clear()
  631. {
  632. TreeMap.this.clear();
  633. }
  634. };
  635. }
  636. // Find the "highest" node which is < key. If key is nil, return last node.
  637. // Note that highestLessThan is exclusive (it won't return a key which is
  638. // equal to "key"), while lowestGreaterThan is inclusive, in order to be
  639. // consistent with the semantics of subMap().
  640. private Node highestLessThan(Object key)
  641. {
  642. if (key == nil)
  643. return lastNode();
  644. Node last = nil;
  645. Node current = root;
  646. int comparison = 0;
  647. while (current != nil)
  648. {
  649. last = current;
  650. comparison = compare(key, current.key);
  651. if (comparison > 0)
  652. current = current.right;
  653. else if (comparison < 0)
  654. current = current.left;
  655. else /* Exact match. */
  656. return predecessor(last);
  657. }
  658. if (comparison <= 0)
  659. return predecessor(last);
  660. else
  661. return last;
  662. }
  663. // Find the "lowest" node which is >= key. If key is nil, return first node.
  664. private Node lowestGreaterThan(Object key)
  665. {
  666. if (key == nil)
  667. return firstNode();
  668. Node last = nil;
  669. Node current = root;
  670. int comparison = 0;
  671. while (current != nil)
  672. {
  673. last = current;
  674. comparison = compare(key, current.key);
  675. if (comparison > 0)
  676. current = current.right;
  677. else if (comparison < 0)
  678. current = current.left;
  679. else
  680. return current;
  681. }
  682. if (comparison > 0)
  683. return successor(last);
  684. else
  685. return last;
  686. }
  687. private int compare(Object o1, Object o2)
  688. {
  689. if (comparator == null)
  690. return ((Comparable) o1).compareTo(o2);
  691. else
  692. return comparator.compare(o1, o2);
  693. }
  694. /* Return the node following Node, or nil if there isn't one. */
  695. private Node successor(Node node)
  696. {
  697. if (node.right != nil)
  698. {
  699. node = node.right;
  700. while (node.left != nil)
  701. node = node.left;
  702. return node;
  703. }
  704. Node parent = node.parent;
  705. while (parent != nil && node == parent.right)
  706. {
  707. node = parent;
  708. parent = parent.parent;
  709. }
  710. return parent;
  711. }
  712. /* Return the node preceeding Node, or nil if there isn't one. */
  713. private Node predecessor(Node node)
  714. {
  715. if (node.left != nil)
  716. {
  717. node = node.left;
  718. while (node.right != nil)
  719. node = node.right;
  720. return node;
  721. }
  722. Node parent = node.parent;
  723. while (parent != nil && node == parent.left)
  724. {
  725. node = parent;
  726. parent = parent.parent;
  727. }
  728. return parent;
  729. }
  730. /** Rotate node n to the left. */
  731. private void rotateLeft(Node node)
  732. {
  733. Node child = node.right;
  734. // Establish node.right link.
  735. node.right = child.left;
  736. if (child.left != nil)
  737. child.left.parent = node;
  738. // Establish child->parent link.
  739. child.parent = node.parent;
  740. if (node.parent != nil)
  741. {
  742. if (node == node.parent.left)
  743. node.parent.left = child;
  744. else
  745. node.parent.right = child;
  746. }
  747. else
  748. root = child;
  749. // Link n and child.
  750. child.left = node;
  751. if (node != nil)
  752. node.parent = child;
  753. }
  754. /** Rotate node n to the right. */
  755. private void rotateRight(Node node)
  756. {
  757. Node child = node.left;
  758. // Establish node.left link.
  759. node.left = child.right;
  760. if (child.right != nil)
  761. child.right.parent = node;
  762. // Establish child->parent link.
  763. child.parent = node.parent;
  764. if (node.parent != nil)
  765. {
  766. if (node == node.parent.right)
  767. node.parent.right = child;
  768. else
  769. node.parent.left = child;
  770. }
  771. else
  772. root = child;
  773. // Link n and child.
  774. child.right = node;
  775. if (node != nil)
  776. node.parent = child;
  777. }
  778. /* Construct a tree from sorted keys in linear time. This is used to
  779. implement TreeSet's SortedSet constructor. */
  780. void putKeysLinear(Iterator keys, int count)
  781. {
  782. fabricateTree(count);
  783. Node node = firstNode();
  784. for (int i = 0; i < count; i++)
  785. {
  786. node.key = keys.next();
  787. node.value = Boolean.TRUE;
  788. node = successor(node);
  789. }
  790. }
  791. /* Construct a perfectly balanced tree consisting of n "blank" nodes.
  792. This permits a tree to be generated from pre-sorted input in linear
  793. time. */
  794. private void fabricateTree(int count)
  795. {
  796. if (count == 0)
  797. return;
  798. // Calculate the (maximum) depth of the perfectly balanced tree.
  799. double ddepth = (Math.log (count + 1) / Math.log (2));
  800. int maxdepth = (int) Math.ceil (ddepth);
  801. // The number of nodes which can fit in a perfectly-balanced tree of
  802. // height "depth - 1".
  803. int max = (int) Math.pow (2, maxdepth - 1) - 1;
  804. // Number of nodes which spill over into the deepest row of the tree.
  805. int overflow = (int) count - max;
  806. size = count;
  807. // Make the root node.
  808. root = new Node(null, null);
  809. root.parent = nil;
  810. root.left = nil;
  811. root.right = nil;
  812. Node row = root;
  813. for (int depth = 2; depth <= maxdepth; depth++) // each row
  814. {
  815. // Number of nodes at this depth
  816. int rowcap = (int) Math.pow (2, depth - 1);
  817. Node parent = row;
  818. Node last = null;
  819. // Actual number of nodes to create in this row
  820. int rowsize;
  821. if (depth == maxdepth)
  822. rowsize = overflow;
  823. else
  824. rowsize = rowcap;
  825. // The bottom most row of nodes is coloured red, as is every second row
  826. // going up, except the root node (row 1). I'm not sure if this is the
  827. // optimal configuration for the tree, but it seems logical enough.
  828. // We just need to honour the black-height and red-parent rules here.
  829. boolean colorRowRed = (depth % 2 == maxdepth % 2);
  830. int i;
  831. for (i = 1; i <= rowsize; i++) // each node in row
  832. {
  833. Node node = new Node(null, null);
  834. node.parent = parent;
  835. if (i % 2 == 1)
  836. parent.left = node;
  837. else
  838. {
  839. Node nextparent = parent.right;
  840. parent.right = node;
  841. parent = nextparent;
  842. }
  843. // We use the "right" link to maintain a chain of nodes in
  844. // each row until the parent->child links are established.
  845. if (last != null)
  846. last.right = node;
  847. last = node;
  848. if (colorRowRed)
  849. node.color = RED;
  850. if (i == 1)
  851. row = node;
  852. }
  853. // Set nil child pointers on leaf nodes.
  854. if (depth == maxdepth)
  855. {
  856. // leaf nodes at maxdepth-1.
  857. if (parent != null)
  858. {
  859. if (i % 2 == 0)
  860. {
  861. // Current "parent" has "left" set already.
  862. Node next = parent.right;
  863. parent.right = nil;
  864. parent = next;
  865. }
  866. while (parent != null)
  867. {
  868. parent.left = nil;
  869. Node next = parent.right;
  870. parent.right = nil;
  871. parent = next;
  872. }
  873. }
  874. // leaf nodes at maxdepth.
  875. Node node = row;
  876. Node next;
  877. while (node != null)
  878. {
  879. node.left = nil;
  880. next = node.right;
  881. node.right = nil;
  882. node = next;
  883. }
  884. }
  885. }
  886. }
  887. private class VerifyResult
  888. {
  889. int count; // Total number of nodes.
  890. int black; // Black height/depth.
  891. int maxdepth; // Maximum depth of branch.
  892. }
  893. /* Check that red-black properties are consistent for the tree. */
  894. private void verifyTree()
  895. {
  896. if (root == nil)
  897. {
  898. System.err.println ("Verify: empty tree");
  899. if (size != 0)
  900. verifyError (this, "no root node but size=" + size);
  901. return;
  902. }
  903. VerifyResult vr = verifySub (root);
  904. if (vr.count != size)
  905. {
  906. verifyError (this, "Tree size not consistent with actual nodes counted. "
  907. + "counted " + vr.count + ", size=" + size);
  908. System.exit(1);
  909. }
  910. System.err.println ("Verify: " + vr.count + " nodes, black height=" + vr.black
  911. + ", maxdepth=" + vr.maxdepth);
  912. }
  913. /* Recursive call to check that rbtree rules hold. Returns total node count
  914. and black height of the given branch. */
  915. private VerifyResult verifySub(Node n)
  916. {
  917. VerifyResult vr1 = null;
  918. VerifyResult vr2 = null;
  919. if (n.left == nil && n.right == nil)
  920. {
  921. // leaf node
  922. VerifyResult r = new VerifyResult();
  923. r.black = (n.color == BLACK ? 1 : 0);
  924. r.count = 1;
  925. r.maxdepth = 1;
  926. return r;
  927. }
  928. if (n.left != nil)
  929. {
  930. if (n.left.parent != n)
  931. verifyError(n.left, "Node's parent link does not point to " + n);
  932. if (n.color == RED && n.left.color == RED)
  933. verifyError(n, "Red node has red left child");
  934. vr1 = verifySub (n.left);
  935. if (n.right == nil)
  936. {
  937. if (n.color == BLACK)
  938. vr1.black++;
  939. vr1.count++;
  940. vr1.maxdepth++;
  941. return vr1;
  942. }
  943. }
  944. if (n.right != nil)
  945. {
  946. if (n.right.parent != n)
  947. verifyError(n.right, "Node's parent link does not point to " + n);
  948. if (n.color == RED && n.right.color == RED)
  949. verifyError(n, "Red node has red right child");
  950. vr2 = verifySub (n.right);
  951. if (n.left == nil)
  952. {
  953. if (n.color == BLACK)
  954. vr2.black++;
  955. vr2.count++;
  956. vr2.maxdepth++;
  957. return vr2;
  958. }
  959. }
  960. if (vr1.black != vr2.black)
  961. verifyError (n, "Black heights: " + vr1.black + "," + vr2.black + " don't match.");
  962. vr1.count += vr2.count + 1;
  963. vr1.maxdepth = Math.max(vr1.maxdepth, vr2.maxdepth) + 1;
  964. if (n.color == BLACK)
  965. vr1.black++;
  966. return vr1;
  967. }
  968. private void verifyError (Object obj, String msg)
  969. {
  970. System.err.print ("Verify error: ");
  971. try
  972. {
  973. System.err.print (obj);
  974. }
  975. catch (Exception x)
  976. {
  977. System.err.print ("(error printing obj): " + x);
  978. }
  979. System.err.println();
  980. System.err.println (msg);
  981. Thread.dumpStack();
  982. System.exit(1);
  983. }
  984. /**
  985. * Iterate over HashMap's entries.
  986. * This implementation is parameterized to give a sequential view of
  987. * keys, values, or entries.
  988. */
  989. class TreeIterator implements Iterator
  990. {
  991. static final int ENTRIES = 0,
  992. KEYS = 1,
  993. VALUES = 2;
  994. // the type of this Iterator: KEYS, VALUES, or ENTRIES.
  995. int type;
  996. // the number of modifications to the backing Map that we know about.
  997. int knownMod = TreeMap.this.modCount;
  998. // The last Entry returned by a next() call.
  999. Node last;
  1000. // The next entry that should be returned by next().
  1001. Node next;
  1002. // The last node visible to this iterator. This is used when iterating
  1003. // on a SubMap.
  1004. Node max;
  1005. /* Create Iterator with the supplied type: KEYS, VALUES, or ENTRIES */
  1006. TreeIterator(int type)
  1007. {
  1008. this.type = type;
  1009. this.next = firstNode();
  1010. }
  1011. /* Construct an interator for a SubMap. Iteration will begin at node
  1012. "first", and stop when "max" is reached. */
  1013. TreeIterator(int type, Node first, Node max)
  1014. {
  1015. this.type = type;
  1016. this.next = first;
  1017. this.max = max;
  1018. }
  1019. public boolean hasNext()
  1020. {
  1021. if (knownMod != TreeMap.this.modCount)
  1022. throw new ConcurrentModificationException();
  1023. return (next != nil);
  1024. }
  1025. public Object next()
  1026. {
  1027. if (next == nil)
  1028. throw new NoSuchElementException();
  1029. if (knownMod != TreeMap.this.modCount)
  1030. throw new ConcurrentModificationException();
  1031. Node n = next;
  1032. // Check limit in case we are iterating through a submap.
  1033. if (n != max)
  1034. next = successor(n);
  1035. else
  1036. next = nil;
  1037. last = n;
  1038. if (type == VALUES)
  1039. return n.value;
  1040. else if (type == KEYS)
  1041. return n.key;
  1042. return n;
  1043. }
  1044. public void remove()
  1045. {
  1046. if (last == null)
  1047. throw new IllegalStateException();
  1048. if (knownMod != TreeMap.this.modCount)
  1049. throw new ConcurrentModificationException();
  1050. /*
  1051. Object key = null;
  1052. if (next != nil)
  1053. key = next.key;
  1054. */
  1055. TreeMap.this.removeNode(last);
  1056. knownMod++;
  1057. /*
  1058. if (key != null)
  1059. next = getNode(key);
  1060. */
  1061. last = null;
  1062. }
  1063. }
  1064. class SubMap extends AbstractMap implements SortedMap
  1065. {
  1066. Object minKey;
  1067. Object maxKey;
  1068. /* Create a SubMap representing the elements between minKey and maxKey
  1069. (inclusive). If minKey is nil, SubMap has no lower bound (headMap).
  1070. If maxKey is nil, the SubMap has no upper bound (tailMap). */
  1071. SubMap(Object minKey, Object maxKey)
  1072. {
  1073. this.minKey = minKey;
  1074. this.maxKey = maxKey;
  1075. }
  1076. public void clear()
  1077. {
  1078. Node current;
  1079. Node next = lowestGreaterThan(minKey);
  1080. Node max = highestLessThan(maxKey);
  1081. if (compare(next.key, max.key) > 0)
  1082. // Nothing to delete.
  1083. return;
  1084. do
  1085. {
  1086. current = next;
  1087. next = successor(current);
  1088. remove(current);
  1089. }
  1090. while (current != max);
  1091. }
  1092. /* Check if "key" is in within the range bounds for this SubMap.
  1093. The lower ("from") SubMap range is inclusive, and the upper (to) bound
  1094. is exclusive. */
  1095. private boolean keyInRange(Object key)
  1096. {
  1097. return ((minKey == nil || compare(key, minKey) >= 0)
  1098. && (maxKey == nil || compare(key, maxKey) < 0));
  1099. }
  1100. public boolean containsKey(Object key)
  1101. {
  1102. return (keyInRange(key) && TreeMap.this.containsKey(key));
  1103. }
  1104. public boolean containsValue(Object value)
  1105. {
  1106. Node node = lowestGreaterThan(minKey);
  1107. Node max = highestLessThan(maxKey);
  1108. Object currentVal;
  1109. if (node == nil || max == nil || compare(node.key, max.key) > 0)
  1110. // Nothing to search.
  1111. return false;
  1112. while (true)
  1113. {
  1114. currentVal = node.getValue();
  1115. if (value == null ? currentVal == null : value.equals (currentVal))
  1116. return true;
  1117. if (node == max)
  1118. return false;
  1119. node = successor(node);
  1120. }
  1121. }
  1122. public Object get(Object key)
  1123. {
  1124. if (keyInRange(key))
  1125. return TreeMap.this.get(key);
  1126. return null;
  1127. }
  1128. public Object put(Object key, Object value)
  1129. {
  1130. if (keyInRange(key))
  1131. return TreeMap.this.put(key, value);
  1132. else
  1133. throw new IllegalArgumentException("Key outside range");
  1134. }
  1135. public Object remove(Object key)
  1136. {
  1137. if (keyInRange(key))
  1138. return TreeMap.this.remove(key);
  1139. else
  1140. return null;
  1141. }
  1142. public int size()
  1143. {
  1144. Node node = lowestGreaterThan(minKey);
  1145. Node max = highestLessThan(maxKey);
  1146. if (node == nil || max == nil || compare(node.key, max.key) > 0)
  1147. return 0; // Empty.
  1148. int count = 1;
  1149. while (node != max)
  1150. {
  1151. count++;
  1152. node = successor(node);
  1153. }
  1154. return count;
  1155. }
  1156. public Set entrySet()
  1157. {
  1158. // Create an AbstractSet with custom implementations of those methods that
  1159. // can be overriden easily and efficiently.
  1160. return new AbstractSet()
  1161. {
  1162. public int size()
  1163. {
  1164. return SubMap.this.size();
  1165. }
  1166. public Iterator iterator()
  1167. {
  1168. Node first = lowestGreaterThan(minKey);
  1169. Node max = highestLessThan(maxKey);
  1170. return new TreeIterator(TreeIterator.ENTRIES, first, max);
  1171. }
  1172. public void clear()
  1173. {
  1174. this.clear();
  1175. }
  1176. public boolean contains(Object o)
  1177. {
  1178. if (!(o instanceof Map.Entry))
  1179. return false;
  1180. Map.Entry me = (Map.Entry) o;
  1181. Object key = me.getKey();
  1182. if (!keyInRange(key))
  1183. return false;
  1184. Node n = getNode(key);
  1185. return (n != nil && me.getValue().equals(n.value));
  1186. }
  1187. public boolean remove(Object o)
  1188. {
  1189. if (!(o instanceof Map.Entry))
  1190. return false;
  1191. Map.Entry me = (Map.Entry) o;
  1192. Object key = me.getKey();
  1193. if (!keyInRange(key))
  1194. return false;
  1195. Node n = getNode(key);
  1196. if (n != nil && me.getValue().equals(n.value))
  1197. {
  1198. removeNode(n);
  1199. return true;
  1200. }
  1201. return false;
  1202. }
  1203. };
  1204. }
  1205. public Comparator comparator()
  1206. {
  1207. return comparator;
  1208. }
  1209. public Object firstKey()
  1210. {
  1211. Node node = lowestGreaterThan(minKey);
  1212. if (node == nil || !keyInRange(node.key))
  1213. throw new NoSuchElementException ("empty");
  1214. return node.key;
  1215. }
  1216. public Object lastKey()
  1217. {
  1218. Node node = highestLessThan(maxKey);
  1219. if (node == nil || !keyInRange(node.key))
  1220. throw new NoSuchElementException ("empty");
  1221. return node.key;
  1222. }
  1223. public SortedMap subMap(Object fromKey, Object toKey)
  1224. {
  1225. if (!keyInRange(fromKey) || !keyInRange(toKey))
  1226. throw new IllegalArgumentException("key outside range");
  1227. return TreeMap.this.subMap(fromKey, toKey);
  1228. }
  1229. public SortedMap headMap(Object toKey)
  1230. {
  1231. if (!keyInRange(toKey))
  1232. throw new IllegalArgumentException("key outside range");
  1233. return TreeMap.this.subMap(minKey, toKey);
  1234. }
  1235. public SortedMap tailMap(Object fromKey)
  1236. {
  1237. if (!keyInRange(fromKey))
  1238. throw new IllegalArgumentException("key outside range");
  1239. return TreeMap.this.subMap(fromKey, maxKey);
  1240. }
  1241. }
  1242. }