GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — classpath/java/util/TreeMap.java at master · jatovm/classpath Expand file tree/ Copy pathTreeMap.javaMore file actions 3341 lines (2970 loc) · 91.8 KB / Copy pathTreeMap.javaFile metadata and controls3341 lines (2970 loc) · 91.8 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 /* TreeMap.java -- a class providing a basic Red-Black Tree data structure, mapping Object --> Object Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package java.util; import gnu.java.lang.CPStringBuilder; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * This class provides a red-black tree implementation of the SortedMap * interface. Elements in the Map will be sorted by either a user-provided * Comparator object, or by the natural ordering of the keys. * * The algorithms are adopted from Corman, Leiserson, and Rivest's * <i>Introduction to Algorithms.</i> TreeMap guarantees O(log n) * insertion and deletion of elements. That being said, there is a large * enough constant coefficient in front of that "log n" (overhead involved * in keeping the tree balanced), that TreeMap may not be the best choice * for small collections. If something is already sorted, you may want to * just use a LinkedHashMap to maintain the order while providing O(1) access. * * TreeMap is a part of the JDK1.2 Collections API. Null keys are allowed * only if a Comparator is used which can deal with them; natural ordering * cannot cope with null. Null values are always allowed. Note that the * ordering must be <i>consistent with equals</i> to correctly implement * the Map interface. If this condition is violated, the map is still * well-behaved, but you may have suprising results when comparing it to * other maps.<p> * * This implementation is not synchronized. If you need to share this between * multiple threads, do something like:<br> * <code>SortedMap m * = Collections.synchronizedSortedMap(new TreeMap(...));</code><p> * * The iterators are <i>fail-fast</i>, meaning that any structural * modification, except for <code>remove()</code> called on the iterator * itself, cause the iterator to throw a * <code>ConcurrentModificationException</code> rather than exhibit * non-deterministic behavior. * * @author Jon Zeppieri * @author Bryce McKinlay * @author Eric Blake ([email protected]) * @author Andrew John Hughes ([email protected]) * @see Map * @see HashMap * @see Hashtable * @see LinkedHashMap * @see Comparable * @see Comparator * @see Collection * @see Collections#synchronizedSortedMap(SortedMap) * @since 1.2 * @status updated to 1.6 */ public class TreeMap<K, V> extends AbstractMap<K, V> implements NavigableMap<K, V>, Cloneable, Serializable { // Implementation note: // A red-black tree is a binary search tree with the additional properties // that all paths to a leaf node visit the same number of black nodes, // and no red node has red children. To avoid some null-pointer checks, // we use the special node nil which is always black, has no relatives, // and has key and value of null (but is not equal to a mapping of null). /** * Compatible with JDK 1.2. */ private static final long serialVersionUID = 919286545866124006L; /** * Color status of a node. Package visible for use by nested classes. */ static final int RED = -1, BLACK = 1; /** * Sentinal node, used to avoid null checks for corner cases and make the * delete rebalance code simpler. The rebalance code must never assign * the parent, left, or right of nil, but may safely reassign the color * to be black. This object must never be used as a key in a TreeMap, or * it will break bounds checking of a SubMap. */ static final Node<Object,Object> nil = new Node<Object,Object>(null, null, BLACK); static { // Nil is self-referential, so we must initialize it after creation. nil.parent = nil; nil.left = nil; nil.right = nil; } /** * The root node of this TreeMap. */ private transient Node<K,V> root; /** * The size of this TreeMap. Package visible for use by nested classes. */ transient int size; /** * The cache for {@link #entrySet()}. */ private transient Set<Map.Entry<K,V>> entries; /** * The cache for {@link #descendingMap()}. */ private transient NavigableMap<K,V> descendingMap; /** * The cache for {@link #navigableKeySet()}. */ private transient NavigableSet<K> nKeys; /** * Counts the number of modifications this TreeMap has undergone, used * by Iterators to know when to throw ConcurrentModificationExceptions. * Package visible for use by nested classes. */ transient int modCount; /** * This TreeMap's comparator, or null for natural ordering. * Package visible for use by nested classes. * @serial the comparator ordering this tree, or null */ final Comparator<? super K> comparator; /** * Class to represent an entry in the tree. Holds a single key-value pair, * plus pointers to parent and child nodes. * * @author Eric Blake ([email protected]) */ private static final class Node<K, V> extends AbstractMap.SimpleEntry<K, V> { // All fields package visible for use by nested classes. /** The color of this node. */ int color; /** The left child node. */ Node<K, V> left; /** The right child node. */ Node<K, V> right; /** The parent node. */ Node<K, V> parent; /** * Simple constructor. * @param key the key * @param value the value */ Node(K key, V value, int color) { super(key, value); @SuppressWarnings("unchecked") Node<K,V> typedNil = (Node<K,V>) nil; parent = left = right = typedNil; this.color = color; } } /** * Instantiate a new TreeMap with no elements, using the keys' natural * ordering to sort. All entries in the map must have a key which implements * Comparable, and which are <i>mutually comparable</i>, otherwise map * operations may throw a {@link ClassCastException}. Attempts to use * a null key will throw a {@link NullPointerException}. * * @see Comparable */ public TreeMap() { this((Comparator<? super K>) null); } /** * Instantiate a new TreeMap with no elements, using the provided comparator * to sort. All entries in the map must have keys which are mutually * comparable by the Comparator, otherwise map operations may throw a * {@link ClassCastException}. * * @param c the sort order for the keys of this map, or null * for the natural order */ public TreeMap(Comparator<? super K> c) { comparator = c; fabricateTree(0); } /** * Instantiate a new TreeMap, initializing it with all of the elements in * the provided Map. The elements will be sorted using the natural * ordering of the keys. This algorithm runs in n*log(n) time. All entries * in the map must have keys which implement Comparable and are mutually * comparable, otherwise map operations may throw a * {@link ClassCastException}. * * @param map a Map, whose entries will be put into this TreeMap * @throws ClassCastException if the keys in the provided Map are not * comparable * @throws NullPointerException if map is null * @see Comparable */ public TreeMap(Map<? extends K, ? extends V> map) { this((Comparator<? super K>) null); putAll(map); } /** * Instantiate a new TreeMap, initializing it with all of the elements in * the provided SortedMap. The elements will be sorted using the same * comparator as in the provided SortedMap. This runs in linear time. * * @param sm a SortedMap, whose entries will be put into this TreeMap * @throws NullPointerException if sm is null */ public TreeMap(SortedMap<K, ? extends V> sm) { this(sm.comparator()); fabricateTree(sm.size()); Node<K,V> node = firstNode(); for (Map.Entry<K,? extends V> me : sm.entrySet()) { node.key = me.getKey(); node.value = me.getValue(); node = successor(node); } } /** * Clears the Map so it has no keys. This is O(1). */ public void clear() { if (size > 0) { modCount++; @SuppressWarnings("unchecked") Node<K,V> typedNil = (Node<K,V>) nil; root = typedNil; size = 0; } } /** * Returns a shallow clone of this TreeMap. The Map itself is cloned, * but its contents are not. * * @return the clone */ public Object clone() { Object clone = null; try { clone = super.clone(); } catch (CloneNotSupportedException x) { } @SuppressWarnings("unchecked") TreeMap<K,V> copy = (TreeMap<K,V>) clone; copy.entries = null; copy.fabricateTree(size); Node<K,V> node = firstNode(); Node<K,V> cnode = copy.firstNode(); while (node != nil) { cnode.key = node.key; cnode.value = node.value; node = successor(node); cnode = copy.successor(cnode); } return copy; } /** * Return the comparator used to sort this map, or null if it is by * natural order. * * @return the map's comparator */ public Comparator<? super K> comparator() { return comparator; } /** * Returns true if the map contains a mapping for the given key. * * @param key the key to look for * @return true if the key has a mapping * @throws ClassCastException if key is not comparable to map elements * @throws NullPointerException if key is null and the comparator is not * tolerant of nulls */ public boolean containsKey(Object key) { @SuppressWarnings("unchecked") K k = (K) key; return getNode(k) != nil; } /** * Returns true if the map contains at least one mapping to the given value. * This requires linear time. * * @param value the value to look for * @return true if the value appears in a mapping */ public boolean containsValue(Object value) { Node<K,V> node = firstNode(); while (node != nil) { if (equals(value, node.value)) return true; node = successor(node); } return false; } /** * Returns a "set view" of this TreeMap's entries. The set is backed by * the TreeMap, so changes in one show up in the other. The set supports * element removal, but not element addition.<p> * * Note that the iterators for all three views, from keySet(), entrySet(), * and values(), traverse the TreeMap in sorted sequence. * * @return a set view of the entries * @see #keySet() * @see #values() * @see Map.Entry */ public Set<Map.Entry<K,V>> entrySet() { if (entries == null) // Create an AbstractSet with custom implementations of those methods // that can be overriden easily and efficiently. entries = new NavigableEntrySet(); return entries; } /** * Returns the first (lowest) key in the map. * * @return the first key * @throws NoSuchElementException if the map is empty */ public K firstKey() { if (root == nil) throw new NoSuchElementException(); return firstNode().key; } /** * Return the value in this TreeMap associated with the supplied key, * or <code>null</code> if the key maps to nothing. NOTE: Since the value * could also be null, you must use containsKey to see if this key * actually maps to something. * * @param key the key for which to fetch an associated value * @return what the key maps to, if present * @throws ClassCastException if key is not comparable to elements in the map * @throws NullPointerException if key is null but the comparator does not * tolerate nulls * @see #put(Object, Object) * @see #containsKey(Object) */ public V get(Object key) { @SuppressWarnings("unchecked") K k = (K) key; // Exploit fact that nil.value == null. return getNode(k).value; } /** * Returns a view of this Map including all entries with keys less than * <code>toKey</code>. The returned map is backed by the original, so changes * in one appear in the other. The submap will throw an * {@link IllegalArgumentException} for any attempt to access or add an * element beyond the specified cutoff. The returned map does not include * the endpoint; if you want inclusion, pass the successor element * or call <code>headMap(toKey, true)</code>. This is equivalent to * calling <code>headMap(toKey, false)</code>. * * @param toKey the (exclusive) cutoff point * @return a view of the map less than the cutoff * @throws ClassCastException if <code>toKey</code> is not compatible with * the comparator (or is not Comparable, for natural ordering) * @throws NullPointerException if toKey is null, but the comparator does not * tolerate null elements */ public SortedMap<K, V> headMap(K toKey) { return headMap(toKey, false); } /** * Returns a view of this Map including all entries with keys less than * (or equal to, if <code>inclusive</code> is true) <code>toKey</code>. * The returned map is backed by the original, so changes in one appear * in the other. The submap will throw an {@link IllegalArgumentException} * for any attempt to access or add an element beyond the specified cutoff. * * @param toKey the cutoff point * @param inclusive true if the cutoff point should be included. * @return a view of the map less than (or equal to, if <code>inclusive</code> * is true) the cutoff. * @throws ClassCastException if <code>toKey</code> is not compatible with * the comparator (or is not Comparable, for natural ordering) * @throws NullPointerException if toKey is null, but the comparator does not * tolerate null elements */ public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { @SuppressWarnings("unchecked") K nilKey = (K) nil; return new SubMap(nilKey, inclusive ? successor(getNode(toKey)).key : toKey); } /** * Returns a "set view" of this TreeMap's keys. The set is backed by the * TreeMap, so changes in one show up in the other. The set supports * element removal, but not element addition. * * @return a set view of the keys * @see #values() * @see #entrySet() */ public Set<K> keySet() { if (keys == null) // Create an AbstractSet with custom implementations of those methods // that can be overriden easily and efficiently. keys = new KeySet(); return keys; } /** * Returns the last (highest) key in the map. * * @return the last key * @throws NoSuchElementException if the map is empty */ public K lastKey() { if (root == nil) throw new NoSuchElementException("empty"); return lastNode().key; } /** * Puts the supplied value into the Map, mapped by the supplied key. * The value may be retrieved by any object which <code>equals()</code> * this key. NOTE: Since the prior value could also be null, you must * first use containsKey if you want to see if you are replacing the * key's mapping. * * @param key the key used to locate the value * @param value the value to be stored in the Map * @return the prior mapping of the key, or null if there was none * @throws ClassCastException if key is not comparable to current map keys * @throws NullPointerException if key is null, but the comparator does * not tolerate nulls * @see #get(Object) * @see Object#equals(Object) */ public V put(K key, V value) { Node<K,V> current = root; @SuppressWarnings("unchecked") Node<K,V> parent = (Node<K,V>) nil; int comparison = 0; // Find new node's parent. while (current != nil) { parent = current; comparison = compare(key, current.key); if (comparison > 0) current = current.right; else if (comparison < 0) current = current.left; else // Key already in tree. return current.setValue(value); } // Set up new node. Node<K,V> n = new Node<K,V>(key, value, RED); n.parent = parent; // Insert node in tree. modCount++; size++; if (parent == nil) { // Special case inserting into an empty tree. root = n; return null; } if (comparison > 0) parent.right = n; else parent.left = n; // Rebalance after insert. insertFixup(n); return null; } /** * Copies all elements of the given map into this TreeMap. If this map * already has a mapping for a key, the new mapping replaces the current * one. * * @param m the map to be added * @throws ClassCastException if a key in m is not comparable with keys * in the map * @throws NullPointerException if a key in m is null, and the comparator * does not tolerate nulls */ public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) put(e.getKey(), e.getValue()); } /** * Removes from the TreeMap and returns the value which is mapped by the * supplied key. If the key maps to nothing, then the TreeMap remains * unchanged, and <code>null</code> is returned. NOTE: Since the value * could also be null, you must use containsKey to see if you are * actually removing a mapping. * * @param key the key used to locate the value to remove * @return whatever the key mapped to, if present * @throws ClassCastException if key is not comparable to current map keys * @throws NullPointerException if key is null, but the comparator does * not tolerate nulls */ public V remove(Object key) { @SuppressWarnings("unchecked") K k = (K) key; Node<K, V> n = getNode(k); if (n == nil) return null; // Note: removeNode can alter the contents of n, so save value now. V result = n.value; removeNode(n); return result; } /** * Returns the number of key-value mappings currently in this Map. * * @return the size */ public int size() { return size; } /** * Returns a view of this Map including all entries with keys greater or * equal to <code>fromKey</code> and less than <code>toKey</code> (a * half-open interval). The returned map is backed by the original, so * changes in one appear in the other. The submap will throw an * {@link IllegalArgumentException} for any attempt to access or add an * element beyond the specified cutoffs. The returned map includes the low * endpoint but not the high; if you want to reverse this behavior on * either end, pass in the successor element or call * {@link #subMap(K,boolean,K,boolean)}. This call is equivalent to * <code>subMap(fromKey, true, toKey, false)</code>. * * @param fromKey the (inclusive) low cutoff point * @param toKey the (exclusive) high cutoff point * @return a view of the map between the cutoffs * @throws ClassCastException if either cutoff is not compatible with * the comparator (or is not Comparable, for natural ordering) * @throws NullPointerException if fromKey or toKey is null, but the * comparator does not tolerate null elements * @throws IllegalArgumentException if fromKey is greater than toKey */ public SortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } /** * Returns a view of this Map including all entries with keys greater (or * equal to, if <code>fromInclusive</code> is true) <code>fromKey</code> and * less than (or equal to, if <code>toInclusive</code> is true) * <code>toKey</code>. The returned map is backed by the original, so * changes in one appear in the other. The submap will throw an * {@link IllegalArgumentException} for any attempt to access or add an * element beyond the specified cutoffs. * * @param fromKey the low cutoff point * @param fromInclusive true if the low cutoff point should be included. * @param toKey the high cutoff point * @param toInclusive true if the high cutoff point should be included. * @return a view of the map for the specified range. * @throws ClassCastException if either cutoff is not compatible with * the comparator (or is not Comparable, for natural ordering) * @throws NullPointerException if fromKey or toKey is null, but the * comparator does not tolerate null elements * @throws IllegalArgumentException if fromKey is greater than toKey */ public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return new SubMap(fromInclusive ? fromKey : successor(getNode(fromKey)).key, toInclusive ? successor(getNode(toKey)).key : toKey); } /** * Returns a view of this Map including all entries with keys greater or * equal to <code>fromKey</code>. The returned map is backed by the * original, so changes in one appear in the other. The submap will throw an * {@link IllegalArgumentException} for any attempt to access or add an * element beyond the specified cutoff. The returned map includes the * endpoint; if you want to exclude it, pass in the successor element. * This is equivalent to calling <code>tailMap(fromKey, true)</code>. * * @param fromKey the (inclusive) low cutoff point * @return a view of the map above the cutoff * @throws ClassCastException if <code>fromKey</code> is not compatible with * the comparator (or is not Comparable, for natural ordering) * @throws NullPointerException if fromKey is null, but the comparator * does not tolerate null elements */ public SortedMap<K, V> tailMap(K fromKey) { return tailMap(fromKey, true); } /** * Returns a view of this Map including all entries with keys greater or * equal to <code>fromKey</code>. The returned map is backed by the * original, so changes in one appear in the other. The submap will throw an * {@link IllegalArgumentException} for any attempt to access or add an * element beyond the specified cutoff. The returned map includes the * endpoint; if you want to exclude it, pass in the successor element. * * @param fromKey the low cutoff point * @param inclusive true if the cutoff point should be included. * @return a view of the map above the cutoff * @throws ClassCastException if <code>fromKey</code> is not compatible with * the comparator (or is not Comparable, for natural ordering) * @throws NullPointerException if fromKey is null, but the comparator * does not tolerate null elements */ public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { @SuppressWarnings("unchecked") K nilKey = (K) nil; return new SubMap(inclusive ? fromKey : successor(getNode(fromKey)).key, nilKey); } /** * Returns a "collection view" (or "bag view") of this TreeMap's values. * The collection is backed by the TreeMap, so changes in one show up * in the other. The collection supports element removal, but not element * addition. * * @return a bag view of the values * @see #keySet() * @see #entrySet() */ public Collection<V> values() { if (values == null) // We don't bother overriding many of the optional methods, as doing so // wouldn't provide any significant performance advantage. values = new AbstractCollection<V>() { public int size() { return size; } public Iterator<V> iterator() { return new TreeIterator<V>(VALUES); } public void clear() { TreeMap.this.clear(); } }; return values; } /** * Compares two elements by the set comparator, or by natural ordering. * Package visible for use by nested classes. * * @param o1 the first object * @param o2 the second object * @throws ClassCastException if o1 and o2 are not mutually comparable, * or are not Comparable with natural ordering * @throws NullPointerException if o1 or o2 is null with natural ordering */ @SuppressWarnings("unchecked") final int compare(K o1, K o2) { return (comparator == null ? ((Comparable<? super K>) o1).compareTo(o2) : comparator.compare(o1, o2)); } /** * Maintain red-black balance after deleting a node. * * @param node the child of the node just deleted, possibly nil * @param parent the parent of the node just deleted, never nil */ private void deleteFixup(Node<K,V> node, Node<K,V> parent) { // if (parent == nil) // throw new InternalError(); // If a black node has been removed, we need to rebalance to avoid // violating the "same number of black nodes on any path" rule. If // node is red, we can simply recolor it black and all is well. while (node != root && node.color == BLACK) { if (node == parent.left) { // Rebalance left side. Node<K,V> sibling = parent.right; // if (sibling == nil) // throw new InternalError(); if (sibling.color == RED) { // Case 1: Sibling is red. // Recolor sibling and parent, and rotate parent left. sibling.color = BLACK; parent.color = RED; rotateLeft(parent); sibling = parent.right; } if (sibling.left.color == BLACK && sibling.right.color == BLACK) { // Case 2: Sibling has no red children. // Recolor sibling, and move to parent. sibling.color = RED; node = parent; parent = parent.parent; } else { if (sibling.right.color == BLACK) { // Case 3: Sibling has red left child. // Recolor sibling and left child, rotate sibling right. sibling.left.color = BLACK; sibling.color = RED; rotateRight(sibling); sibling = parent.right; } // Case 4: Sibling has red right child. Recolor sibling, // right child, and parent, and rotate parent left. sibling.color = parent.color; parent.color = BLACK; sibling.right.color = BLACK; rotateLeft(parent); node = root; // Finished. } } else { // Symmetric "mirror" of left-side case. Node<K,V> sibling = parent.left; // if (sibling == nil) // throw new InternalError(); if (sibling.color == RED) { // Case 1: Sibling is red. // Recolor sibling and parent, and rotate parent right. sibling.color = BLACK; parent.color = RED; rotateRight(parent); sibling = parent.left; } if (sibling.right.color == BLACK && sibling.left.color == BLACK) { // Case 2: Sibling has no red children. // Recolor sibling, and move to parent. sibling.color = RED; node = parent; parent = parent.parent; } else { if (sibling.left.color == BLACK) { // Case 3: Sibling has red right child. // Recolor sibling and right child, rotate sibling left. sibling.right.color = BLACK; sibling.color = RED; rotateLeft(sibling); sibling = parent.left; } // Case 4: Sibling has red left child. Recolor sibling, // left child, and parent, and rotate parent right. sibling.color = parent.color; parent.color = BLACK; sibling.left.color = BLACK; rotateRight(parent); node = root; // Finished. } } } node.color = BLACK; } /** * Construct a perfectly balanced tree consisting of n "blank" nodes. This * permits a tree to be generated from pre-sorted input in linear time. * * @param count the number of blank nodes, non-negative */ private void fabricateTree(final int count) { if (count == 0) { @SuppressWarnings("unchecked") Node<K,V> typedNil = (Node<K,V>) nil; root = typedNil; size = 0; return; } // We color every row of nodes black, except for the overflow nodes. // I believe that this is the optimal arrangement. We construct the tree // in place by temporarily linking each node to the next node in the row, // then updating those links to the children when working on the next row. // Make the root node. root = new Node<K,V>(null, null, BLACK); size = count; Node<K,V> row = root; int rowsize; // Fill each row that is completely full of nodes. for (rowsize = 2; rowsize + rowsize <= count; rowsize <<= 1) { Node<K,V> parent = row; Node<K,V> last = null; for (int i = 0; i < rowsize; i += 2) { Node<K,V> left = new Node<K,V>(null, null, BLACK); Node<K,V> right = new Node<K,V>(null, null, BLACK); left.parent = parent; left.right = right; right.parent = parent; parent.left = left; Node<K,V> next = parent.right; parent.right = right; parent = next; if (last != null) last.right = left; last = right; } row = row.left; } // Now do the partial final row in red. int overflow = count - rowsize; Node<K,V> parent = row; int i; for (i = 0; i < overflow; i += 2) { Node<K,V> left = new Node<K,V>(null, null, RED); Node<K,V> right = new Node<K,V>(null, null, RED); left.parent = parent; right.parent = parent; parent.left = left; Node<K,V> next = parent.right; parent.right = right; parent = next; } @SuppressWarnings("unchecked") Node<K,V> nilNode = (Node<K,V>) nil; // Add a lone left node if necessary. if (i - overflow == 0) { Node<K,V> left = new Node<K,V>(null, null, RED); left.parent = parent; parent.left = left; parent = parent.right; left.parent.right = nilNode; } // Unlink the remaining nodes of the previous row. while (parent != nil) { Node<K,V> next = parent.right; parent.right = nilNode; parent = next; } } /** * Returns the first sorted node in the map, or nil if empty. Package * visible for use by nested classes. * * @return the first node */ final Node<K, V> firstNode() { // Exploit fact that nil.left == nil. Node<K,V> node = root; while (node.left != nil) node = node.left; return node; } /** * Return the TreeMap.Node associated with key, or the nil node if no such * node exists in the tree. Package visible for use by nested classes. * * @param key the key to search for * @return the node where the key is found, or nil */ final Node<K, V> getNode(K key) { Node<K,V> current = root; while (current != nil) { int comparison = compare(key, current.key); if (comparison > 0) current = current.right; else if (comparison < 0) current = current.left; else return current; } return current; } /** * Find the "highest" node which is < key. If key is nil, return last * node. Package visible for use by nested classes. * * @param key the upper bound, exclusive * @return the previous node */ final Node<K,V> highestLessThan(K key) { |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |