12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323 |
- /* 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 (ebb9@email.byu.edu)
- * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
- * @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 nil = new Node(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 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 (ebb9@email.byu.edu)
- */
- 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 = nil;
- /** The right child node. */
- Node<K, V> right = nil;
- /** The parent node. */
- Node<K, V> parent = nil;
- /**
- * Simple constructor.
- * @param key the key
- * @param value the value
- */
- Node(K key, V value, int color)
- {
- super(key, value);
- 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) 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) 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());
- int pos = sm.size();
- Iterator itr = sm.entrySet().iterator();
- fabricateTree(pos);
- Node node = firstNode();
- while (--pos >= 0)
- {
- Map.Entry me = (Map.Entry) itr.next();
- 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++;
- root = nil;
- 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()
- {
- TreeMap copy = null;
- try
- {
- copy = (TreeMap) super.clone();
- }
- catch (CloneNotSupportedException x)
- {
- }
- copy.entries = null;
- copy.fabricateTree(size);
- Node node = firstNode();
- Node 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)
- {
- return getNode((K) key) != 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 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)
- {
- // Exploit fact that nil.value == null.
- return getNode((K) key).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)
- {
- return new SubMap((K)(Object)nil, 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;
- Node<K,V> parent = 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 n = new Node(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)
- {
- Iterator itr = m.entrySet().iterator();
- int pos = m.size();
- while (--pos >= 0)
- {
- Map.Entry<K,V> e = (Map.Entry<K,V>) itr.next();
- 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)
- {
- Node<K, V> n = getNode((K)key);
- 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)
- {
- return new SubMap(inclusive ? fromKey : successor(getNode(fromKey)).key,
- (K)(Object)nil);
- }
- /**
- * 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(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
- */
- final int compare(K o1, K o2)
- {
- return (comparator == null
- ? ((Comparable) 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)
- {
- root = nil;
- 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(null, null, BLACK);
- size = count;
- Node row = root;
- int rowsize;
- // Fill each row that is completely full of nodes.
- for (rowsize = 2; rowsize + rowsize <= count; rowsize <<= 1)
- {
- Node parent = row;
- Node last = null;
- for (int i = 0; i < rowsize; i += 2)
- {
- Node left = new Node(null, null, BLACK);
- Node right = new Node(null, null, BLACK);
- left.parent = parent;
- left.right = right;
- right.parent = parent;
- parent.left = left;
- Node 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 parent = row;
- int i;
- for (i = 0; i < overflow; i += 2)
- {
- Node left = new Node(null, null, RED);
- Node right = new Node(null, null, RED);
- left.parent = parent;
- right.parent = parent;
- parent.left = left;
- Node next = parent.right;
- parent.right = right;
- parent = next;
- }
- // Add a lone left node if necessary.
- if (i - overflow == 0)
- {
- Node left = new Node(null, null, RED);
- left.parent = parent;
- parent.left = left;
- parent = parent.right;
- left.parent.right = nil;
- }
- // Unlink the remaining nodes of the previous row.
- while (parent != nil)
- {
- Node next = parent.right;
- parent.right = nil;
- 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 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)
- {
- return highestLessThan(key, false);
- }
- /**
- * Find the "highest" node which is < (or equal to,
- * if <code>equal</code> is true) key. If key is nil,
- * return last node. Package visible for use by nested
- * classes.
- *
- * @param key the upper bound, exclusive
- * @param equal true if the key should be returned if found.
- * @return the previous node
- */
- final Node<K,V> highestLessThan(K key, boolean equal)
- {
- if (key == nil)
- return lastNode();
- Node<K,V> last = nil;
- Node<K,V> current = root;
- int comparison = 0;
- while (current != nil)
- {
- last = current;
- comparison = compare(key, current.key);
- if (comparison > 0)
- current = current.right;
- else if (comparison < 0)
- current = current.left;
- else // Exact match.
- return (equal ? last : predecessor(last));
- }
- return comparison < 0 ? predecessor(last) : last;
- }
- /**
- * Maintain red-black balance after inserting a new node.
- *
- * @param n the newly inserted node
- */
- private void insertFixup(Node<K,V> n)
- {
- // Only need to rebalance when parent is a RED node, and while at least
- // 2 levels deep into the tree (ie: node has a grandparent). Remember
- // that nil.color == BLACK.
- while (n.parent.color == RED && n.parent.parent != nil)
- {
- if (n.parent == n.parent.parent.left)
- {
- Node uncle = n.parent.parent.right;
- // Uncle may be nil, in which case it is BLACK.
- if (uncle.color == RED)
- {
- // Case 1. Uncle is RED: Change colors of parent, uncle,
- // and grandparent, and move n to grandparent.
- n.parent.color = BLACK;
- uncle.color = BLACK;
- uncle.parent.color = RED;
- n = uncle.parent;
- }
- else
- {
- if (n == n.parent.right)
- {
- // Case 2. Uncle is BLACK and x is right child.
- // Move n to parent, and rotate n left.
- n = n.parent;
- rotateLeft(n);
- }
- // Case 3. Uncle is BLACK and x is left child.
- // Recolor parent, grandparent, and rotate grandparent right.
- n.parent.color = BLACK;
- n.parent.parent.color = RED;
- rotateRight(n.parent.parent);
- }
- }
- else
- {
- // Mirror image of above code.
- Node uncle = n.parent.parent.left;
- // Uncle may be nil, in which case it is BLACK.
- if (uncle.color == RED)
- {
- // Case 1. Uncle is RED: Change colors of parent, uncle,
- // and grandparent, and move n to grandparent.
- n.parent.color = BLACK;
- uncle.color = BLACK;
- uncle.parent.color = RED;
- n = uncle.parent;
- }
- else
- {
- if (n == n.parent.left)
- {
- // Case 2. Uncle is BLACK and x is left child.
- // Move n to parent, and rotate n right.
- n = n.parent;
- rotateRight(n);
- }
- // Case 3. Uncle is BLACK and x is right child.
- // Recolor parent, grandparent, and rotate grandparent left.
- n.parent.color = BLACK;
- n.parent.parent.color = RED;
- rotateLeft(n.parent.parent);
- }
- }
- }
- root.color = BLACK;
- }
- /**
- * Returns the last sorted node in the map, or nil if empty.
- *
- * @return the last node
- */
- private Node<K,V> lastNode()
- {
- // Exploit fact that nil.right == nil.
- Node node = root;
- while (node.right != nil)
- node = node.right;
- return node;
- }
- /**
- * Find the "lowest" node which is >= key. If key is nil, return either
- * nil or the first node, depending on the parameter first. Package visible
- * for use by nested classes.
- *
- * @param key the lower bound, inclusive
- * @param first true to return the first element instead of nil for nil key
- * @return the next node
- */
- final Node<K,V> lowestGreaterThan(K key, boolean first)
- {
- return lowestGreaterThan(key, first, true);
- }
- /**
- * Find the "lowest" node which is > (or equal to, if <code>equal</code>
- * is true) key. If key is nil, return either nil or the first node, depending
- * on the parameter first. Package visible for use by nested classes.
- *
- * @param key the lower bound, inclusive
- * @param first true to return the first element instead of nil for nil key
- * @param equal true if the key should be returned if found.
- * @return the next node
- */
- final Node<K,V> lowestGreaterThan(K key, boolean first, boolean equal)
- {
- if (key == nil)
- return first ? firstNode() : nil;
- Node<K,V> last = nil;
- Node<K,V> current = root;
- int comparison = 0;
- while (current != nil)
- {
- last = current;
- comparison = compare(key, current.key);
- if (comparison > 0)
- current = current.right;
- else if (comparison < 0)
- current = current.left;
- else
- return (equal ? current : successor(current));
- }
- return comparison > 0 ? successor(last) : last;
- }
- /**
- * Return the node preceding the given one, or nil if there isn't one.
- *
- * @param node the current node, not nil
- * @return the prior node in sorted order
- */
- private Node<K,V> predecessor(Node<K,V> node)
- {
- if (node.left != nil)
- {
- node = node.left;
- while (node.right != nil)
- node = node.right;
- return node;
- }
- Node parent = node.parent;
- // Exploit fact that nil.left == nil and node is non-nil.
- while (node == parent.left)
- {
- node = parent;
- parent = node.parent;
- }
- return parent;
- }
- /**
- * Construct a tree from sorted keys in linear time. Package visible for
- * use by TreeSet.
- *
- * @param s the stream to read from
- * @param count the number of keys to read
- * @param readValues true to read values, false to insert "" as the value
- * @throws ClassNotFoundException if the underlying stream fails
- * @throws IOException if the underlying stream fails
- * @see #readObject(ObjectInputStream)
- * @see TreeSet#readObject(ObjectInputStream)
- */
- final void putFromObjStream(ObjectInputStream s, int count,
- boolean readValues)
- throws IOException, ClassNotFoundException
- {
- fabricateTree(count);
- Node node = firstNode();
- while (--count >= 0)
- {
- node.key = s.readObject();
- node.value = readValues ? s.readObject() : "";
- node = successor(node);
- }
- }
- /**
- * Construct a tree from sorted keys in linear time, with values of "".
- * Package visible for use by TreeSet, which uses a value type of String.
- *
- * @param keys the iterator over the sorted keys
- * @param count the number of nodes to insert
- * @see TreeSet#TreeSet(SortedSet)
- */
- final void putKeysLinear(Iterator<K> keys, int count)
- {
- fabricateTree(count);
- Node<K,V> node = firstNode();
- while (--count >= 0)
- {
- node.key = keys.next();
- node.value = (V) "";
- node = successor(node);
- }
- }
- /**
- * Deserializes this object from the given stream.
- *
- * @param s the stream to read from
- * @throws ClassNotFoundException if the underlying stream fails
- * @throws IOException if the underlying stream fails
- * @serialData the <i>size</i> (int), followed by key (Object) and value
- * (Object) pairs in sorted order
- */
- private void readObject(ObjectInputStream s)
- throws IOException, ClassNotFoundException
- {
- s.defaultReadObject();
- int size = s.readInt();
- putFromObjStream(s, size, true);
- }
- /**
- * Remove node from tree. This will increment modCount and decrement size.
- * Node must exist in the tree. Package visible for use by nested classes.
- *
- * @param node the node to remove
- */
- final void removeNode(Node<K,V> node)
- {
- Node<K,V> splice;
- Node<K,V> child;
- modCount++;
- size--;
- // Find splice, the node at the position to actually remove from the tree.
- if (node.left == nil)
- {
- // Node to be deleted has 0 or 1 children.
- splice = node;
- child = node.right;
- }
- else if (node.right == nil)
- {
- // Node to be deleted has 1 child.
- splice = node;
- child = node.left;
- }
- else
- {
- // Node has 2 children. Splice is node's predecessor, and we swap
- // its contents into node.
- splice = node.left;
- while (splice.right != nil)
- splice = splice.right;
- child = splice.left;
- node.key = splice.key;
- node.value = splice.value;
- }
- // Unlink splice from the tree.
- Node parent = splice.parent;
- if (child != nil)
- child.parent = parent;
- if (parent == nil)
- {
- // Special case for 0 or 1 node remaining.
- root = child;
- return;
- }
- if (splice == parent.left)
- parent.left = child;
- else
- parent.right = child;
- if (splice.color == BLACK)
- deleteFixup(child, parent);
- }
- /**
- * Rotate node n to the left.
- *
- * @param node the node to rotate
- */
- private void rotateLeft(Node<K,V> node)
- {
- Node child = node.right;
- // if (node == nil || child == nil)
- // throw new InternalError();
- // Establish node.right link.
- node.right = child.left;
- if (child.left != nil)
- child.left.parent = node;
- // Establish child->parent link.
- child.parent = node.parent;
- if (node.parent != nil)
- {
- if (node == node.parent.left)
- node.parent.left = child;
- else
- node.parent.right = child;
- }
- else
- root = child;
- // Link n and child.
- child.left = node;
- node.parent = child;
- }
- /**
- * Rotate node n to the right.
- *
- * @param node the node to rotate
- */
- private void rotateRight(Node<K,V> node)
- {
- Node child = node.left;
- // if (node == nil || child == nil)
- // throw new InternalError();
- // Establish node.left link.
- node.left = child.right;
- if (child.right != nil)
- child.right.parent = node;
- // Establish child->parent link.
- child.parent = node.parent;
- if (node.parent != nil)
- {
- if (node == node.parent.right)
- node.parent.right = child;
- else
- node.parent.left = child;
- }
- else
- root = child;
- // Link n and child.
- child.right = node;
- node.parent = child;
- }
- /**
- * Return the node following the given one, or nil if there isn't one.
- * Package visible for use by nested classes.
- *
- * @param node the current node, not nil
- * @return the next node in sorted order
- */
- final Node<K,V> successor(Node<K,V> node)
- {
- if (node.right != nil)
- {
- node = node.right;
- while (node.left != nil)
- node = node.left;
- return node;
- }
- Node<K,V> parent = node.parent;
- // Exploit fact that nil.right == nil and node is non-nil.
- while (node == parent.right)
- {
- node = parent;
- parent = parent.parent;
- }
- return parent;
- }
- /**
- * Serializes this object to the given stream.
- *
- * @param s the stream to write to
- * @throws IOException if the underlying stream fails
- * @serialData the <i>size</i> (int), followed by key (Object) and value
- * (Object) pairs in sorted order
- */
- private void writeObject(ObjectOutputStream s) throws IOException
- {
- s.defaultWriteObject();
- Node node = firstNode();
- s.writeInt(size);
- while (node != nil)
- {
- s.writeObject(node.key);
- s.writeObject(node.value);
- node = successor(node);
- }
- }
- /**
- * Iterate over TreeMap's entries. This implementation is parameterized
- * to give a sequential view of keys, values, or entries.
- *
- * @author Eric Blake (ebb9@email.byu.edu)
- */
- private final class TreeIterator implements Iterator
- {
- /**
- * The type of this Iterator: {@link #KEYS}, {@link #VALUES},
- * or {@link #ENTRIES}.
- */
- private final int type;
- /** The number of modifications to the backing Map that we know about. */
- private int knownMod = modCount;
- /** The last Entry returned by a next() call. */
- private Node last;
- /** The next entry that should be returned by next(). */
- private Node next;
- /**
- * The last node visible to this iterator. This is used when iterating
- * on a SubMap.
- */
- private final Node max;
- /**
- * Construct a new TreeIterator with the supplied type.
- * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
- */
- TreeIterator(int type)
- {
- this(type, firstNode(), nil);
- }
- /**
- * Construct a new TreeIterator with the supplied type. Iteration will
- * be from "first" (inclusive) to "max" (exclusive).
- *
- * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
- * @param first where to start iteration, nil for empty iterator
- * @param max the cutoff for iteration, nil for all remaining nodes
- */
- TreeIterator(int type, Node first, Node max)
- {
- this.type = type;
- this.next = first;
- this.max = max;
- }
- /**
- * Returns true if the Iterator has more elements.
- * @return true if there are more elements
- */
- public boolean hasNext()
- {
- return next != max;
- }
- /**
- * Returns the next element in the Iterator's sequential view.
- * @return the next element
- * @throws ConcurrentModificationException if the TreeMap was modified
- * @throws NoSuchElementException if there is none
- */
- public Object next()
- {
- if (knownMod != modCount)
- throw new ConcurrentModificationException();
- if (next == max)
- throw new NoSuchElementException();
- last = next;
- next = successor(last);
- if (type == VALUES)
- return last.value;
- else if (type == KEYS)
- return last.key;
- return last;
- }
- /**
- * Removes from the backing TreeMap the last element which was fetched
- * with the <code>next()</code> method.
- * @throws ConcurrentModificationException if the TreeMap was modified
- * @throws IllegalStateException if called when there is no last element
- */
- public void remove()
- {
- if (last == null)
- throw new IllegalStateException();
- if (knownMod != modCount)
- throw new ConcurrentModificationException();
- removeNode(last);
- last = null;
- knownMod++;
- }
- } // class TreeIterator
- /**
- * Implementation of {@link #subMap(Object, Object)} and other map
- * ranges. This class provides a view of a portion of the original backing
- * map, and throws {@link IllegalArgumentException} for attempts to
- * access beyond that range.
- *
- * @author Eric Blake (ebb9@email.byu.edu)
- */
- private final class SubMap
- extends AbstractMap<K,V>
- implements NavigableMap<K,V>
- {
- /**
- * The lower range of this view, inclusive, or nil for unbounded.
- * Package visible for use by nested classes.
- */
- final K minKey;
- /**
- * The upper range of this view, exclusive, or nil for unbounded.
- * Package visible for use by nested classes.
- */
- final K maxKey;
- /**
- * The cache for {@link #entrySet()}.
- */
- private Set<Map.Entry<K,V>> entries;
- /**
- * The cache for {@link #descendingMap()}.
- */
- private NavigableMap<K,V> descendingMap;
- /**
- * The cache for {@link #navigableKeySet()}.
- */
- private NavigableSet<K> nKeys;
- /**
- * Create a SubMap representing the elements between minKey (inclusive)
- * and maxKey (exclusive). If minKey is nil, SubMap has no lower bound
- * (headMap). If maxKey is nil, the SubMap has no upper bound (tailMap).
- *
- * @param minKey the lower bound
- * @param maxKey the upper bound
- * @throws IllegalArgumentException if minKey > maxKey
- */
- SubMap(K minKey, K maxKey)
- {
- if (minKey != nil && maxKey != nil && compare(minKey, maxKey) > 0)
- throw new IllegalArgumentException("fromKey > toKey");
- this.minKey = minKey;
- this.maxKey = maxKey;
- }
- /**
- * Check if "key" is in within the range bounds for this SubMap. The
- * lower ("from") SubMap range is inclusive, and the upper ("to") bound
- * is exclusive. Package visible for use by nested classes.
- *
- * @param key the key to check
- * @return true if the key is in range
- */
- boolean keyInRange(K key)
- {
- return ((minKey == nil || compare(key, minKey) >= 0)
- && (maxKey == nil || compare(key, maxKey) < 0));
- }
- public Entry<K,V> ceilingEntry(K key)
- {
- Entry<K,V> n = TreeMap.this.ceilingEntry(key);
- if (n != null && keyInRange(n.getKey()))
- return n;
- return null;
- }
- public K ceilingKey(K key)
- {
- K found = TreeMap.this.ceilingKey(key);
- if (keyInRange(found))
- return found;
- else
- return null;
- }
- public NavigableSet<K> descendingKeySet()
- {
- return descendingMap().navigableKeySet();
- }
- public NavigableMap<K,V> descendingMap()
- {
- if (descendingMap == null)
- descendingMap = new DescendingMap(this);
- return descendingMap;
- }
- public void clear()
- {
- Node next = lowestGreaterThan(minKey, true);
- Node max = lowestGreaterThan(maxKey, false);
- while (next != max)
- {
- Node current = next;
- next = successor(current);
- removeNode(current);
- }
- }
- public Comparator<? super K> comparator()
- {
- return comparator;
- }
- public boolean containsKey(Object key)
- {
- return keyInRange((K) key) && TreeMap.this.containsKey(key);
- }
- public boolean containsValue(Object value)
- {
- Node node = lowestGreaterThan(minKey, true);
- Node max = lowestGreaterThan(maxKey, false);
- while (node != max)
- {
- if (equals(value, node.getValue()))
- return true;
- node = successor(node);
- }
- return false;
- }
- 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 SubMap.NavigableEntrySet();
- return entries;
- }
- public Entry<K,V> firstEntry()
- {
- Node<K,V> node = lowestGreaterThan(minKey, true);
- if (node == nil || ! keyInRange(node.key))
- return null;
- return node;
- }
- public K firstKey()
- {
- Entry<K,V> e = firstEntry();
- if (e == null)
- throw new NoSuchElementException();
- return e.getKey();
- }
- public Entry<K,V> floorEntry(K key)
- {
- Entry<K,V> n = TreeMap.this.floorEntry(key);
- if (n != null && keyInRange(n.getKey()))
- return n;
- return null;
- }
- public K floorKey(K key)
- {
- K found = TreeMap.this.floorKey(key);
- if (keyInRange(found))
- return found;
- else
- return null;
- }
- public V get(Object key)
- {
- if (keyInRange((K) key))
- return TreeMap.this.get(key);
- return null;
- }
- public SortedMap<K,V> headMap(K toKey)
- {
- return headMap(toKey, false);
- }
- public NavigableMap<K,V> headMap(K toKey, boolean inclusive)
- {
- if (!keyInRange(toKey))
- throw new IllegalArgumentException("Key outside submap range");
- return new SubMap(minKey, (inclusive ?
- successor(getNode(toKey)).key : toKey));
- }
- public Set<K> keySet()
- {
- if (this.keys == null)
- // Create an AbstractSet with custom implementations of those methods
- // that can be overriden easily and efficiently.
- this.keys = new SubMap.KeySet();
- return this.keys;
- }
- public Entry<K,V> higherEntry(K key)
- {
- Entry<K,V> n = TreeMap.this.higherEntry(key);
- if (n != null && keyInRange(n.getKey()))
- return n;
- return null;
- }
- public K higherKey(K key)
- {
- K found = TreeMap.this.higherKey(key);
- if (keyInRange(found))
- return found;
- else
- return null;
- }
- public Entry<K,V> lastEntry()
- {
- return lowerEntry(maxKey);
- }
- public K lastKey()
- {
- Entry<K,V> e = lastEntry();
- if (e == null)
- throw new NoSuchElementException();
- return e.getKey();
- }
- public Entry<K,V> lowerEntry(K key)
- {
- Entry<K,V> n = TreeMap.this.lowerEntry(key);
- if (n != null && keyInRange(n.getKey()))
- return n;
- return null;
- }
- public K lowerKey(K key)
- {
- K found = TreeMap.this.lowerKey(key);
- if (keyInRange(found))
- return found;
- else
- return null;
- }
- public NavigableSet<K> navigableKeySet()
- {
- if (this.nKeys == null)
- // Create an AbstractSet with custom implementations of those methods
- // that can be overriden easily and efficiently.
- this.nKeys = new SubMap.NavigableKeySet();
- return this.nKeys;
- }
- public Entry<K,V> pollFirstEntry()
- {
- Entry<K,V> e = firstEntry();
- if (e != null)
- removeNode((Node<K,V>) e);
- return e;
- }
- public Entry<K,V> pollLastEntry()
- {
- Entry<K,V> e = lastEntry();
- if (e != null)
- removeNode((Node<K,V>) e);
- return e;
- }
- public V put(K key, V value)
- {
- if (! keyInRange(key))
- throw new IllegalArgumentException("Key outside range");
- return TreeMap.this.put(key, value);
- }
- public V remove(Object key)
- {
- if (keyInRange((K)key))
- return TreeMap.this.remove(key);
- return null;
- }
- public int size()
- {
- Node node = lowestGreaterThan(minKey, true);
- Node max = lowestGreaterThan(maxKey, false);
- int count = 0;
- while (node != max)
- {
- count++;
- node = successor(node);
- }
- return count;
- }
- public SortedMap<K,V> subMap(K fromKey, K toKey)
- {
- return subMap(fromKey, true, toKey, false);
- }
- public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
- K toKey, boolean toInclusive)
- {
- if (! keyInRange(fromKey) || ! keyInRange(toKey))
- throw new IllegalArgumentException("key outside range");
- return new SubMap(fromInclusive ? fromKey : successor(getNode(fromKey)).key,
- toInclusive ? successor(getNode(toKey)).key : toKey);
- }
- public SortedMap<K, V> tailMap(K fromKey)
- {
- return tailMap(fromKey, true);
- }
- public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive)
- {
- if (! keyInRange(fromKey))
- throw new IllegalArgumentException("key outside range");
- return new SubMap(inclusive ? fromKey : successor(getNode(fromKey)).key,
- maxKey);
- }
- public Collection<V> values()
- {
- if (this.values == null)
- // Create an AbstractCollection with custom implementations of those
- // methods that can be overriden easily and efficiently.
- this.values = new AbstractCollection()
- {
- public int size()
- {
- return SubMap.this.size();
- }
- public Iterator<V> iterator()
- {
- Node first = lowestGreaterThan(minKey, true);
- Node max = lowestGreaterThan(maxKey, false);
- return new TreeIterator(VALUES, first, max);
- }
- public void clear()
- {
- SubMap.this.clear();
- }
- };
- return this.values;
- }
- private class KeySet
- extends AbstractSet<K>
- {
- public int size()
- {
- return SubMap.this.size();
- }
- public Iterator<K> iterator()
- {
- Node first = lowestGreaterThan(minKey, true);
- Node max = lowestGreaterThan(maxKey, false);
- return new TreeIterator(KEYS, first, max);
- }
- public void clear()
- {
- SubMap.this.clear();
- }
- public boolean contains(Object o)
- {
- if (! keyInRange((K) o))
- return false;
- return getNode((K) o) != nil;
- }
- public boolean remove(Object o)
- {
- if (! keyInRange((K) o))
- return false;
- Node n = getNode((K) o);
- if (n != nil)
- {
- removeNode(n);
- return true;
- }
- return false;
- }
- } // class SubMap.KeySet
- private final class NavigableKeySet
- extends KeySet
- implements NavigableSet<K>
- {
- public K ceiling(K k)
- {
- return SubMap.this.ceilingKey(k);
- }
- public Comparator<? super K> comparator()
- {
- return comparator;
- }
- public Iterator<K> descendingIterator()
- {
- return descendingSet().iterator();
- }
- public NavigableSet<K> descendingSet()
- {
- return new DescendingSet(this);
- }
- public K first()
- {
- return SubMap.this.firstKey();
- }
- public K floor(K k)
- {
- return SubMap.this.floorKey(k);
- }
- public SortedSet<K> headSet(K to)
- {
- return headSet(to, false);
- }
- public NavigableSet<K> headSet(K to, boolean inclusive)
- {
- return SubMap.this.headMap(to, inclusive).navigableKeySet();
- }
- public K higher(K k)
- {
- return SubMap.this.higherKey(k);
- }
- public K last()
- {
- return SubMap.this.lastKey();
- }
- public K lower(K k)
- {
- return SubMap.this.lowerKey(k);
- }
- public K pollFirst()
- {
- return SubMap.this.pollFirstEntry().getKey();
- }
- public K pollLast()
- {
- return SubMap.this.pollLastEntry().getKey();
- }
- public SortedSet<K> subSet(K from, K to)
- {
- return subSet(from, true, to, false);
- }
- public NavigableSet<K> subSet(K from, boolean fromInclusive,
- K to, boolean toInclusive)
- {
- return SubMap.this.subMap(from, fromInclusive,
- to, toInclusive).navigableKeySet();
- }
- public SortedSet<K> tailSet(K from)
- {
- return tailSet(from, true);
- }
- public NavigableSet<K> tailSet(K from, boolean inclusive)
- {
- return SubMap.this.tailMap(from, inclusive).navigableKeySet();
- }
- } // class SubMap.NavigableKeySet
- /**
- * Implementation of {@link #entrySet()}.
- */
- private class EntrySet
- extends AbstractSet<Entry<K,V>>
- {
- public int size()
- {
- return SubMap.this.size();
- }
- public Iterator<Map.Entry<K,V>> iterator()
- {
- Node first = lowestGreaterThan(minKey, true);
- Node max = lowestGreaterThan(maxKey, false);
- return new TreeIterator(ENTRIES, first, max);
- }
- public void clear()
- {
- SubMap.this.clear();
- }
- public boolean contains(Object o)
- {
- if (! (o instanceof Map.Entry))
- return false;
- Map.Entry<K,V> me = (Map.Entry<K,V>) o;
- K key = me.getKey();
- if (! keyInRange(key))
- return false;
- Node<K,V> n = getNode(key);
- return n != nil && AbstractSet.equals(me.getValue(), n.value);
- }
- public boolean remove(Object o)
- {
- if (! (o instanceof Map.Entry))
- return false;
- Map.Entry<K,V> me = (Map.Entry<K,V>) o;
- K key = me.getKey();
- if (! keyInRange(key))
- return false;
- Node<K,V> n = getNode(key);
- if (n != nil && AbstractSet.equals(me.getValue(), n.value))
- {
- removeNode(n);
- return true;
- }
- return false;
- }
- } // class SubMap.EntrySet
- private final class NavigableEntrySet
- extends EntrySet
- implements NavigableSet<Entry<K,V>>
- {
- public Entry<K,V> ceiling(Entry<K,V> e)
- {
- return SubMap.this.ceilingEntry(e.getKey());
- }
- public Comparator<? super Entry<K,V>> comparator()
- {
- return new Comparator<Entry<K,V>>()
- {
- public int compare(Entry<K,V> t1, Entry<K,V> t2)
- {
- return comparator.compare(t1.getKey(), t2.getKey());
- }
- };
- }
- public Iterator<Entry<K,V>> descendingIterator()
- {
- return descendingSet().iterator();
- }
- public NavigableSet<Entry<K,V>> descendingSet()
- {
- return new DescendingSet(this);
- }
- public Entry<K,V> first()
- {
- return SubMap.this.firstEntry();
- }
- public Entry<K,V> floor(Entry<K,V> e)
- {
- return SubMap.this.floorEntry(e.getKey());
- }
- public SortedSet<Entry<K,V>> headSet(Entry<K,V> to)
- {
- return headSet(to, false);
- }
- public NavigableSet<Entry<K,V>> headSet(Entry<K,V> to, boolean inclusive)
- {
- return (NavigableSet<Entry<K,V>>)
- SubMap.this.headMap(to.getKey(), inclusive).entrySet();
- }
- public Entry<K,V> higher(Entry<K,V> e)
- {
- return SubMap.this.higherEntry(e.getKey());
- }
- public Entry<K,V> last()
- {
- return SubMap.this.lastEntry();
- }
- public Entry<K,V> lower(Entry<K,V> e)
- {
- return SubMap.this.lowerEntry(e.getKey());
- }
- public Entry<K,V> pollFirst()
- {
- return SubMap.this.pollFirstEntry();
- }
- public Entry<K,V> pollLast()
- {
- return SubMap.this.pollLastEntry();
- }
- public SortedSet<Entry<K,V>> subSet(Entry<K,V> from, Entry<K,V> to)
- {
- return subSet(from, true, to, false);
- }
- public NavigableSet<Entry<K,V>> subSet(Entry<K,V> from, boolean fromInclusive,
- Entry<K,V> to, boolean toInclusive)
- {
- return (NavigableSet<Entry<K,V>>)
- SubMap.this.subMap(from.getKey(), fromInclusive,
- to.getKey(), toInclusive).entrySet();
- }
- public SortedSet<Entry<K,V>> tailSet(Entry<K,V> from)
- {
- return tailSet(from, true);
- }
- public NavigableSet<Entry<K,V>> tailSet(Entry<K,V> from, boolean inclusive)
- {
- return (NavigableSet<Entry<K,V>>)
- SubMap.this.tailMap(from.getKey(), inclusive).navigableKeySet();
- }
- } // class SubMap.NavigableEntrySet
- } // class SubMap
- /**
- * Returns the entry associated with the least or lowest key
- * that is greater than or equal to the specified key, or
- * <code>null</code> if there is no such key.
- *
- * @param key the key relative to the returned entry.
- * @return the entry with the least key greater than or equal
- * to the given key, or <code>null</code> if there is
- * no such key.
- * @throws ClassCastException if the specified key can not
- * be compared with those in the map.
- * @throws NullPointerException if the key is <code>null</code>
- * and this map either uses natural
- * ordering or a comparator that does
- * not permit null keys.
- * @since 1.6
- */
- public Entry<K,V> ceilingEntry(K key)
- {
- Node<K,V> n = lowestGreaterThan(key, false);
- return (n == nil) ? null : n;
- }
- /**
- * Returns the the least or lowest key that is greater than
- * or equal to the specified key, or <code>null</code> if
- * there is no such key.
- *
- * @param key the key relative to the returned entry.
- * @return the least key greater than or equal to the given key,
- * or <code>null</code> if there is no such key.
- * @throws ClassCastException if the specified key can not
- * be compared with those in the map.
- * @throws NullPointerException if the key is <code>null</code>
- * and this map either uses natural
- * ordering or a comparator that does
- * not permit null keys.
- * @since 1.6
- */
- public K ceilingKey(K key)
- {
- Entry<K,V> e = ceilingEntry(key);
- return (e == null) ? null : e.getKey();
- }
- /**
- * Returns a reverse ordered {@link NavigableSet} view of this
- * map's keys. The set is backed by the {@link TreeMap}, so changes
- * in one show up in the other. The set supports element removal,
- * but not element addition.
- *
- * @return a reverse ordered set view of the keys.
- * @since 1.6
- * @see #descendingMap()
- */
- public NavigableSet<K> descendingKeySet()
- {
- return descendingMap().navigableKeySet();
- }
- /**
- * Returns a view of the map in reverse order. The descending map
- * is backed by the original map, so that changes affect both maps.
- * Any changes occurring to either map while an iteration is taking
- * place (with the exception of a {@link Iterator#remove()} operation)
- * result in undefined behaviour from the iteration. The ordering
- * of the descending map is the same as for a map with a
- * {@link Comparator} given by {@link Collections#reverseOrder()},
- * and calling {@link #descendingMap()} on the descending map itself
- * results in a view equivalent to the original map.
- *
- * @return a reverse order view of the map.
- * @since 1.6
- */
- public NavigableMap<K,V> descendingMap()
- {
- if (descendingMap == null)
- descendingMap = new DescendingMap<K,V>(this);
- return descendingMap;
- }
- /**
- * Returns the entry associated with the least or lowest key
- * in the map, or <code>null</code> if the map is empty.
- *
- * @return the lowest entry, or <code>null</code> if the map
- * is empty.
- * @since 1.6
- */
- public Entry<K,V> firstEntry()
- {
- Node<K,V> n = firstNode();
- return (n == nil) ? null : n;
- }
- /**
- * Returns the entry associated with the greatest or highest key
- * that is less than or equal to the specified key, or
- * <code>null</code> if there is no such key.
- *
- * @param key the key relative to the returned entry.
- * @return the entry with the greatest key less than or equal
- * to the given key, or <code>null</code> if there is
- * no such key.
- * @throws ClassCastException if the specified key can not
- * be compared with those in the map.
- * @throws NullPointerException if the key is <code>null</code>
- * and this map either uses natural
- * ordering or a comparator that does
- * not permit null keys.
- * @since 1.6
- */
- public Entry<K,V> floorEntry(K key)
- {
- Node<K,V> n = highestLessThan(key, true);
- return (n == nil) ? null : n;
- }
- /**
- * Returns the the greatest or highest key that is less than
- * or equal to the specified key, or <code>null</code> if
- * there is no such key.
- *
- * @param key the key relative to the returned entry.
- * @return the greatest key less than or equal to the given key,
- * or <code>null</code> if there is no such key.
- * @throws ClassCastException if the specified key can not
- * be compared with those in the map.
- * @throws NullPointerException if the key is <code>null</code>
- * and this map either uses natural
- * ordering or a comparator that does
- * not permit null keys.
- * @since 1.6
- */
- public K floorKey(K key)
- {
- Entry<K,V> e = floorEntry(key);
- return (e == null) ? null : e.getKey();
- }
- /**
- * Returns the entry associated with the least or lowest key
- * that is strictly greater than the specified key, or
- * <code>null</code> if there is no such key.
- *
- * @param key the key relative to the returned entry.
- * @return the entry with the least key greater than
- * the given key, or <code>null</code> if there is
- * no such key.
- * @throws ClassCastException if the specified key can not
- * be compared with those in the map.
- * @throws NullPointerException if the key is <code>null</code>
- * and this map either uses natural
- * ordering or a comparator that does
- * not permit null keys.
- * @since 1.6
- */
- public Entry<K,V> higherEntry(K key)
- {
- Node<K,V> n = lowestGreaterThan(key, false, false);
- return (n == nil) ? null : n;
- }
- /**
- * Returns the the least or lowest key that is strictly
- * greater than the specified key, or <code>null</code> if
- * there is no such key.
- *
- * @param key the key relative to the returned entry.
- * @return the least key greater than the given key,
- * or <code>null</code> if there is no such key.
- * @throws ClassCastException if the specified key can not
- * be compared with those in the map.
- * @throws NullPointerException if the key is <code>null</code>
- * and this map either uses natural
- * ordering or a comparator that does
- * not permit null keys.
- * @since 1.6
- */
- public K higherKey(K key)
- {
- Entry<K,V> e = higherEntry(key);
- return (e == null) ? null : e.getKey();
- }
- /**
- * Returns the entry associated with the greatest or highest key
- * in the map, or <code>null</code> if the map is empty.
- *
- * @return the highest entry, or <code>null</code> if the map
- * is empty.
- * @since 1.6
- */
- public Entry<K,V> lastEntry()
- {
- Node<K,V> n = lastNode();
- return (n == nil) ? null : n;
- }
- /**
- * Returns the entry associated with the greatest or highest key
- * that is strictly less than the specified key, or
- * <code>null</code> if there is no such key.
- *
- * @param key the key relative to the returned entry.
- * @return the entry with the greatest key less than
- * the given key, or <code>null</code> if there is
- * no such key.
- * @throws ClassCastException if the specified key can not
- * be compared with those in the map.
- * @throws NullPointerException if the key is <code>null</code>
- * and this map either uses natural
- * ordering or a comparator that does
- * not permit null keys.
- * @since 1.6
- */
- public Entry<K,V> lowerEntry(K key)
- {
- Node<K,V> n = highestLessThan(key);
- return (n == nil) ? null : n;
- }
- /**
- * Returns the the greatest or highest key that is strictly
- * less than the specified key, or <code>null</code> if
- * there is no such key.
- *
- * @param key the key relative to the returned entry.
- * @return the greatest key less than the given key,
- * or <code>null</code> if there is no such key.
- * @throws ClassCastException if the specified key can not
- * be compared with those in the map.
- * @throws NullPointerException if the key is <code>null</code>
- * and this map either uses natural
- * ordering or a comparator that does
- * not permit null keys.
- * @since 1.6
- */
- public K lowerKey(K key)
- {
- Entry<K,V> e = lowerEntry(key);
- return (e == null) ? null : e.getKey();
- }
- /**
- * Returns a {@link NavigableSet} view of this map's keys. The set is
- * backed by the {@link TreeMap}, so changes in one show up in the other.
- * Any changes occurring to either while an iteration is taking
- * place (with the exception of a {@link Iterator#remove()} operation)
- * result in undefined behaviour from the iteration. The ordering
- * The set supports element removal, but not element addition.
- *
- * @return a {@link NavigableSet} view of the keys.
- * @since 1.6
- */
- public NavigableSet<K> navigableKeySet()
- {
- if (nKeys == null)
- nKeys = new NavigableKeySet();
- return nKeys;
- }
- /**
- * Removes and returns the entry associated with the least
- * or lowest key in the map, or <code>null</code> if the map
- * is empty.
- *
- * @return the removed first entry, or <code>null</code> if the
- * map is empty.
- * @since 1.6
- */
- public Entry<K,V> pollFirstEntry()
- {
- Entry<K,V> e = firstEntry();
- if (e != null)
- removeNode((Node<K,V>)e);
- return e;
- }
- /**
- * Removes and returns the entry associated with the greatest
- * or highest key in the map, or <code>null</code> if the map
- * is empty.
- *
- * @return the removed last entry, or <code>null</code> if the
- * map is empty.
- * @since 1.6
- */
- public Entry<K,V> pollLastEntry()
- {
- Entry<K,V> e = lastEntry();
- if (e != null)
- removeNode((Node<K,V>)e);
- return e;
- }
- /**
- * Implementation of {@link #descendingMap()} and associated
- * derivatives. This class provides a view of the
- * original backing map in reverse order, and throws
- * {@link IllegalArgumentException} for attempts to
- * access beyond that range.
- *
- * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
- */
- private static final class DescendingMap<DK,DV>
- implements NavigableMap<DK,DV>
- {
- /**
- * The cache for {@link #entrySet()}.
- */
- private Set<Map.Entry<DK,DV>> entries;
- /**
- * The cache for {@link #keySet()}.
- */
- private Set<DK> keys;
- /**
- * The cache for {@link #navigableKeySet()}.
- */
- private NavigableSet<DK> nKeys;
- /**
- * The cache for {@link #values()}.
- */
- private Collection<DV> values;
- /**
- * The backing {@link NavigableMap}.
- */
- private NavigableMap<DK,DV> map;
- /**
- * Create a {@link DescendingMap} around the specified
- * map.
- *
- * @param map the map to wrap.
- */
- public DescendingMap(NavigableMap<DK,DV> map)
- {
- this.map = map;
- }
- public Map.Entry<DK,DV> ceilingEntry(DK key)
- {
- return map.floorEntry(key);
- }
- public DK ceilingKey(DK key)
- {
- return map.floorKey(key);
- }
- public void clear()
- {
- map.clear();
- }
- public Comparator<? super DK> comparator()
- {
- return Collections.reverseOrder(map.comparator());
- }
- public boolean containsKey(Object o)
- {
- return map.containsKey(o);
- }
- public boolean containsValue(Object o)
- {
- return map.containsValue(o);
- }
- public NavigableSet<DK> descendingKeySet()
- {
- return descendingMap().navigableKeySet();
- }
- public NavigableMap<DK,DV> descendingMap()
- {
- return map;
- }
- public Set<Entry<DK,DV>> entrySet()
- {
- if (entries == null)
- entries =
- new DescendingSet<Entry<DK,DV>>((NavigableSet<Entry<DK,DV>>)
- map.entrySet());
- return entries;
- }
- public boolean equals(Object o)
- {
- return map.equals(o);
- }
- public Entry<DK,DV> firstEntry()
- {
- return map.lastEntry();
- }
- public DK firstKey()
- {
- return map.lastKey();
- }
- public Entry<DK,DV> floorEntry(DK key)
- {
- return map.ceilingEntry(key);
- }
- public DK floorKey(DK key)
- {
- return map.ceilingKey(key);
- }
- public DV get(Object key)
- {
- return map.get(key);
- }
- public int hashCode()
- {
- return map.hashCode();
- }
- public SortedMap<DK,DV> headMap(DK toKey)
- {
- return headMap(toKey, false);
- }
- public NavigableMap<DK,DV> headMap(DK toKey, boolean inclusive)
- {
- return new DescendingMap(map.tailMap(toKey, inclusive));
- }
- public Entry<DK,DV> higherEntry(DK key)
- {
- return map.lowerEntry(key);
- }
- public DK higherKey(DK key)
- {
- return map.lowerKey(key);
- }
- public Set<DK> keySet()
- {
- if (keys == null)
- keys = new DescendingSet<DK>(map.navigableKeySet());
- return keys;
- }
- public boolean isEmpty()
- {
- return map.isEmpty();
- }
- public Entry<DK,DV> lastEntry()
- {
- return map.firstEntry();
- }
- public DK lastKey()
- {
- return map.firstKey();
- }
- public Entry<DK,DV> lowerEntry(DK key)
- {
- return map.higherEntry(key);
- }
- public DK lowerKey(DK key)
- {
- return map.higherKey(key);
- }
- public NavigableSet<DK> navigableKeySet()
- {
- if (nKeys == null)
- nKeys = new DescendingSet<DK>(map.navigableKeySet());
- return nKeys;
- }
- public Entry<DK,DV> pollFirstEntry()
- {
- return pollLastEntry();
- }
- public Entry<DK,DV> pollLastEntry()
- {
- return pollFirstEntry();
- }
- public DV put(DK key, DV value)
- {
- return map.put(key, value);
- }
- public void putAll(Map<? extends DK, ? extends DV> m)
- {
- map.putAll(m);
- }
- public DV remove(Object key)
- {
- return map.remove(key);
- }
- public int size()
- {
- return map.size();
- }
- public SortedMap<DK,DV> subMap(DK fromKey, DK toKey)
- {
- return subMap(fromKey, true, toKey, false);
- }
- public NavigableMap<DK,DV> subMap(DK fromKey, boolean fromInclusive,
- DK toKey, boolean toInclusive)
- {
- return new DescendingMap(map.subMap(fromKey, fromInclusive,
- toKey, toInclusive));
- }
- public SortedMap<DK,DV> tailMap(DK fromKey)
- {
- return tailMap(fromKey, true);
- }
- public NavigableMap<DK,DV> tailMap(DK fromKey, boolean inclusive)
- {
- return new DescendingMap(map.headMap(fromKey, inclusive));
- }
- public String toString()
- {
- CPStringBuilder r = new CPStringBuilder("{");
- final Iterator<Entry<DK,DV>> it = entrySet().iterator();
- while (it.hasNext())
- {
- final Entry<DK,DV> e = it.next();
- r.append(e.getKey());
- r.append('=');
- r.append(e.getValue());
- r.append(", ");
- }
- r.replace(r.length() - 2, r.length(), "}");
- return r.toString();
- }
- public Collection<DV> values()
- {
- if (values == null)
- // Create an AbstractCollection with custom implementations of those
- // methods that can be overriden easily and efficiently.
- values = new AbstractCollection()
- {
- public int size()
- {
- return DescendingMap.this.size();
- }
- public Iterator<DV> iterator()
- {
- return new Iterator<DV>()
- {
- /** The last Entry returned by a next() call. */
- private Entry<DK,DV> last;
- /** The next entry that should be returned by next(). */
- private Entry<DK,DV> next = firstEntry();
- public boolean hasNext()
- {
- return next != null;
- }
- public DV next()
- {
- if (next == null)
- throw new NoSuchElementException();
- last = next;
- next = higherEntry(last.getKey());
- return last.getValue();
- }
- public void remove()
- {
- if (last == null)
- throw new IllegalStateException();
- DescendingMap.this.remove(last.getKey());
- last = null;
- }
- };
- }
- public void clear()
- {
- DescendingMap.this.clear();
- }
- };
- return values;
- }
- } // class DescendingMap
- /**
- * Implementation of {@link #keySet()}.
- */
- private class KeySet
- extends AbstractSet<K>
- {
- public int size()
- {
- return size;
- }
- public Iterator<K> iterator()
- {
- return new TreeIterator(KEYS);
- }
- public void clear()
- {
- TreeMap.this.clear();
- }
- public boolean contains(Object o)
- {
- return containsKey(o);
- }
- public boolean remove(Object key)
- {
- Node<K,V> n = getNode((K) key);
- if (n == nil)
- return false;
- removeNode(n);
- return true;
- }
- } // class KeySet
- /**
- * Implementation of {@link #navigableKeySet()}.
- *
- * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
- */
- private final class NavigableKeySet
- extends KeySet
- implements NavigableSet<K>
- {
- public K ceiling(K k)
- {
- return ceilingKey(k);
- }
- public Comparator<? super K> comparator()
- {
- return comparator;
- }
- public Iterator<K> descendingIterator()
- {
- return descendingSet().iterator();
- }
- public NavigableSet<K> descendingSet()
- {
- return new DescendingSet<K>(this);
- }
- public K first()
- {
- return firstKey();
- }
- public K floor(K k)
- {
- return floorKey(k);
- }
- public SortedSet<K> headSet(K to)
- {
- return headSet(to, false);
- }
- public NavigableSet<K> headSet(K to, boolean inclusive)
- {
- return headMap(to, inclusive).navigableKeySet();
- }
- public K higher(K k)
- {
- return higherKey(k);
- }
- public K last()
- {
- return lastKey();
- }
- public K lower(K k)
- {
- return lowerKey(k);
- }
- public K pollFirst()
- {
- return pollFirstEntry().getKey();
- }
- public K pollLast()
- {
- return pollLastEntry().getKey();
- }
- public SortedSet<K> subSet(K from, K to)
- {
- return subSet(from, true, to, false);
- }
- public NavigableSet<K> subSet(K from, boolean fromInclusive,
- K to, boolean toInclusive)
- {
- return subMap(from, fromInclusive,
- to, toInclusive).navigableKeySet();
- }
- public SortedSet<K> tailSet(K from)
- {
- return tailSet(from, true);
- }
- public NavigableSet<K> tailSet(K from, boolean inclusive)
- {
- return tailMap(from, inclusive).navigableKeySet();
- }
- } // class NavigableKeySet
- /**
- * Implementation of {@link #descendingSet()} and associated
- * derivatives. This class provides a view of the
- * original backing set in reverse order, and throws
- * {@link IllegalArgumentException} for attempts to
- * access beyond that range.
- *
- * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
- */
- private static final class DescendingSet<D>
- implements NavigableSet<D>
- {
- /**
- * The backing {@link NavigableSet}.
- */
- private NavigableSet<D> set;
- /**
- * Create a {@link DescendingSet} around the specified
- * set.
- *
- * @param map the set to wrap.
- */
- public DescendingSet(NavigableSet<D> set)
- {
- this.set = set;
- }
- public boolean add(D e)
- {
- return set.add(e);
- }
- public boolean addAll(Collection<? extends D> c)
- {
- return set.addAll(c);
- }
- public D ceiling(D e)
- {
- return set.floor(e);
- }
- public void clear()
- {
- set.clear();
- }
- public Comparator<? super D> comparator()
- {
- return Collections.reverseOrder(set.comparator());
- }
- public boolean contains(Object o)
- {
- return set.contains(o);
- }
- public boolean containsAll(Collection<?> c)
- {
- return set.containsAll(c);
- }
- public Iterator<D> descendingIterator()
- {
- return descendingSet().iterator();
- }
- public NavigableSet<D> descendingSet()
- {
- return set;
- }
- public boolean equals(Object o)
- {
- return set.equals(o);
- }
- public D first()
- {
- return set.last();
- }
- public D floor(D e)
- {
- return set.ceiling(e);
- }
- public int hashCode()
- {
- return set.hashCode();
- }
- public SortedSet<D> headSet(D to)
- {
- return headSet(to, false);
- }
- public NavigableSet<D> headSet(D to, boolean inclusive)
- {
- return new DescendingSet(set.tailSet(to, inclusive));
- }
- public D higher(D e)
- {
- return set.lower(e);
- }
- public boolean isEmpty()
- {
- return set.isEmpty();
- }
- public Iterator<D> iterator()
- {
- return new Iterator<D>()
- {
- /** The last element returned by a next() call. */
- private D last;
- /** The next element that should be returned by next(). */
- private D next = first();
- public boolean hasNext()
- {
- return next != null;
- }
- public D next()
- {
- if (next == null)
- throw new NoSuchElementException();
- last = next;
- next = higher(last);
- return last;
- }
- public void remove()
- {
- if (last == null)
- throw new IllegalStateException();
- DescendingSet.this.remove(last);
- last = null;
- }
- };
- }
- public D last()
- {
- return set.first();
- }
- public D lower(D e)
- {
- return set.higher(e);
- }
- public D pollFirst()
- {
- return set.pollLast();
- }
- public D pollLast()
- {
- return set.pollFirst();
- }
- public boolean remove(Object o)
- {
- return set.remove(o);
- }
- public boolean removeAll(Collection<?> c)
- {
- return set.removeAll(c);
- }
- public boolean retainAll(Collection<?> c)
- {
- return set.retainAll(c);
- }
- public int size()
- {
- return set.size();
- }
- public SortedSet<D> subSet(D from, D to)
- {
- return subSet(from, true, to, false);
- }
- public NavigableSet<D> subSet(D from, boolean fromInclusive,
- D to, boolean toInclusive)
- {
- return new DescendingSet(set.subSet(from, fromInclusive,
- to, toInclusive));
- }
- public SortedSet<D> tailSet(D from)
- {
- return tailSet(from, true);
- }
- public NavigableSet<D> tailSet(D from, boolean inclusive)
- {
- return new DescendingSet(set.headSet(from, inclusive));
- }
- public Object[] toArray()
- {
- D[] array = (D[]) set.toArray();
- Arrays.sort(array, comparator());
- return array;
- }
- public <T> T[] toArray(T[] a)
- {
- T[] array = set.toArray(a);
- Arrays.sort(array, (Comparator<? super T>) comparator());
- return array;
- }
- public String toString()
- {
- CPStringBuilder r = new CPStringBuilder("[");
- final Iterator<D> it = iterator();
- while (it.hasNext())
- {
- final D o = it.next();
- if (o == this)
- r.append("<this>");
- else
- r.append(o);
- r.append(", ");
- }
- r.replace(r.length() - 2, r.length(), "]");
- return r.toString();
- }
- } // class DescendingSet
- private class EntrySet
- extends AbstractSet<Entry<K,V>>
- {
- public int size()
- {
- return size;
- }
- public Iterator<Map.Entry<K,V>> iterator()
- {
- return new TreeIterator(ENTRIES);
- }
- public void clear()
- {
- TreeMap.this.clear();
- }
- public boolean contains(Object o)
- {
- if (! (o instanceof Map.Entry))
- return false;
- Map.Entry<K,V> me = (Map.Entry<K,V>) o;
- Node<K,V> n = getNode(me.getKey());
- return n != nil && AbstractSet.equals(me.getValue(), n.value);
- }
- public boolean remove(Object o)
- {
- if (! (o instanceof Map.Entry))
- return false;
- Map.Entry<K,V> me = (Map.Entry<K,V>) o;
- Node<K,V> n = getNode(me.getKey());
- if (n != nil && AbstractSet.equals(me.getValue(), n.value))
- {
- removeNode(n);
- return true;
- }
- return false;
- }
- }
- private final class NavigableEntrySet
- extends EntrySet
- implements NavigableSet<Entry<K,V>>
- {
- public Entry<K,V> ceiling(Entry<K,V> e)
- {
- return ceilingEntry(e.getKey());
- }
- public Comparator<? super Entry<K,V>> comparator()
- {
- return new Comparator<Entry<K,V>>()
- {
- public int compare(Entry<K,V> t1, Entry<K,V> t2)
- {
- return comparator.compare(t1.getKey(), t2.getKey());
- }
- };
- }
- public Iterator<Entry<K,V>> descendingIterator()
- {
- return descendingSet().iterator();
- }
- public NavigableSet<Entry<K,V>> descendingSet()
- {
- return new DescendingSet(this);
- }
- public Entry<K,V> first()
- {
- return firstEntry();
- }
- public Entry<K,V> floor(Entry<K,V> e)
- {
- return floorEntry(e.getKey());
- }
- public SortedSet<Entry<K,V>> headSet(Entry<K,V> to)
- {
- return headSet(to, false);
- }
- public NavigableSet<Entry<K,V>> headSet(Entry<K,V> to, boolean inclusive)
- {
- return (NavigableSet<Entry<K,V>>) headMap(to.getKey(), inclusive).entrySet();
- }
- public Entry<K,V> higher(Entry<K,V> e)
- {
- return higherEntry(e.getKey());
- }
- public Entry<K,V> last()
- {
- return lastEntry();
- }
- public Entry<K,V> lower(Entry<K,V> e)
- {
- return lowerEntry(e.getKey());
- }
- public Entry<K,V> pollFirst()
- {
- return pollFirstEntry();
- }
- public Entry<K,V> pollLast()
- {
- return pollLastEntry();
- }
- public SortedSet<Entry<K,V>> subSet(Entry<K,V> from, Entry<K,V> to)
- {
- return subSet(from, true, to, false);
- }
- public NavigableSet<Entry<K,V>> subSet(Entry<K,V> from, boolean fromInclusive,
- Entry<K,V> to, boolean toInclusive)
- {
- return (NavigableSet<Entry<K,V>>) subMap(from.getKey(), fromInclusive,
- to.getKey(), toInclusive).entrySet();
- }
- public SortedSet<Entry<K,V>> tailSet(Entry<K,V> from)
- {
- return tailSet(from, true);
- }
- public NavigableSet<Entry<K,V>> tailSet(Entry<K,V> from, boolean inclusive)
- {
- return (NavigableSet<Entry<K,V>>) tailMap(from.getKey(), inclusive).navigableKeySet();
- }
- } // class NavigableEntrySet
- } // class TreeMap
|