TreeMap.java 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323
  1. /* TreeMap.java -- a class providing a basic Red-Black Tree data structure,
  2. mapping Object --> Object
  3. Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006 Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.util;
  33. import gnu.java.lang.CPStringBuilder;
  34. import java.io.IOException;
  35. import java.io.ObjectInputStream;
  36. import java.io.ObjectOutputStream;
  37. import java.io.Serializable;
  38. /**
  39. * This class provides a red-black tree implementation of the SortedMap
  40. * interface. Elements in the Map will be sorted by either a user-provided
  41. * Comparator object, or by the natural ordering of the keys.
  42. *
  43. * The algorithms are adopted from Corman, Leiserson, and Rivest's
  44. * <i>Introduction to Algorithms.</i> TreeMap guarantees O(log n)
  45. * insertion and deletion of elements. That being said, there is a large
  46. * enough constant coefficient in front of that "log n" (overhead involved
  47. * in keeping the tree balanced), that TreeMap may not be the best choice
  48. * for small collections. If something is already sorted, you may want to
  49. * just use a LinkedHashMap to maintain the order while providing O(1) access.
  50. *
  51. * TreeMap is a part of the JDK1.2 Collections API. Null keys are allowed
  52. * only if a Comparator is used which can deal with them; natural ordering
  53. * cannot cope with null. Null values are always allowed. Note that the
  54. * ordering must be <i>consistent with equals</i> to correctly implement
  55. * the Map interface. If this condition is violated, the map is still
  56. * well-behaved, but you may have suprising results when comparing it to
  57. * other maps.<p>
  58. *
  59. * This implementation is not synchronized. If you need to share this between
  60. * multiple threads, do something like:<br>
  61. * <code>SortedMap m
  62. * = Collections.synchronizedSortedMap(new TreeMap(...));</code><p>
  63. *
  64. * The iterators are <i>fail-fast</i>, meaning that any structural
  65. * modification, except for <code>remove()</code> called on the iterator
  66. * itself, cause the iterator to throw a
  67. * <code>ConcurrentModificationException</code> rather than exhibit
  68. * non-deterministic behavior.
  69. *
  70. * @author Jon Zeppieri
  71. * @author Bryce McKinlay
  72. * @author Eric Blake (ebb9@email.byu.edu)
  73. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  74. * @see Map
  75. * @see HashMap
  76. * @see Hashtable
  77. * @see LinkedHashMap
  78. * @see Comparable
  79. * @see Comparator
  80. * @see Collection
  81. * @see Collections#synchronizedSortedMap(SortedMap)
  82. * @since 1.2
  83. * @status updated to 1.6
  84. */
  85. public class TreeMap<K, V> extends AbstractMap<K, V>
  86. implements NavigableMap<K, V>, Cloneable, Serializable
  87. {
  88. // Implementation note:
  89. // A red-black tree is a binary search tree with the additional properties
  90. // that all paths to a leaf node visit the same number of black nodes,
  91. // and no red node has red children. To avoid some null-pointer checks,
  92. // we use the special node nil which is always black, has no relatives,
  93. // and has key and value of null (but is not equal to a mapping of null).
  94. /**
  95. * Compatible with JDK 1.2.
  96. */
  97. private static final long serialVersionUID = 919286545866124006L;
  98. /**
  99. * Color status of a node. Package visible for use by nested classes.
  100. */
  101. static final int RED = -1,
  102. BLACK = 1;
  103. /**
  104. * Sentinal node, used to avoid null checks for corner cases and make the
  105. * delete rebalance code simpler. The rebalance code must never assign
  106. * the parent, left, or right of nil, but may safely reassign the color
  107. * to be black. This object must never be used as a key in a TreeMap, or
  108. * it will break bounds checking of a SubMap.
  109. */
  110. static final Node nil = new Node(null, null, BLACK);
  111. static
  112. {
  113. // Nil is self-referential, so we must initialize it after creation.
  114. nil.parent = nil;
  115. nil.left = nil;
  116. nil.right = nil;
  117. }
  118. /**
  119. * The root node of this TreeMap.
  120. */
  121. private transient Node root;
  122. /**
  123. * The size of this TreeMap. Package visible for use by nested classes.
  124. */
  125. transient int size;
  126. /**
  127. * The cache for {@link #entrySet()}.
  128. */
  129. private transient Set<Map.Entry<K,V>> entries;
  130. /**
  131. * The cache for {@link #descendingMap()}.
  132. */
  133. private transient NavigableMap<K,V> descendingMap;
  134. /**
  135. * The cache for {@link #navigableKeySet()}.
  136. */
  137. private transient NavigableSet<K> nKeys;
  138. /**
  139. * Counts the number of modifications this TreeMap has undergone, used
  140. * by Iterators to know when to throw ConcurrentModificationExceptions.
  141. * Package visible for use by nested classes.
  142. */
  143. transient int modCount;
  144. /**
  145. * This TreeMap's comparator, or null for natural ordering.
  146. * Package visible for use by nested classes.
  147. * @serial the comparator ordering this tree, or null
  148. */
  149. final Comparator<? super K> comparator;
  150. /**
  151. * Class to represent an entry in the tree. Holds a single key-value pair,
  152. * plus pointers to parent and child nodes.
  153. *
  154. * @author Eric Blake (ebb9@email.byu.edu)
  155. */
  156. private static final class Node<K, V> extends AbstractMap.SimpleEntry<K, V>
  157. {
  158. // All fields package visible for use by nested classes.
  159. /** The color of this node. */
  160. int color;
  161. /** The left child node. */
  162. Node<K, V> left = nil;
  163. /** The right child node. */
  164. Node<K, V> right = nil;
  165. /** The parent node. */
  166. Node<K, V> parent = nil;
  167. /**
  168. * Simple constructor.
  169. * @param key the key
  170. * @param value the value
  171. */
  172. Node(K key, V value, int color)
  173. {
  174. super(key, value);
  175. this.color = color;
  176. }
  177. }
  178. /**
  179. * Instantiate a new TreeMap with no elements, using the keys' natural
  180. * ordering to sort. All entries in the map must have a key which implements
  181. * Comparable, and which are <i>mutually comparable</i>, otherwise map
  182. * operations may throw a {@link ClassCastException}. Attempts to use
  183. * a null key will throw a {@link NullPointerException}.
  184. *
  185. * @see Comparable
  186. */
  187. public TreeMap()
  188. {
  189. this((Comparator) null);
  190. }
  191. /**
  192. * Instantiate a new TreeMap with no elements, using the provided comparator
  193. * to sort. All entries in the map must have keys which are mutually
  194. * comparable by the Comparator, otherwise map operations may throw a
  195. * {@link ClassCastException}.
  196. *
  197. * @param c the sort order for the keys of this map, or null
  198. * for the natural order
  199. */
  200. public TreeMap(Comparator<? super K> c)
  201. {
  202. comparator = c;
  203. fabricateTree(0);
  204. }
  205. /**
  206. * Instantiate a new TreeMap, initializing it with all of the elements in
  207. * the provided Map. The elements will be sorted using the natural
  208. * ordering of the keys. This algorithm runs in n*log(n) time. All entries
  209. * in the map must have keys which implement Comparable and are mutually
  210. * comparable, otherwise map operations may throw a
  211. * {@link ClassCastException}.
  212. *
  213. * @param map a Map, whose entries will be put into this TreeMap
  214. * @throws ClassCastException if the keys in the provided Map are not
  215. * comparable
  216. * @throws NullPointerException if map is null
  217. * @see Comparable
  218. */
  219. public TreeMap(Map<? extends K, ? extends V> map)
  220. {
  221. this((Comparator) null);
  222. putAll(map);
  223. }
  224. /**
  225. * Instantiate a new TreeMap, initializing it with all of the elements in
  226. * the provided SortedMap. The elements will be sorted using the same
  227. * comparator as in the provided SortedMap. This runs in linear time.
  228. *
  229. * @param sm a SortedMap, whose entries will be put into this TreeMap
  230. * @throws NullPointerException if sm is null
  231. */
  232. public TreeMap(SortedMap<K, ? extends V> sm)
  233. {
  234. this(sm.comparator());
  235. int pos = sm.size();
  236. Iterator itr = sm.entrySet().iterator();
  237. fabricateTree(pos);
  238. Node node = firstNode();
  239. while (--pos >= 0)
  240. {
  241. Map.Entry me = (Map.Entry) itr.next();
  242. node.key = me.getKey();
  243. node.value = me.getValue();
  244. node = successor(node);
  245. }
  246. }
  247. /**
  248. * Clears the Map so it has no keys. This is O(1).
  249. */
  250. public void clear()
  251. {
  252. if (size > 0)
  253. {
  254. modCount++;
  255. root = nil;
  256. size = 0;
  257. }
  258. }
  259. /**
  260. * Returns a shallow clone of this TreeMap. The Map itself is cloned,
  261. * but its contents are not.
  262. *
  263. * @return the clone
  264. */
  265. public Object clone()
  266. {
  267. TreeMap copy = null;
  268. try
  269. {
  270. copy = (TreeMap) super.clone();
  271. }
  272. catch (CloneNotSupportedException x)
  273. {
  274. }
  275. copy.entries = null;
  276. copy.fabricateTree(size);
  277. Node node = firstNode();
  278. Node cnode = copy.firstNode();
  279. while (node != nil)
  280. {
  281. cnode.key = node.key;
  282. cnode.value = node.value;
  283. node = successor(node);
  284. cnode = copy.successor(cnode);
  285. }
  286. return copy;
  287. }
  288. /**
  289. * Return the comparator used to sort this map, or null if it is by
  290. * natural order.
  291. *
  292. * @return the map's comparator
  293. */
  294. public Comparator<? super K> comparator()
  295. {
  296. return comparator;
  297. }
  298. /**
  299. * Returns true if the map contains a mapping for the given key.
  300. *
  301. * @param key the key to look for
  302. * @return true if the key has a mapping
  303. * @throws ClassCastException if key is not comparable to map elements
  304. * @throws NullPointerException if key is null and the comparator is not
  305. * tolerant of nulls
  306. */
  307. public boolean containsKey(Object key)
  308. {
  309. return getNode((K) key) != nil;
  310. }
  311. /**
  312. * Returns true if the map contains at least one mapping to the given value.
  313. * This requires linear time.
  314. *
  315. * @param value the value to look for
  316. * @return true if the value appears in a mapping
  317. */
  318. public boolean containsValue(Object value)
  319. {
  320. Node node = firstNode();
  321. while (node != nil)
  322. {
  323. if (equals(value, node.value))
  324. return true;
  325. node = successor(node);
  326. }
  327. return false;
  328. }
  329. /**
  330. * Returns a "set view" of this TreeMap's entries. The set is backed by
  331. * the TreeMap, so changes in one show up in the other. The set supports
  332. * element removal, but not element addition.<p>
  333. *
  334. * Note that the iterators for all three views, from keySet(), entrySet(),
  335. * and values(), traverse the TreeMap in sorted sequence.
  336. *
  337. * @return a set view of the entries
  338. * @see #keySet()
  339. * @see #values()
  340. * @see Map.Entry
  341. */
  342. public Set<Map.Entry<K,V>> entrySet()
  343. {
  344. if (entries == null)
  345. // Create an AbstractSet with custom implementations of those methods
  346. // that can be overriden easily and efficiently.
  347. entries = new NavigableEntrySet();
  348. return entries;
  349. }
  350. /**
  351. * Returns the first (lowest) key in the map.
  352. *
  353. * @return the first key
  354. * @throws NoSuchElementException if the map is empty
  355. */
  356. public K firstKey()
  357. {
  358. if (root == nil)
  359. throw new NoSuchElementException();
  360. return firstNode().key;
  361. }
  362. /**
  363. * Return the value in this TreeMap associated with the supplied key,
  364. * or <code>null</code> if the key maps to nothing. NOTE: Since the value
  365. * could also be null, you must use containsKey to see if this key
  366. * actually maps to something.
  367. *
  368. * @param key the key for which to fetch an associated value
  369. * @return what the key maps to, if present
  370. * @throws ClassCastException if key is not comparable to elements in the map
  371. * @throws NullPointerException if key is null but the comparator does not
  372. * tolerate nulls
  373. * @see #put(Object, Object)
  374. * @see #containsKey(Object)
  375. */
  376. public V get(Object key)
  377. {
  378. // Exploit fact that nil.value == null.
  379. return getNode((K) key).value;
  380. }
  381. /**
  382. * Returns a view of this Map including all entries with keys less than
  383. * <code>toKey</code>. The returned map is backed by the original, so changes
  384. * in one appear in the other. The submap will throw an
  385. * {@link IllegalArgumentException} for any attempt to access or add an
  386. * element beyond the specified cutoff. The returned map does not include
  387. * the endpoint; if you want inclusion, pass the successor element
  388. * or call <code>headMap(toKey, true)</code>. This is equivalent to
  389. * calling <code>headMap(toKey, false)</code>.
  390. *
  391. * @param toKey the (exclusive) cutoff point
  392. * @return a view of the map less than the cutoff
  393. * @throws ClassCastException if <code>toKey</code> is not compatible with
  394. * the comparator (or is not Comparable, for natural ordering)
  395. * @throws NullPointerException if toKey is null, but the comparator does not
  396. * tolerate null elements
  397. */
  398. public SortedMap<K, V> headMap(K toKey)
  399. {
  400. return headMap(toKey, false);
  401. }
  402. /**
  403. * Returns a view of this Map including all entries with keys less than
  404. * (or equal to, if <code>inclusive</code> is true) <code>toKey</code>.
  405. * The returned map is backed by the original, so changes in one appear
  406. * in the other. The submap will throw an {@link IllegalArgumentException}
  407. * for any attempt to access or add an element beyond the specified cutoff.
  408. *
  409. * @param toKey the cutoff point
  410. * @param inclusive true if the cutoff point should be included.
  411. * @return a view of the map less than (or equal to, if <code>inclusive</code>
  412. * is true) the cutoff.
  413. * @throws ClassCastException if <code>toKey</code> is not compatible with
  414. * the comparator (or is not Comparable, for natural ordering)
  415. * @throws NullPointerException if toKey is null, but the comparator does not
  416. * tolerate null elements
  417. */
  418. public NavigableMap<K, V> headMap(K toKey, boolean inclusive)
  419. {
  420. return new SubMap((K)(Object)nil, inclusive
  421. ? successor(getNode(toKey)).key : toKey);
  422. }
  423. /**
  424. * Returns a "set view" of this TreeMap's keys. The set is backed by the
  425. * TreeMap, so changes in one show up in the other. The set supports
  426. * element removal, but not element addition.
  427. *
  428. * @return a set view of the keys
  429. * @see #values()
  430. * @see #entrySet()
  431. */
  432. public Set<K> keySet()
  433. {
  434. if (keys == null)
  435. // Create an AbstractSet with custom implementations of those methods
  436. // that can be overriden easily and efficiently.
  437. keys = new KeySet();
  438. return keys;
  439. }
  440. /**
  441. * Returns the last (highest) key in the map.
  442. *
  443. * @return the last key
  444. * @throws NoSuchElementException if the map is empty
  445. */
  446. public K lastKey()
  447. {
  448. if (root == nil)
  449. throw new NoSuchElementException("empty");
  450. return lastNode().key;
  451. }
  452. /**
  453. * Puts the supplied value into the Map, mapped by the supplied key.
  454. * The value may be retrieved by any object which <code>equals()</code>
  455. * this key. NOTE: Since the prior value could also be null, you must
  456. * first use containsKey if you want to see if you are replacing the
  457. * key's mapping.
  458. *
  459. * @param key the key used to locate the value
  460. * @param value the value to be stored in the Map
  461. * @return the prior mapping of the key, or null if there was none
  462. * @throws ClassCastException if key is not comparable to current map keys
  463. * @throws NullPointerException if key is null, but the comparator does
  464. * not tolerate nulls
  465. * @see #get(Object)
  466. * @see Object#equals(Object)
  467. */
  468. public V put(K key, V value)
  469. {
  470. Node<K,V> current = root;
  471. Node<K,V> parent = nil;
  472. int comparison = 0;
  473. // Find new node's parent.
  474. while (current != nil)
  475. {
  476. parent = current;
  477. comparison = compare(key, current.key);
  478. if (comparison > 0)
  479. current = current.right;
  480. else if (comparison < 0)
  481. current = current.left;
  482. else // Key already in tree.
  483. return current.setValue(value);
  484. }
  485. // Set up new node.
  486. Node n = new Node(key, value, RED);
  487. n.parent = parent;
  488. // Insert node in tree.
  489. modCount++;
  490. size++;
  491. if (parent == nil)
  492. {
  493. // Special case inserting into an empty tree.
  494. root = n;
  495. return null;
  496. }
  497. if (comparison > 0)
  498. parent.right = n;
  499. else
  500. parent.left = n;
  501. // Rebalance after insert.
  502. insertFixup(n);
  503. return null;
  504. }
  505. /**
  506. * Copies all elements of the given map into this TreeMap. If this map
  507. * already has a mapping for a key, the new mapping replaces the current
  508. * one.
  509. *
  510. * @param m the map to be added
  511. * @throws ClassCastException if a key in m is not comparable with keys
  512. * in the map
  513. * @throws NullPointerException if a key in m is null, and the comparator
  514. * does not tolerate nulls
  515. */
  516. public void putAll(Map<? extends K, ? extends V> m)
  517. {
  518. Iterator itr = m.entrySet().iterator();
  519. int pos = m.size();
  520. while (--pos >= 0)
  521. {
  522. Map.Entry<K,V> e = (Map.Entry<K,V>) itr.next();
  523. put(e.getKey(), e.getValue());
  524. }
  525. }
  526. /**
  527. * Removes from the TreeMap and returns the value which is mapped by the
  528. * supplied key. If the key maps to nothing, then the TreeMap remains
  529. * unchanged, and <code>null</code> is returned. NOTE: Since the value
  530. * could also be null, you must use containsKey to see if you are
  531. * actually removing a mapping.
  532. *
  533. * @param key the key used to locate the value to remove
  534. * @return whatever the key mapped to, if present
  535. * @throws ClassCastException if key is not comparable to current map keys
  536. * @throws NullPointerException if key is null, but the comparator does
  537. * not tolerate nulls
  538. */
  539. public V remove(Object key)
  540. {
  541. Node<K, V> n = getNode((K)key);
  542. if (n == nil)
  543. return null;
  544. // Note: removeNode can alter the contents of n, so save value now.
  545. V result = n.value;
  546. removeNode(n);
  547. return result;
  548. }
  549. /**
  550. * Returns the number of key-value mappings currently in this Map.
  551. *
  552. * @return the size
  553. */
  554. public int size()
  555. {
  556. return size;
  557. }
  558. /**
  559. * Returns a view of this Map including all entries with keys greater or
  560. * equal to <code>fromKey</code> and less than <code>toKey</code> (a
  561. * half-open interval). The returned map is backed by the original, so
  562. * changes in one appear in the other. The submap will throw an
  563. * {@link IllegalArgumentException} for any attempt to access or add an
  564. * element beyond the specified cutoffs. The returned map includes the low
  565. * endpoint but not the high; if you want to reverse this behavior on
  566. * either end, pass in the successor element or call
  567. * {@link #subMap(K,boolean,K,boolean)}. This call is equivalent to
  568. * <code>subMap(fromKey, true, toKey, false)</code>.
  569. *
  570. * @param fromKey the (inclusive) low cutoff point
  571. * @param toKey the (exclusive) high cutoff point
  572. * @return a view of the map between the cutoffs
  573. * @throws ClassCastException if either cutoff is not compatible with
  574. * the comparator (or is not Comparable, for natural ordering)
  575. * @throws NullPointerException if fromKey or toKey is null, but the
  576. * comparator does not tolerate null elements
  577. * @throws IllegalArgumentException if fromKey is greater than toKey
  578. */
  579. public SortedMap<K, V> subMap(K fromKey, K toKey)
  580. {
  581. return subMap(fromKey, true, toKey, false);
  582. }
  583. /**
  584. * Returns a view of this Map including all entries with keys greater (or
  585. * equal to, if <code>fromInclusive</code> is true) <code>fromKey</code> and
  586. * less than (or equal to, if <code>toInclusive</code> is true)
  587. * <code>toKey</code>. The returned map is backed by the original, so
  588. * changes in one appear in the other. The submap will throw an
  589. * {@link IllegalArgumentException} for any attempt to access or add an
  590. * element beyond the specified cutoffs.
  591. *
  592. * @param fromKey the low cutoff point
  593. * @param fromInclusive true if the low cutoff point should be included.
  594. * @param toKey the high cutoff point
  595. * @param toInclusive true if the high cutoff point should be included.
  596. * @return a view of the map for the specified range.
  597. * @throws ClassCastException if either cutoff is not compatible with
  598. * the comparator (or is not Comparable, for natural ordering)
  599. * @throws NullPointerException if fromKey or toKey is null, but the
  600. * comparator does not tolerate null elements
  601. * @throws IllegalArgumentException if fromKey is greater than toKey
  602. */
  603. public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive,
  604. K toKey, boolean toInclusive)
  605. {
  606. return new SubMap(fromInclusive ? fromKey : successor(getNode(fromKey)).key,
  607. toInclusive ? successor(getNode(toKey)).key : toKey);
  608. }
  609. /**
  610. * Returns a view of this Map including all entries with keys greater or
  611. * equal to <code>fromKey</code>. The returned map is backed by the
  612. * original, so changes in one appear in the other. The submap will throw an
  613. * {@link IllegalArgumentException} for any attempt to access or add an
  614. * element beyond the specified cutoff. The returned map includes the
  615. * endpoint; if you want to exclude it, pass in the successor element.
  616. * This is equivalent to calling <code>tailMap(fromKey, true)</code>.
  617. *
  618. * @param fromKey the (inclusive) low cutoff point
  619. * @return a view of the map above the cutoff
  620. * @throws ClassCastException if <code>fromKey</code> is not compatible with
  621. * the comparator (or is not Comparable, for natural ordering)
  622. * @throws NullPointerException if fromKey is null, but the comparator
  623. * does not tolerate null elements
  624. */
  625. public SortedMap<K, V> tailMap(K fromKey)
  626. {
  627. return tailMap(fromKey, true);
  628. }
  629. /**
  630. * Returns a view of this Map including all entries with keys greater or
  631. * equal to <code>fromKey</code>. The returned map is backed by the
  632. * original, so changes in one appear in the other. The submap will throw an
  633. * {@link IllegalArgumentException} for any attempt to access or add an
  634. * element beyond the specified cutoff. The returned map includes the
  635. * endpoint; if you want to exclude it, pass in the successor element.
  636. *
  637. * @param fromKey the low cutoff point
  638. * @param inclusive true if the cutoff point should be included.
  639. * @return a view of the map above the cutoff
  640. * @throws ClassCastException if <code>fromKey</code> is not compatible with
  641. * the comparator (or is not Comparable, for natural ordering)
  642. * @throws NullPointerException if fromKey is null, but the comparator
  643. * does not tolerate null elements
  644. */
  645. public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive)
  646. {
  647. return new SubMap(inclusive ? fromKey : successor(getNode(fromKey)).key,
  648. (K)(Object)nil);
  649. }
  650. /**
  651. * Returns a "collection view" (or "bag view") of this TreeMap's values.
  652. * The collection is backed by the TreeMap, so changes in one show up
  653. * in the other. The collection supports element removal, but not element
  654. * addition.
  655. *
  656. * @return a bag view of the values
  657. * @see #keySet()
  658. * @see #entrySet()
  659. */
  660. public Collection<V> values()
  661. {
  662. if (values == null)
  663. // We don't bother overriding many of the optional methods, as doing so
  664. // wouldn't provide any significant performance advantage.
  665. values = new AbstractCollection<V>()
  666. {
  667. public int size()
  668. {
  669. return size;
  670. }
  671. public Iterator<V> iterator()
  672. {
  673. return new TreeIterator(VALUES);
  674. }
  675. public void clear()
  676. {
  677. TreeMap.this.clear();
  678. }
  679. };
  680. return values;
  681. }
  682. /**
  683. * Compares two elements by the set comparator, or by natural ordering.
  684. * Package visible for use by nested classes.
  685. *
  686. * @param o1 the first object
  687. * @param o2 the second object
  688. * @throws ClassCastException if o1 and o2 are not mutually comparable,
  689. * or are not Comparable with natural ordering
  690. * @throws NullPointerException if o1 or o2 is null with natural ordering
  691. */
  692. final int compare(K o1, K o2)
  693. {
  694. return (comparator == null
  695. ? ((Comparable) o1).compareTo(o2)
  696. : comparator.compare(o1, o2));
  697. }
  698. /**
  699. * Maintain red-black balance after deleting a node.
  700. *
  701. * @param node the child of the node just deleted, possibly nil
  702. * @param parent the parent of the node just deleted, never nil
  703. */
  704. private void deleteFixup(Node<K,V> node, Node<K,V> parent)
  705. {
  706. // if (parent == nil)
  707. // throw new InternalError();
  708. // If a black node has been removed, we need to rebalance to avoid
  709. // violating the "same number of black nodes on any path" rule. If
  710. // node is red, we can simply recolor it black and all is well.
  711. while (node != root && node.color == BLACK)
  712. {
  713. if (node == parent.left)
  714. {
  715. // Rebalance left side.
  716. Node<K,V> sibling = parent.right;
  717. // if (sibling == nil)
  718. // throw new InternalError();
  719. if (sibling.color == RED)
  720. {
  721. // Case 1: Sibling is red.
  722. // Recolor sibling and parent, and rotate parent left.
  723. sibling.color = BLACK;
  724. parent.color = RED;
  725. rotateLeft(parent);
  726. sibling = parent.right;
  727. }
  728. if (sibling.left.color == BLACK && sibling.right.color == BLACK)
  729. {
  730. // Case 2: Sibling has no red children.
  731. // Recolor sibling, and move to parent.
  732. sibling.color = RED;
  733. node = parent;
  734. parent = parent.parent;
  735. }
  736. else
  737. {
  738. if (sibling.right.color == BLACK)
  739. {
  740. // Case 3: Sibling has red left child.
  741. // Recolor sibling and left child, rotate sibling right.
  742. sibling.left.color = BLACK;
  743. sibling.color = RED;
  744. rotateRight(sibling);
  745. sibling = parent.right;
  746. }
  747. // Case 4: Sibling has red right child. Recolor sibling,
  748. // right child, and parent, and rotate parent left.
  749. sibling.color = parent.color;
  750. parent.color = BLACK;
  751. sibling.right.color = BLACK;
  752. rotateLeft(parent);
  753. node = root; // Finished.
  754. }
  755. }
  756. else
  757. {
  758. // Symmetric "mirror" of left-side case.
  759. Node<K,V> sibling = parent.left;
  760. // if (sibling == nil)
  761. // throw new InternalError();
  762. if (sibling.color == RED)
  763. {
  764. // Case 1: Sibling is red.
  765. // Recolor sibling and parent, and rotate parent right.
  766. sibling.color = BLACK;
  767. parent.color = RED;
  768. rotateRight(parent);
  769. sibling = parent.left;
  770. }
  771. if (sibling.right.color == BLACK && sibling.left.color == BLACK)
  772. {
  773. // Case 2: Sibling has no red children.
  774. // Recolor sibling, and move to parent.
  775. sibling.color = RED;
  776. node = parent;
  777. parent = parent.parent;
  778. }
  779. else
  780. {
  781. if (sibling.left.color == BLACK)
  782. {
  783. // Case 3: Sibling has red right child.
  784. // Recolor sibling and right child, rotate sibling left.
  785. sibling.right.color = BLACK;
  786. sibling.color = RED;
  787. rotateLeft(sibling);
  788. sibling = parent.left;
  789. }
  790. // Case 4: Sibling has red left child. Recolor sibling,
  791. // left child, and parent, and rotate parent right.
  792. sibling.color = parent.color;
  793. parent.color = BLACK;
  794. sibling.left.color = BLACK;
  795. rotateRight(parent);
  796. node = root; // Finished.
  797. }
  798. }
  799. }
  800. node.color = BLACK;
  801. }
  802. /**
  803. * Construct a perfectly balanced tree consisting of n "blank" nodes. This
  804. * permits a tree to be generated from pre-sorted input in linear time.
  805. *
  806. * @param count the number of blank nodes, non-negative
  807. */
  808. private void fabricateTree(final int count)
  809. {
  810. if (count == 0)
  811. {
  812. root = nil;
  813. size = 0;
  814. return;
  815. }
  816. // We color every row of nodes black, except for the overflow nodes.
  817. // I believe that this is the optimal arrangement. We construct the tree
  818. // in place by temporarily linking each node to the next node in the row,
  819. // then updating those links to the children when working on the next row.
  820. // Make the root node.
  821. root = new Node(null, null, BLACK);
  822. size = count;
  823. Node row = root;
  824. int rowsize;
  825. // Fill each row that is completely full of nodes.
  826. for (rowsize = 2; rowsize + rowsize <= count; rowsize <<= 1)
  827. {
  828. Node parent = row;
  829. Node last = null;
  830. for (int i = 0; i < rowsize; i += 2)
  831. {
  832. Node left = new Node(null, null, BLACK);
  833. Node right = new Node(null, null, BLACK);
  834. left.parent = parent;
  835. left.right = right;
  836. right.parent = parent;
  837. parent.left = left;
  838. Node next = parent.right;
  839. parent.right = right;
  840. parent = next;
  841. if (last != null)
  842. last.right = left;
  843. last = right;
  844. }
  845. row = row.left;
  846. }
  847. // Now do the partial final row in red.
  848. int overflow = count - rowsize;
  849. Node parent = row;
  850. int i;
  851. for (i = 0; i < overflow; i += 2)
  852. {
  853. Node left = new Node(null, null, RED);
  854. Node right = new Node(null, null, RED);
  855. left.parent = parent;
  856. right.parent = parent;
  857. parent.left = left;
  858. Node next = parent.right;
  859. parent.right = right;
  860. parent = next;
  861. }
  862. // Add a lone left node if necessary.
  863. if (i - overflow == 0)
  864. {
  865. Node left = new Node(null, null, RED);
  866. left.parent = parent;
  867. parent.left = left;
  868. parent = parent.right;
  869. left.parent.right = nil;
  870. }
  871. // Unlink the remaining nodes of the previous row.
  872. while (parent != nil)
  873. {
  874. Node next = parent.right;
  875. parent.right = nil;
  876. parent = next;
  877. }
  878. }
  879. /**
  880. * Returns the first sorted node in the map, or nil if empty. Package
  881. * visible for use by nested classes.
  882. *
  883. * @return the first node
  884. */
  885. final Node<K, V> firstNode()
  886. {
  887. // Exploit fact that nil.left == nil.
  888. Node node = root;
  889. while (node.left != nil)
  890. node = node.left;
  891. return node;
  892. }
  893. /**
  894. * Return the TreeMap.Node associated with key, or the nil node if no such
  895. * node exists in the tree. Package visible for use by nested classes.
  896. *
  897. * @param key the key to search for
  898. * @return the node where the key is found, or nil
  899. */
  900. final Node<K, V> getNode(K key)
  901. {
  902. Node<K,V> current = root;
  903. while (current != nil)
  904. {
  905. int comparison = compare(key, current.key);
  906. if (comparison > 0)
  907. current = current.right;
  908. else if (comparison < 0)
  909. current = current.left;
  910. else
  911. return current;
  912. }
  913. return current;
  914. }
  915. /**
  916. * Find the "highest" node which is &lt; key. If key is nil, return last
  917. * node. Package visible for use by nested classes.
  918. *
  919. * @param key the upper bound, exclusive
  920. * @return the previous node
  921. */
  922. final Node<K,V> highestLessThan(K key)
  923. {
  924. return highestLessThan(key, false);
  925. }
  926. /**
  927. * Find the "highest" node which is &lt; (or equal to,
  928. * if <code>equal</code> is true) key. If key is nil,
  929. * return last node. Package visible for use by nested
  930. * classes.
  931. *
  932. * @param key the upper bound, exclusive
  933. * @param equal true if the key should be returned if found.
  934. * @return the previous node
  935. */
  936. final Node<K,V> highestLessThan(K key, boolean equal)
  937. {
  938. if (key == nil)
  939. return lastNode();
  940. Node<K,V> last = nil;
  941. Node<K,V> current = root;
  942. int comparison = 0;
  943. while (current != nil)
  944. {
  945. last = current;
  946. comparison = compare(key, current.key);
  947. if (comparison > 0)
  948. current = current.right;
  949. else if (comparison < 0)
  950. current = current.left;
  951. else // Exact match.
  952. return (equal ? last : predecessor(last));
  953. }
  954. return comparison < 0 ? predecessor(last) : last;
  955. }
  956. /**
  957. * Maintain red-black balance after inserting a new node.
  958. *
  959. * @param n the newly inserted node
  960. */
  961. private void insertFixup(Node<K,V> n)
  962. {
  963. // Only need to rebalance when parent is a RED node, and while at least
  964. // 2 levels deep into the tree (ie: node has a grandparent). Remember
  965. // that nil.color == BLACK.
  966. while (n.parent.color == RED && n.parent.parent != nil)
  967. {
  968. if (n.parent == n.parent.parent.left)
  969. {
  970. Node uncle = n.parent.parent.right;
  971. // Uncle may be nil, in which case it is BLACK.
  972. if (uncle.color == RED)
  973. {
  974. // Case 1. Uncle is RED: Change colors of parent, uncle,
  975. // and grandparent, and move n to grandparent.
  976. n.parent.color = BLACK;
  977. uncle.color = BLACK;
  978. uncle.parent.color = RED;
  979. n = uncle.parent;
  980. }
  981. else
  982. {
  983. if (n == n.parent.right)
  984. {
  985. // Case 2. Uncle is BLACK and x is right child.
  986. // Move n to parent, and rotate n left.
  987. n = n.parent;
  988. rotateLeft(n);
  989. }
  990. // Case 3. Uncle is BLACK and x is left child.
  991. // Recolor parent, grandparent, and rotate grandparent right.
  992. n.parent.color = BLACK;
  993. n.parent.parent.color = RED;
  994. rotateRight(n.parent.parent);
  995. }
  996. }
  997. else
  998. {
  999. // Mirror image of above code.
  1000. Node uncle = n.parent.parent.left;
  1001. // Uncle may be nil, in which case it is BLACK.
  1002. if (uncle.color == RED)
  1003. {
  1004. // Case 1. Uncle is RED: Change colors of parent, uncle,
  1005. // and grandparent, and move n to grandparent.
  1006. n.parent.color = BLACK;
  1007. uncle.color = BLACK;
  1008. uncle.parent.color = RED;
  1009. n = uncle.parent;
  1010. }
  1011. else
  1012. {
  1013. if (n == n.parent.left)
  1014. {
  1015. // Case 2. Uncle is BLACK and x is left child.
  1016. // Move n to parent, and rotate n right.
  1017. n = n.parent;
  1018. rotateRight(n);
  1019. }
  1020. // Case 3. Uncle is BLACK and x is right child.
  1021. // Recolor parent, grandparent, and rotate grandparent left.
  1022. n.parent.color = BLACK;
  1023. n.parent.parent.color = RED;
  1024. rotateLeft(n.parent.parent);
  1025. }
  1026. }
  1027. }
  1028. root.color = BLACK;
  1029. }
  1030. /**
  1031. * Returns the last sorted node in the map, or nil if empty.
  1032. *
  1033. * @return the last node
  1034. */
  1035. private Node<K,V> lastNode()
  1036. {
  1037. // Exploit fact that nil.right == nil.
  1038. Node node = root;
  1039. while (node.right != nil)
  1040. node = node.right;
  1041. return node;
  1042. }
  1043. /**
  1044. * Find the "lowest" node which is &gt;= key. If key is nil, return either
  1045. * nil or the first node, depending on the parameter first. Package visible
  1046. * for use by nested classes.
  1047. *
  1048. * @param key the lower bound, inclusive
  1049. * @param first true to return the first element instead of nil for nil key
  1050. * @return the next node
  1051. */
  1052. final Node<K,V> lowestGreaterThan(K key, boolean first)
  1053. {
  1054. return lowestGreaterThan(key, first, true);
  1055. }
  1056. /**
  1057. * Find the "lowest" node which is &gt; (or equal to, if <code>equal</code>
  1058. * is true) key. If key is nil, return either nil or the first node, depending
  1059. * on the parameter first. Package visible for use by nested classes.
  1060. *
  1061. * @param key the lower bound, inclusive
  1062. * @param first true to return the first element instead of nil for nil key
  1063. * @param equal true if the key should be returned if found.
  1064. * @return the next node
  1065. */
  1066. final Node<K,V> lowestGreaterThan(K key, boolean first, boolean equal)
  1067. {
  1068. if (key == nil)
  1069. return first ? firstNode() : nil;
  1070. Node<K,V> last = nil;
  1071. Node<K,V> current = root;
  1072. int comparison = 0;
  1073. while (current != nil)
  1074. {
  1075. last = current;
  1076. comparison = compare(key, current.key);
  1077. if (comparison > 0)
  1078. current = current.right;
  1079. else if (comparison < 0)
  1080. current = current.left;
  1081. else
  1082. return (equal ? current : successor(current));
  1083. }
  1084. return comparison > 0 ? successor(last) : last;
  1085. }
  1086. /**
  1087. * Return the node preceding the given one, or nil if there isn't one.
  1088. *
  1089. * @param node the current node, not nil
  1090. * @return the prior node in sorted order
  1091. */
  1092. private Node<K,V> predecessor(Node<K,V> node)
  1093. {
  1094. if (node.left != nil)
  1095. {
  1096. node = node.left;
  1097. while (node.right != nil)
  1098. node = node.right;
  1099. return node;
  1100. }
  1101. Node parent = node.parent;
  1102. // Exploit fact that nil.left == nil and node is non-nil.
  1103. while (node == parent.left)
  1104. {
  1105. node = parent;
  1106. parent = node.parent;
  1107. }
  1108. return parent;
  1109. }
  1110. /**
  1111. * Construct a tree from sorted keys in linear time. Package visible for
  1112. * use by TreeSet.
  1113. *
  1114. * @param s the stream to read from
  1115. * @param count the number of keys to read
  1116. * @param readValues true to read values, false to insert "" as the value
  1117. * @throws ClassNotFoundException if the underlying stream fails
  1118. * @throws IOException if the underlying stream fails
  1119. * @see #readObject(ObjectInputStream)
  1120. * @see TreeSet#readObject(ObjectInputStream)
  1121. */
  1122. final void putFromObjStream(ObjectInputStream s, int count,
  1123. boolean readValues)
  1124. throws IOException, ClassNotFoundException
  1125. {
  1126. fabricateTree(count);
  1127. Node node = firstNode();
  1128. while (--count >= 0)
  1129. {
  1130. node.key = s.readObject();
  1131. node.value = readValues ? s.readObject() : "";
  1132. node = successor(node);
  1133. }
  1134. }
  1135. /**
  1136. * Construct a tree from sorted keys in linear time, with values of "".
  1137. * Package visible for use by TreeSet, which uses a value type of String.
  1138. *
  1139. * @param keys the iterator over the sorted keys
  1140. * @param count the number of nodes to insert
  1141. * @see TreeSet#TreeSet(SortedSet)
  1142. */
  1143. final void putKeysLinear(Iterator<K> keys, int count)
  1144. {
  1145. fabricateTree(count);
  1146. Node<K,V> node = firstNode();
  1147. while (--count >= 0)
  1148. {
  1149. node.key = keys.next();
  1150. node.value = (V) "";
  1151. node = successor(node);
  1152. }
  1153. }
  1154. /**
  1155. * Deserializes this object from the given stream.
  1156. *
  1157. * @param s the stream to read from
  1158. * @throws ClassNotFoundException if the underlying stream fails
  1159. * @throws IOException if the underlying stream fails
  1160. * @serialData the <i>size</i> (int), followed by key (Object) and value
  1161. * (Object) pairs in sorted order
  1162. */
  1163. private void readObject(ObjectInputStream s)
  1164. throws IOException, ClassNotFoundException
  1165. {
  1166. s.defaultReadObject();
  1167. int size = s.readInt();
  1168. putFromObjStream(s, size, true);
  1169. }
  1170. /**
  1171. * Remove node from tree. This will increment modCount and decrement size.
  1172. * Node must exist in the tree. Package visible for use by nested classes.
  1173. *
  1174. * @param node the node to remove
  1175. */
  1176. final void removeNode(Node<K,V> node)
  1177. {
  1178. Node<K,V> splice;
  1179. Node<K,V> child;
  1180. modCount++;
  1181. size--;
  1182. // Find splice, the node at the position to actually remove from the tree.
  1183. if (node.left == nil)
  1184. {
  1185. // Node to be deleted has 0 or 1 children.
  1186. splice = node;
  1187. child = node.right;
  1188. }
  1189. else if (node.right == nil)
  1190. {
  1191. // Node to be deleted has 1 child.
  1192. splice = node;
  1193. child = node.left;
  1194. }
  1195. else
  1196. {
  1197. // Node has 2 children. Splice is node's predecessor, and we swap
  1198. // its contents into node.
  1199. splice = node.left;
  1200. while (splice.right != nil)
  1201. splice = splice.right;
  1202. child = splice.left;
  1203. node.key = splice.key;
  1204. node.value = splice.value;
  1205. }
  1206. // Unlink splice from the tree.
  1207. Node parent = splice.parent;
  1208. if (child != nil)
  1209. child.parent = parent;
  1210. if (parent == nil)
  1211. {
  1212. // Special case for 0 or 1 node remaining.
  1213. root = child;
  1214. return;
  1215. }
  1216. if (splice == parent.left)
  1217. parent.left = child;
  1218. else
  1219. parent.right = child;
  1220. if (splice.color == BLACK)
  1221. deleteFixup(child, parent);
  1222. }
  1223. /**
  1224. * Rotate node n to the left.
  1225. *
  1226. * @param node the node to rotate
  1227. */
  1228. private void rotateLeft(Node<K,V> node)
  1229. {
  1230. Node child = node.right;
  1231. // if (node == nil || child == nil)
  1232. // throw new InternalError();
  1233. // Establish node.right link.
  1234. node.right = child.left;
  1235. if (child.left != nil)
  1236. child.left.parent = node;
  1237. // Establish child->parent link.
  1238. child.parent = node.parent;
  1239. if (node.parent != nil)
  1240. {
  1241. if (node == node.parent.left)
  1242. node.parent.left = child;
  1243. else
  1244. node.parent.right = child;
  1245. }
  1246. else
  1247. root = child;
  1248. // Link n and child.
  1249. child.left = node;
  1250. node.parent = child;
  1251. }
  1252. /**
  1253. * Rotate node n to the right.
  1254. *
  1255. * @param node the node to rotate
  1256. */
  1257. private void rotateRight(Node<K,V> node)
  1258. {
  1259. Node child = node.left;
  1260. // if (node == nil || child == nil)
  1261. // throw new InternalError();
  1262. // Establish node.left link.
  1263. node.left = child.right;
  1264. if (child.right != nil)
  1265. child.right.parent = node;
  1266. // Establish child->parent link.
  1267. child.parent = node.parent;
  1268. if (node.parent != nil)
  1269. {
  1270. if (node == node.parent.right)
  1271. node.parent.right = child;
  1272. else
  1273. node.parent.left = child;
  1274. }
  1275. else
  1276. root = child;
  1277. // Link n and child.
  1278. child.right = node;
  1279. node.parent = child;
  1280. }
  1281. /**
  1282. * Return the node following the given one, or nil if there isn't one.
  1283. * Package visible for use by nested classes.
  1284. *
  1285. * @param node the current node, not nil
  1286. * @return the next node in sorted order
  1287. */
  1288. final Node<K,V> successor(Node<K,V> node)
  1289. {
  1290. if (node.right != nil)
  1291. {
  1292. node = node.right;
  1293. while (node.left != nil)
  1294. node = node.left;
  1295. return node;
  1296. }
  1297. Node<K,V> parent = node.parent;
  1298. // Exploit fact that nil.right == nil and node is non-nil.
  1299. while (node == parent.right)
  1300. {
  1301. node = parent;
  1302. parent = parent.parent;
  1303. }
  1304. return parent;
  1305. }
  1306. /**
  1307. * Serializes this object to the given stream.
  1308. *
  1309. * @param s the stream to write to
  1310. * @throws IOException if the underlying stream fails
  1311. * @serialData the <i>size</i> (int), followed by key (Object) and value
  1312. * (Object) pairs in sorted order
  1313. */
  1314. private void writeObject(ObjectOutputStream s) throws IOException
  1315. {
  1316. s.defaultWriteObject();
  1317. Node node = firstNode();
  1318. s.writeInt(size);
  1319. while (node != nil)
  1320. {
  1321. s.writeObject(node.key);
  1322. s.writeObject(node.value);
  1323. node = successor(node);
  1324. }
  1325. }
  1326. /**
  1327. * Iterate over TreeMap's entries. This implementation is parameterized
  1328. * to give a sequential view of keys, values, or entries.
  1329. *
  1330. * @author Eric Blake (ebb9@email.byu.edu)
  1331. */
  1332. private final class TreeIterator implements Iterator
  1333. {
  1334. /**
  1335. * The type of this Iterator: {@link #KEYS}, {@link #VALUES},
  1336. * or {@link #ENTRIES}.
  1337. */
  1338. private final int type;
  1339. /** The number of modifications to the backing Map that we know about. */
  1340. private int knownMod = modCount;
  1341. /** The last Entry returned by a next() call. */
  1342. private Node last;
  1343. /** The next entry that should be returned by next(). */
  1344. private Node next;
  1345. /**
  1346. * The last node visible to this iterator. This is used when iterating
  1347. * on a SubMap.
  1348. */
  1349. private final Node max;
  1350. /**
  1351. * Construct a new TreeIterator with the supplied type.
  1352. * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
  1353. */
  1354. TreeIterator(int type)
  1355. {
  1356. this(type, firstNode(), nil);
  1357. }
  1358. /**
  1359. * Construct a new TreeIterator with the supplied type. Iteration will
  1360. * be from "first" (inclusive) to "max" (exclusive).
  1361. *
  1362. * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
  1363. * @param first where to start iteration, nil for empty iterator
  1364. * @param max the cutoff for iteration, nil for all remaining nodes
  1365. */
  1366. TreeIterator(int type, Node first, Node max)
  1367. {
  1368. this.type = type;
  1369. this.next = first;
  1370. this.max = max;
  1371. }
  1372. /**
  1373. * Returns true if the Iterator has more elements.
  1374. * @return true if there are more elements
  1375. */
  1376. public boolean hasNext()
  1377. {
  1378. return next != max;
  1379. }
  1380. /**
  1381. * Returns the next element in the Iterator's sequential view.
  1382. * @return the next element
  1383. * @throws ConcurrentModificationException if the TreeMap was modified
  1384. * @throws NoSuchElementException if there is none
  1385. */
  1386. public Object next()
  1387. {
  1388. if (knownMod != modCount)
  1389. throw new ConcurrentModificationException();
  1390. if (next == max)
  1391. throw new NoSuchElementException();
  1392. last = next;
  1393. next = successor(last);
  1394. if (type == VALUES)
  1395. return last.value;
  1396. else if (type == KEYS)
  1397. return last.key;
  1398. return last;
  1399. }
  1400. /**
  1401. * Removes from the backing TreeMap the last element which was fetched
  1402. * with the <code>next()</code> method.
  1403. * @throws ConcurrentModificationException if the TreeMap was modified
  1404. * @throws IllegalStateException if called when there is no last element
  1405. */
  1406. public void remove()
  1407. {
  1408. if (last == null)
  1409. throw new IllegalStateException();
  1410. if (knownMod != modCount)
  1411. throw new ConcurrentModificationException();
  1412. removeNode(last);
  1413. last = null;
  1414. knownMod++;
  1415. }
  1416. } // class TreeIterator
  1417. /**
  1418. * Implementation of {@link #subMap(Object, Object)} and other map
  1419. * ranges. This class provides a view of a portion of the original backing
  1420. * map, and throws {@link IllegalArgumentException} for attempts to
  1421. * access beyond that range.
  1422. *
  1423. * @author Eric Blake (ebb9@email.byu.edu)
  1424. */
  1425. private final class SubMap
  1426. extends AbstractMap<K,V>
  1427. implements NavigableMap<K,V>
  1428. {
  1429. /**
  1430. * The lower range of this view, inclusive, or nil for unbounded.
  1431. * Package visible for use by nested classes.
  1432. */
  1433. final K minKey;
  1434. /**
  1435. * The upper range of this view, exclusive, or nil for unbounded.
  1436. * Package visible for use by nested classes.
  1437. */
  1438. final K maxKey;
  1439. /**
  1440. * The cache for {@link #entrySet()}.
  1441. */
  1442. private Set<Map.Entry<K,V>> entries;
  1443. /**
  1444. * The cache for {@link #descendingMap()}.
  1445. */
  1446. private NavigableMap<K,V> descendingMap;
  1447. /**
  1448. * The cache for {@link #navigableKeySet()}.
  1449. */
  1450. private NavigableSet<K> nKeys;
  1451. /**
  1452. * Create a SubMap representing the elements between minKey (inclusive)
  1453. * and maxKey (exclusive). If minKey is nil, SubMap has no lower bound
  1454. * (headMap). If maxKey is nil, the SubMap has no upper bound (tailMap).
  1455. *
  1456. * @param minKey the lower bound
  1457. * @param maxKey the upper bound
  1458. * @throws IllegalArgumentException if minKey &gt; maxKey
  1459. */
  1460. SubMap(K minKey, K maxKey)
  1461. {
  1462. if (minKey != nil && maxKey != nil && compare(minKey, maxKey) > 0)
  1463. throw new IllegalArgumentException("fromKey > toKey");
  1464. this.minKey = minKey;
  1465. this.maxKey = maxKey;
  1466. }
  1467. /**
  1468. * Check if "key" is in within the range bounds for this SubMap. The
  1469. * lower ("from") SubMap range is inclusive, and the upper ("to") bound
  1470. * is exclusive. Package visible for use by nested classes.
  1471. *
  1472. * @param key the key to check
  1473. * @return true if the key is in range
  1474. */
  1475. boolean keyInRange(K key)
  1476. {
  1477. return ((minKey == nil || compare(key, minKey) >= 0)
  1478. && (maxKey == nil || compare(key, maxKey) < 0));
  1479. }
  1480. public Entry<K,V> ceilingEntry(K key)
  1481. {
  1482. Entry<K,V> n = TreeMap.this.ceilingEntry(key);
  1483. if (n != null && keyInRange(n.getKey()))
  1484. return n;
  1485. return null;
  1486. }
  1487. public K ceilingKey(K key)
  1488. {
  1489. K found = TreeMap.this.ceilingKey(key);
  1490. if (keyInRange(found))
  1491. return found;
  1492. else
  1493. return null;
  1494. }
  1495. public NavigableSet<K> descendingKeySet()
  1496. {
  1497. return descendingMap().navigableKeySet();
  1498. }
  1499. public NavigableMap<K,V> descendingMap()
  1500. {
  1501. if (descendingMap == null)
  1502. descendingMap = new DescendingMap(this);
  1503. return descendingMap;
  1504. }
  1505. public void clear()
  1506. {
  1507. Node next = lowestGreaterThan(minKey, true);
  1508. Node max = lowestGreaterThan(maxKey, false);
  1509. while (next != max)
  1510. {
  1511. Node current = next;
  1512. next = successor(current);
  1513. removeNode(current);
  1514. }
  1515. }
  1516. public Comparator<? super K> comparator()
  1517. {
  1518. return comparator;
  1519. }
  1520. public boolean containsKey(Object key)
  1521. {
  1522. return keyInRange((K) key) && TreeMap.this.containsKey(key);
  1523. }
  1524. public boolean containsValue(Object value)
  1525. {
  1526. Node node = lowestGreaterThan(minKey, true);
  1527. Node max = lowestGreaterThan(maxKey, false);
  1528. while (node != max)
  1529. {
  1530. if (equals(value, node.getValue()))
  1531. return true;
  1532. node = successor(node);
  1533. }
  1534. return false;
  1535. }
  1536. public Set<Map.Entry<K,V>> entrySet()
  1537. {
  1538. if (entries == null)
  1539. // Create an AbstractSet with custom implementations of those methods
  1540. // that can be overriden easily and efficiently.
  1541. entries = new SubMap.NavigableEntrySet();
  1542. return entries;
  1543. }
  1544. public Entry<K,V> firstEntry()
  1545. {
  1546. Node<K,V> node = lowestGreaterThan(minKey, true);
  1547. if (node == nil || ! keyInRange(node.key))
  1548. return null;
  1549. return node;
  1550. }
  1551. public K firstKey()
  1552. {
  1553. Entry<K,V> e = firstEntry();
  1554. if (e == null)
  1555. throw new NoSuchElementException();
  1556. return e.getKey();
  1557. }
  1558. public Entry<K,V> floorEntry(K key)
  1559. {
  1560. Entry<K,V> n = TreeMap.this.floorEntry(key);
  1561. if (n != null && keyInRange(n.getKey()))
  1562. return n;
  1563. return null;
  1564. }
  1565. public K floorKey(K key)
  1566. {
  1567. K found = TreeMap.this.floorKey(key);
  1568. if (keyInRange(found))
  1569. return found;
  1570. else
  1571. return null;
  1572. }
  1573. public V get(Object key)
  1574. {
  1575. if (keyInRange((K) key))
  1576. return TreeMap.this.get(key);
  1577. return null;
  1578. }
  1579. public SortedMap<K,V> headMap(K toKey)
  1580. {
  1581. return headMap(toKey, false);
  1582. }
  1583. public NavigableMap<K,V> headMap(K toKey, boolean inclusive)
  1584. {
  1585. if (!keyInRange(toKey))
  1586. throw new IllegalArgumentException("Key outside submap range");
  1587. return new SubMap(minKey, (inclusive ?
  1588. successor(getNode(toKey)).key : toKey));
  1589. }
  1590. public Set<K> keySet()
  1591. {
  1592. if (this.keys == null)
  1593. // Create an AbstractSet with custom implementations of those methods
  1594. // that can be overriden easily and efficiently.
  1595. this.keys = new SubMap.KeySet();
  1596. return this.keys;
  1597. }
  1598. public Entry<K,V> higherEntry(K key)
  1599. {
  1600. Entry<K,V> n = TreeMap.this.higherEntry(key);
  1601. if (n != null && keyInRange(n.getKey()))
  1602. return n;
  1603. return null;
  1604. }
  1605. public K higherKey(K key)
  1606. {
  1607. K found = TreeMap.this.higherKey(key);
  1608. if (keyInRange(found))
  1609. return found;
  1610. else
  1611. return null;
  1612. }
  1613. public Entry<K,V> lastEntry()
  1614. {
  1615. return lowerEntry(maxKey);
  1616. }
  1617. public K lastKey()
  1618. {
  1619. Entry<K,V> e = lastEntry();
  1620. if (e == null)
  1621. throw new NoSuchElementException();
  1622. return e.getKey();
  1623. }
  1624. public Entry<K,V> lowerEntry(K key)
  1625. {
  1626. Entry<K,V> n = TreeMap.this.lowerEntry(key);
  1627. if (n != null && keyInRange(n.getKey()))
  1628. return n;
  1629. return null;
  1630. }
  1631. public K lowerKey(K key)
  1632. {
  1633. K found = TreeMap.this.lowerKey(key);
  1634. if (keyInRange(found))
  1635. return found;
  1636. else
  1637. return null;
  1638. }
  1639. public NavigableSet<K> navigableKeySet()
  1640. {
  1641. if (this.nKeys == null)
  1642. // Create an AbstractSet with custom implementations of those methods
  1643. // that can be overriden easily and efficiently.
  1644. this.nKeys = new SubMap.NavigableKeySet();
  1645. return this.nKeys;
  1646. }
  1647. public Entry<K,V> pollFirstEntry()
  1648. {
  1649. Entry<K,V> e = firstEntry();
  1650. if (e != null)
  1651. removeNode((Node<K,V>) e);
  1652. return e;
  1653. }
  1654. public Entry<K,V> pollLastEntry()
  1655. {
  1656. Entry<K,V> e = lastEntry();
  1657. if (e != null)
  1658. removeNode((Node<K,V>) e);
  1659. return e;
  1660. }
  1661. public V put(K key, V value)
  1662. {
  1663. if (! keyInRange(key))
  1664. throw new IllegalArgumentException("Key outside range");
  1665. return TreeMap.this.put(key, value);
  1666. }
  1667. public V remove(Object key)
  1668. {
  1669. if (keyInRange((K)key))
  1670. return TreeMap.this.remove(key);
  1671. return null;
  1672. }
  1673. public int size()
  1674. {
  1675. Node node = lowestGreaterThan(minKey, true);
  1676. Node max = lowestGreaterThan(maxKey, false);
  1677. int count = 0;
  1678. while (node != max)
  1679. {
  1680. count++;
  1681. node = successor(node);
  1682. }
  1683. return count;
  1684. }
  1685. public SortedMap<K,V> subMap(K fromKey, K toKey)
  1686. {
  1687. return subMap(fromKey, true, toKey, false);
  1688. }
  1689. public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
  1690. K toKey, boolean toInclusive)
  1691. {
  1692. if (! keyInRange(fromKey) || ! keyInRange(toKey))
  1693. throw new IllegalArgumentException("key outside range");
  1694. return new SubMap(fromInclusive ? fromKey : successor(getNode(fromKey)).key,
  1695. toInclusive ? successor(getNode(toKey)).key : toKey);
  1696. }
  1697. public SortedMap<K, V> tailMap(K fromKey)
  1698. {
  1699. return tailMap(fromKey, true);
  1700. }
  1701. public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive)
  1702. {
  1703. if (! keyInRange(fromKey))
  1704. throw new IllegalArgumentException("key outside range");
  1705. return new SubMap(inclusive ? fromKey : successor(getNode(fromKey)).key,
  1706. maxKey);
  1707. }
  1708. public Collection<V> values()
  1709. {
  1710. if (this.values == null)
  1711. // Create an AbstractCollection with custom implementations of those
  1712. // methods that can be overriden easily and efficiently.
  1713. this.values = new AbstractCollection()
  1714. {
  1715. public int size()
  1716. {
  1717. return SubMap.this.size();
  1718. }
  1719. public Iterator<V> iterator()
  1720. {
  1721. Node first = lowestGreaterThan(minKey, true);
  1722. Node max = lowestGreaterThan(maxKey, false);
  1723. return new TreeIterator(VALUES, first, max);
  1724. }
  1725. public void clear()
  1726. {
  1727. SubMap.this.clear();
  1728. }
  1729. };
  1730. return this.values;
  1731. }
  1732. private class KeySet
  1733. extends AbstractSet<K>
  1734. {
  1735. public int size()
  1736. {
  1737. return SubMap.this.size();
  1738. }
  1739. public Iterator<K> iterator()
  1740. {
  1741. Node first = lowestGreaterThan(minKey, true);
  1742. Node max = lowestGreaterThan(maxKey, false);
  1743. return new TreeIterator(KEYS, first, max);
  1744. }
  1745. public void clear()
  1746. {
  1747. SubMap.this.clear();
  1748. }
  1749. public boolean contains(Object o)
  1750. {
  1751. if (! keyInRange((K) o))
  1752. return false;
  1753. return getNode((K) o) != nil;
  1754. }
  1755. public boolean remove(Object o)
  1756. {
  1757. if (! keyInRange((K) o))
  1758. return false;
  1759. Node n = getNode((K) o);
  1760. if (n != nil)
  1761. {
  1762. removeNode(n);
  1763. return true;
  1764. }
  1765. return false;
  1766. }
  1767. } // class SubMap.KeySet
  1768. private final class NavigableKeySet
  1769. extends KeySet
  1770. implements NavigableSet<K>
  1771. {
  1772. public K ceiling(K k)
  1773. {
  1774. return SubMap.this.ceilingKey(k);
  1775. }
  1776. public Comparator<? super K> comparator()
  1777. {
  1778. return comparator;
  1779. }
  1780. public Iterator<K> descendingIterator()
  1781. {
  1782. return descendingSet().iterator();
  1783. }
  1784. public NavigableSet<K> descendingSet()
  1785. {
  1786. return new DescendingSet(this);
  1787. }
  1788. public K first()
  1789. {
  1790. return SubMap.this.firstKey();
  1791. }
  1792. public K floor(K k)
  1793. {
  1794. return SubMap.this.floorKey(k);
  1795. }
  1796. public SortedSet<K> headSet(K to)
  1797. {
  1798. return headSet(to, false);
  1799. }
  1800. public NavigableSet<K> headSet(K to, boolean inclusive)
  1801. {
  1802. return SubMap.this.headMap(to, inclusive).navigableKeySet();
  1803. }
  1804. public K higher(K k)
  1805. {
  1806. return SubMap.this.higherKey(k);
  1807. }
  1808. public K last()
  1809. {
  1810. return SubMap.this.lastKey();
  1811. }
  1812. public K lower(K k)
  1813. {
  1814. return SubMap.this.lowerKey(k);
  1815. }
  1816. public K pollFirst()
  1817. {
  1818. return SubMap.this.pollFirstEntry().getKey();
  1819. }
  1820. public K pollLast()
  1821. {
  1822. return SubMap.this.pollLastEntry().getKey();
  1823. }
  1824. public SortedSet<K> subSet(K from, K to)
  1825. {
  1826. return subSet(from, true, to, false);
  1827. }
  1828. public NavigableSet<K> subSet(K from, boolean fromInclusive,
  1829. K to, boolean toInclusive)
  1830. {
  1831. return SubMap.this.subMap(from, fromInclusive,
  1832. to, toInclusive).navigableKeySet();
  1833. }
  1834. public SortedSet<K> tailSet(K from)
  1835. {
  1836. return tailSet(from, true);
  1837. }
  1838. public NavigableSet<K> tailSet(K from, boolean inclusive)
  1839. {
  1840. return SubMap.this.tailMap(from, inclusive).navigableKeySet();
  1841. }
  1842. } // class SubMap.NavigableKeySet
  1843. /**
  1844. * Implementation of {@link #entrySet()}.
  1845. */
  1846. private class EntrySet
  1847. extends AbstractSet<Entry<K,V>>
  1848. {
  1849. public int size()
  1850. {
  1851. return SubMap.this.size();
  1852. }
  1853. public Iterator<Map.Entry<K,V>> iterator()
  1854. {
  1855. Node first = lowestGreaterThan(minKey, true);
  1856. Node max = lowestGreaterThan(maxKey, false);
  1857. return new TreeIterator(ENTRIES, first, max);
  1858. }
  1859. public void clear()
  1860. {
  1861. SubMap.this.clear();
  1862. }
  1863. public boolean contains(Object o)
  1864. {
  1865. if (! (o instanceof Map.Entry))
  1866. return false;
  1867. Map.Entry<K,V> me = (Map.Entry<K,V>) o;
  1868. K key = me.getKey();
  1869. if (! keyInRange(key))
  1870. return false;
  1871. Node<K,V> n = getNode(key);
  1872. return n != nil && AbstractSet.equals(me.getValue(), n.value);
  1873. }
  1874. public boolean remove(Object o)
  1875. {
  1876. if (! (o instanceof Map.Entry))
  1877. return false;
  1878. Map.Entry<K,V> me = (Map.Entry<K,V>) o;
  1879. K key = me.getKey();
  1880. if (! keyInRange(key))
  1881. return false;
  1882. Node<K,V> n = getNode(key);
  1883. if (n != nil && AbstractSet.equals(me.getValue(), n.value))
  1884. {
  1885. removeNode(n);
  1886. return true;
  1887. }
  1888. return false;
  1889. }
  1890. } // class SubMap.EntrySet
  1891. private final class NavigableEntrySet
  1892. extends EntrySet
  1893. implements NavigableSet<Entry<K,V>>
  1894. {
  1895. public Entry<K,V> ceiling(Entry<K,V> e)
  1896. {
  1897. return SubMap.this.ceilingEntry(e.getKey());
  1898. }
  1899. public Comparator<? super Entry<K,V>> comparator()
  1900. {
  1901. return new Comparator<Entry<K,V>>()
  1902. {
  1903. public int compare(Entry<K,V> t1, Entry<K,V> t2)
  1904. {
  1905. return comparator.compare(t1.getKey(), t2.getKey());
  1906. }
  1907. };
  1908. }
  1909. public Iterator<Entry<K,V>> descendingIterator()
  1910. {
  1911. return descendingSet().iterator();
  1912. }
  1913. public NavigableSet<Entry<K,V>> descendingSet()
  1914. {
  1915. return new DescendingSet(this);
  1916. }
  1917. public Entry<K,V> first()
  1918. {
  1919. return SubMap.this.firstEntry();
  1920. }
  1921. public Entry<K,V> floor(Entry<K,V> e)
  1922. {
  1923. return SubMap.this.floorEntry(e.getKey());
  1924. }
  1925. public SortedSet<Entry<K,V>> headSet(Entry<K,V> to)
  1926. {
  1927. return headSet(to, false);
  1928. }
  1929. public NavigableSet<Entry<K,V>> headSet(Entry<K,V> to, boolean inclusive)
  1930. {
  1931. return (NavigableSet<Entry<K,V>>)
  1932. SubMap.this.headMap(to.getKey(), inclusive).entrySet();
  1933. }
  1934. public Entry<K,V> higher(Entry<K,V> e)
  1935. {
  1936. return SubMap.this.higherEntry(e.getKey());
  1937. }
  1938. public Entry<K,V> last()
  1939. {
  1940. return SubMap.this.lastEntry();
  1941. }
  1942. public Entry<K,V> lower(Entry<K,V> e)
  1943. {
  1944. return SubMap.this.lowerEntry(e.getKey());
  1945. }
  1946. public Entry<K,V> pollFirst()
  1947. {
  1948. return SubMap.this.pollFirstEntry();
  1949. }
  1950. public Entry<K,V> pollLast()
  1951. {
  1952. return SubMap.this.pollLastEntry();
  1953. }
  1954. public SortedSet<Entry<K,V>> subSet(Entry<K,V> from, Entry<K,V> to)
  1955. {
  1956. return subSet(from, true, to, false);
  1957. }
  1958. public NavigableSet<Entry<K,V>> subSet(Entry<K,V> from, boolean fromInclusive,
  1959. Entry<K,V> to, boolean toInclusive)
  1960. {
  1961. return (NavigableSet<Entry<K,V>>)
  1962. SubMap.this.subMap(from.getKey(), fromInclusive,
  1963. to.getKey(), toInclusive).entrySet();
  1964. }
  1965. public SortedSet<Entry<K,V>> tailSet(Entry<K,V> from)
  1966. {
  1967. return tailSet(from, true);
  1968. }
  1969. public NavigableSet<Entry<K,V>> tailSet(Entry<K,V> from, boolean inclusive)
  1970. {
  1971. return (NavigableSet<Entry<K,V>>)
  1972. SubMap.this.tailMap(from.getKey(), inclusive).navigableKeySet();
  1973. }
  1974. } // class SubMap.NavigableEntrySet
  1975. } // class SubMap
  1976. /**
  1977. * Returns the entry associated with the least or lowest key
  1978. * that is greater than or equal to the specified key, or
  1979. * <code>null</code> if there is no such key.
  1980. *
  1981. * @param key the key relative to the returned entry.
  1982. * @return the entry with the least key greater than or equal
  1983. * to the given key, or <code>null</code> if there is
  1984. * no such key.
  1985. * @throws ClassCastException if the specified key can not
  1986. * be compared with those in the map.
  1987. * @throws NullPointerException if the key is <code>null</code>
  1988. * and this map either uses natural
  1989. * ordering or a comparator that does
  1990. * not permit null keys.
  1991. * @since 1.6
  1992. */
  1993. public Entry<K,V> ceilingEntry(K key)
  1994. {
  1995. Node<K,V> n = lowestGreaterThan(key, false);
  1996. return (n == nil) ? null : n;
  1997. }
  1998. /**
  1999. * Returns the the least or lowest key that is greater than
  2000. * or equal to the specified key, or <code>null</code> if
  2001. * there is no such key.
  2002. *
  2003. * @param key the key relative to the returned entry.
  2004. * @return the least key greater than or equal to the given key,
  2005. * or <code>null</code> if there is no such key.
  2006. * @throws ClassCastException if the specified key can not
  2007. * be compared with those in the map.
  2008. * @throws NullPointerException if the key is <code>null</code>
  2009. * and this map either uses natural
  2010. * ordering or a comparator that does
  2011. * not permit null keys.
  2012. * @since 1.6
  2013. */
  2014. public K ceilingKey(K key)
  2015. {
  2016. Entry<K,V> e = ceilingEntry(key);
  2017. return (e == null) ? null : e.getKey();
  2018. }
  2019. /**
  2020. * Returns a reverse ordered {@link NavigableSet} view of this
  2021. * map's keys. The set is backed by the {@link TreeMap}, so changes
  2022. * in one show up in the other. The set supports element removal,
  2023. * but not element addition.
  2024. *
  2025. * @return a reverse ordered set view of the keys.
  2026. * @since 1.6
  2027. * @see #descendingMap()
  2028. */
  2029. public NavigableSet<K> descendingKeySet()
  2030. {
  2031. return descendingMap().navigableKeySet();
  2032. }
  2033. /**
  2034. * Returns a view of the map in reverse order. The descending map
  2035. * is backed by the original map, so that changes affect both maps.
  2036. * Any changes occurring to either map while an iteration is taking
  2037. * place (with the exception of a {@link Iterator#remove()} operation)
  2038. * result in undefined behaviour from the iteration. The ordering
  2039. * of the descending map is the same as for a map with a
  2040. * {@link Comparator} given by {@link Collections#reverseOrder()},
  2041. * and calling {@link #descendingMap()} on the descending map itself
  2042. * results in a view equivalent to the original map.
  2043. *
  2044. * @return a reverse order view of the map.
  2045. * @since 1.6
  2046. */
  2047. public NavigableMap<K,V> descendingMap()
  2048. {
  2049. if (descendingMap == null)
  2050. descendingMap = new DescendingMap<K,V>(this);
  2051. return descendingMap;
  2052. }
  2053. /**
  2054. * Returns the entry associated with the least or lowest key
  2055. * in the map, or <code>null</code> if the map is empty.
  2056. *
  2057. * @return the lowest entry, or <code>null</code> if the map
  2058. * is empty.
  2059. * @since 1.6
  2060. */
  2061. public Entry<K,V> firstEntry()
  2062. {
  2063. Node<K,V> n = firstNode();
  2064. return (n == nil) ? null : n;
  2065. }
  2066. /**
  2067. * Returns the entry associated with the greatest or highest key
  2068. * that is less than or equal to the specified key, or
  2069. * <code>null</code> if there is no such key.
  2070. *
  2071. * @param key the key relative to the returned entry.
  2072. * @return the entry with the greatest key less than or equal
  2073. * to the given key, or <code>null</code> if there is
  2074. * no such key.
  2075. * @throws ClassCastException if the specified key can not
  2076. * be compared with those in the map.
  2077. * @throws NullPointerException if the key is <code>null</code>
  2078. * and this map either uses natural
  2079. * ordering or a comparator that does
  2080. * not permit null keys.
  2081. * @since 1.6
  2082. */
  2083. public Entry<K,V> floorEntry(K key)
  2084. {
  2085. Node<K,V> n = highestLessThan(key, true);
  2086. return (n == nil) ? null : n;
  2087. }
  2088. /**
  2089. * Returns the the greatest or highest key that is less than
  2090. * or equal to the specified key, or <code>null</code> if
  2091. * there is no such key.
  2092. *
  2093. * @param key the key relative to the returned entry.
  2094. * @return the greatest key less than or equal to the given key,
  2095. * or <code>null</code> if there is no such key.
  2096. * @throws ClassCastException if the specified key can not
  2097. * be compared with those in the map.
  2098. * @throws NullPointerException if the key is <code>null</code>
  2099. * and this map either uses natural
  2100. * ordering or a comparator that does
  2101. * not permit null keys.
  2102. * @since 1.6
  2103. */
  2104. public K floorKey(K key)
  2105. {
  2106. Entry<K,V> e = floorEntry(key);
  2107. return (e == null) ? null : e.getKey();
  2108. }
  2109. /**
  2110. * Returns the entry associated with the least or lowest key
  2111. * that is strictly greater than the specified key, or
  2112. * <code>null</code> if there is no such key.
  2113. *
  2114. * @param key the key relative to the returned entry.
  2115. * @return the entry with the least key greater than
  2116. * the given key, or <code>null</code> if there is
  2117. * no such key.
  2118. * @throws ClassCastException if the specified key can not
  2119. * be compared with those in the map.
  2120. * @throws NullPointerException if the key is <code>null</code>
  2121. * and this map either uses natural
  2122. * ordering or a comparator that does
  2123. * not permit null keys.
  2124. * @since 1.6
  2125. */
  2126. public Entry<K,V> higherEntry(K key)
  2127. {
  2128. Node<K,V> n = lowestGreaterThan(key, false, false);
  2129. return (n == nil) ? null : n;
  2130. }
  2131. /**
  2132. * Returns the the least or lowest key that is strictly
  2133. * greater than the specified key, or <code>null</code> if
  2134. * there is no such key.
  2135. *
  2136. * @param key the key relative to the returned entry.
  2137. * @return the least key greater than the given key,
  2138. * or <code>null</code> if there is no such key.
  2139. * @throws ClassCastException if the specified key can not
  2140. * be compared with those in the map.
  2141. * @throws NullPointerException if the key is <code>null</code>
  2142. * and this map either uses natural
  2143. * ordering or a comparator that does
  2144. * not permit null keys.
  2145. * @since 1.6
  2146. */
  2147. public K higherKey(K key)
  2148. {
  2149. Entry<K,V> e = higherEntry(key);
  2150. return (e == null) ? null : e.getKey();
  2151. }
  2152. /**
  2153. * Returns the entry associated with the greatest or highest key
  2154. * in the map, or <code>null</code> if the map is empty.
  2155. *
  2156. * @return the highest entry, or <code>null</code> if the map
  2157. * is empty.
  2158. * @since 1.6
  2159. */
  2160. public Entry<K,V> lastEntry()
  2161. {
  2162. Node<K,V> n = lastNode();
  2163. return (n == nil) ? null : n;
  2164. }
  2165. /**
  2166. * Returns the entry associated with the greatest or highest key
  2167. * that is strictly less than the specified key, or
  2168. * <code>null</code> if there is no such key.
  2169. *
  2170. * @param key the key relative to the returned entry.
  2171. * @return the entry with the greatest key less than
  2172. * the given key, or <code>null</code> if there is
  2173. * no such key.
  2174. * @throws ClassCastException if the specified key can not
  2175. * be compared with those in the map.
  2176. * @throws NullPointerException if the key is <code>null</code>
  2177. * and this map either uses natural
  2178. * ordering or a comparator that does
  2179. * not permit null keys.
  2180. * @since 1.6
  2181. */
  2182. public Entry<K,V> lowerEntry(K key)
  2183. {
  2184. Node<K,V> n = highestLessThan(key);
  2185. return (n == nil) ? null : n;
  2186. }
  2187. /**
  2188. * Returns the the greatest or highest key that is strictly
  2189. * less than the specified key, or <code>null</code> if
  2190. * there is no such key.
  2191. *
  2192. * @param key the key relative to the returned entry.
  2193. * @return the greatest key less than the given key,
  2194. * or <code>null</code> if there is no such key.
  2195. * @throws ClassCastException if the specified key can not
  2196. * be compared with those in the map.
  2197. * @throws NullPointerException if the key is <code>null</code>
  2198. * and this map either uses natural
  2199. * ordering or a comparator that does
  2200. * not permit null keys.
  2201. * @since 1.6
  2202. */
  2203. public K lowerKey(K key)
  2204. {
  2205. Entry<K,V> e = lowerEntry(key);
  2206. return (e == null) ? null : e.getKey();
  2207. }
  2208. /**
  2209. * Returns a {@link NavigableSet} view of this map's keys. The set is
  2210. * backed by the {@link TreeMap}, so changes in one show up in the other.
  2211. * Any changes occurring to either while an iteration is taking
  2212. * place (with the exception of a {@link Iterator#remove()} operation)
  2213. * result in undefined behaviour from the iteration. The ordering
  2214. * The set supports element removal, but not element addition.
  2215. *
  2216. * @return a {@link NavigableSet} view of the keys.
  2217. * @since 1.6
  2218. */
  2219. public NavigableSet<K> navigableKeySet()
  2220. {
  2221. if (nKeys == null)
  2222. nKeys = new NavigableKeySet();
  2223. return nKeys;
  2224. }
  2225. /**
  2226. * Removes and returns the entry associated with the least
  2227. * or lowest key in the map, or <code>null</code> if the map
  2228. * is empty.
  2229. *
  2230. * @return the removed first entry, or <code>null</code> if the
  2231. * map is empty.
  2232. * @since 1.6
  2233. */
  2234. public Entry<K,V> pollFirstEntry()
  2235. {
  2236. Entry<K,V> e = firstEntry();
  2237. if (e != null)
  2238. removeNode((Node<K,V>)e);
  2239. return e;
  2240. }
  2241. /**
  2242. * Removes and returns the entry associated with the greatest
  2243. * or highest key in the map, or <code>null</code> if the map
  2244. * is empty.
  2245. *
  2246. * @return the removed last entry, or <code>null</code> if the
  2247. * map is empty.
  2248. * @since 1.6
  2249. */
  2250. public Entry<K,V> pollLastEntry()
  2251. {
  2252. Entry<K,V> e = lastEntry();
  2253. if (e != null)
  2254. removeNode((Node<K,V>)e);
  2255. return e;
  2256. }
  2257. /**
  2258. * Implementation of {@link #descendingMap()} and associated
  2259. * derivatives. This class provides a view of the
  2260. * original backing map in reverse order, and throws
  2261. * {@link IllegalArgumentException} for attempts to
  2262. * access beyond that range.
  2263. *
  2264. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  2265. */
  2266. private static final class DescendingMap<DK,DV>
  2267. implements NavigableMap<DK,DV>
  2268. {
  2269. /**
  2270. * The cache for {@link #entrySet()}.
  2271. */
  2272. private Set<Map.Entry<DK,DV>> entries;
  2273. /**
  2274. * The cache for {@link #keySet()}.
  2275. */
  2276. private Set<DK> keys;
  2277. /**
  2278. * The cache for {@link #navigableKeySet()}.
  2279. */
  2280. private NavigableSet<DK> nKeys;
  2281. /**
  2282. * The cache for {@link #values()}.
  2283. */
  2284. private Collection<DV> values;
  2285. /**
  2286. * The backing {@link NavigableMap}.
  2287. */
  2288. private NavigableMap<DK,DV> map;
  2289. /**
  2290. * Create a {@link DescendingMap} around the specified
  2291. * map.
  2292. *
  2293. * @param map the map to wrap.
  2294. */
  2295. public DescendingMap(NavigableMap<DK,DV> map)
  2296. {
  2297. this.map = map;
  2298. }
  2299. public Map.Entry<DK,DV> ceilingEntry(DK key)
  2300. {
  2301. return map.floorEntry(key);
  2302. }
  2303. public DK ceilingKey(DK key)
  2304. {
  2305. return map.floorKey(key);
  2306. }
  2307. public void clear()
  2308. {
  2309. map.clear();
  2310. }
  2311. public Comparator<? super DK> comparator()
  2312. {
  2313. return Collections.reverseOrder(map.comparator());
  2314. }
  2315. public boolean containsKey(Object o)
  2316. {
  2317. return map.containsKey(o);
  2318. }
  2319. public boolean containsValue(Object o)
  2320. {
  2321. return map.containsValue(o);
  2322. }
  2323. public NavigableSet<DK> descendingKeySet()
  2324. {
  2325. return descendingMap().navigableKeySet();
  2326. }
  2327. public NavigableMap<DK,DV> descendingMap()
  2328. {
  2329. return map;
  2330. }
  2331. public Set<Entry<DK,DV>> entrySet()
  2332. {
  2333. if (entries == null)
  2334. entries =
  2335. new DescendingSet<Entry<DK,DV>>((NavigableSet<Entry<DK,DV>>)
  2336. map.entrySet());
  2337. return entries;
  2338. }
  2339. public boolean equals(Object o)
  2340. {
  2341. return map.equals(o);
  2342. }
  2343. public Entry<DK,DV> firstEntry()
  2344. {
  2345. return map.lastEntry();
  2346. }
  2347. public DK firstKey()
  2348. {
  2349. return map.lastKey();
  2350. }
  2351. public Entry<DK,DV> floorEntry(DK key)
  2352. {
  2353. return map.ceilingEntry(key);
  2354. }
  2355. public DK floorKey(DK key)
  2356. {
  2357. return map.ceilingKey(key);
  2358. }
  2359. public DV get(Object key)
  2360. {
  2361. return map.get(key);
  2362. }
  2363. public int hashCode()
  2364. {
  2365. return map.hashCode();
  2366. }
  2367. public SortedMap<DK,DV> headMap(DK toKey)
  2368. {
  2369. return headMap(toKey, false);
  2370. }
  2371. public NavigableMap<DK,DV> headMap(DK toKey, boolean inclusive)
  2372. {
  2373. return new DescendingMap(map.tailMap(toKey, inclusive));
  2374. }
  2375. public Entry<DK,DV> higherEntry(DK key)
  2376. {
  2377. return map.lowerEntry(key);
  2378. }
  2379. public DK higherKey(DK key)
  2380. {
  2381. return map.lowerKey(key);
  2382. }
  2383. public Set<DK> keySet()
  2384. {
  2385. if (keys == null)
  2386. keys = new DescendingSet<DK>(map.navigableKeySet());
  2387. return keys;
  2388. }
  2389. public boolean isEmpty()
  2390. {
  2391. return map.isEmpty();
  2392. }
  2393. public Entry<DK,DV> lastEntry()
  2394. {
  2395. return map.firstEntry();
  2396. }
  2397. public DK lastKey()
  2398. {
  2399. return map.firstKey();
  2400. }
  2401. public Entry<DK,DV> lowerEntry(DK key)
  2402. {
  2403. return map.higherEntry(key);
  2404. }
  2405. public DK lowerKey(DK key)
  2406. {
  2407. return map.higherKey(key);
  2408. }
  2409. public NavigableSet<DK> navigableKeySet()
  2410. {
  2411. if (nKeys == null)
  2412. nKeys = new DescendingSet<DK>(map.navigableKeySet());
  2413. return nKeys;
  2414. }
  2415. public Entry<DK,DV> pollFirstEntry()
  2416. {
  2417. return pollLastEntry();
  2418. }
  2419. public Entry<DK,DV> pollLastEntry()
  2420. {
  2421. return pollFirstEntry();
  2422. }
  2423. public DV put(DK key, DV value)
  2424. {
  2425. return map.put(key, value);
  2426. }
  2427. public void putAll(Map<? extends DK, ? extends DV> m)
  2428. {
  2429. map.putAll(m);
  2430. }
  2431. public DV remove(Object key)
  2432. {
  2433. return map.remove(key);
  2434. }
  2435. public int size()
  2436. {
  2437. return map.size();
  2438. }
  2439. public SortedMap<DK,DV> subMap(DK fromKey, DK toKey)
  2440. {
  2441. return subMap(fromKey, true, toKey, false);
  2442. }
  2443. public NavigableMap<DK,DV> subMap(DK fromKey, boolean fromInclusive,
  2444. DK toKey, boolean toInclusive)
  2445. {
  2446. return new DescendingMap(map.subMap(fromKey, fromInclusive,
  2447. toKey, toInclusive));
  2448. }
  2449. public SortedMap<DK,DV> tailMap(DK fromKey)
  2450. {
  2451. return tailMap(fromKey, true);
  2452. }
  2453. public NavigableMap<DK,DV> tailMap(DK fromKey, boolean inclusive)
  2454. {
  2455. return new DescendingMap(map.headMap(fromKey, inclusive));
  2456. }
  2457. public String toString()
  2458. {
  2459. CPStringBuilder r = new CPStringBuilder("{");
  2460. final Iterator<Entry<DK,DV>> it = entrySet().iterator();
  2461. while (it.hasNext())
  2462. {
  2463. final Entry<DK,DV> e = it.next();
  2464. r.append(e.getKey());
  2465. r.append('=');
  2466. r.append(e.getValue());
  2467. r.append(", ");
  2468. }
  2469. r.replace(r.length() - 2, r.length(), "}");
  2470. return r.toString();
  2471. }
  2472. public Collection<DV> values()
  2473. {
  2474. if (values == null)
  2475. // Create an AbstractCollection with custom implementations of those
  2476. // methods that can be overriden easily and efficiently.
  2477. values = new AbstractCollection()
  2478. {
  2479. public int size()
  2480. {
  2481. return DescendingMap.this.size();
  2482. }
  2483. public Iterator<DV> iterator()
  2484. {
  2485. return new Iterator<DV>()
  2486. {
  2487. /** The last Entry returned by a next() call. */
  2488. private Entry<DK,DV> last;
  2489. /** The next entry that should be returned by next(). */
  2490. private Entry<DK,DV> next = firstEntry();
  2491. public boolean hasNext()
  2492. {
  2493. return next != null;
  2494. }
  2495. public DV next()
  2496. {
  2497. if (next == null)
  2498. throw new NoSuchElementException();
  2499. last = next;
  2500. next = higherEntry(last.getKey());
  2501. return last.getValue();
  2502. }
  2503. public void remove()
  2504. {
  2505. if (last == null)
  2506. throw new IllegalStateException();
  2507. DescendingMap.this.remove(last.getKey());
  2508. last = null;
  2509. }
  2510. };
  2511. }
  2512. public void clear()
  2513. {
  2514. DescendingMap.this.clear();
  2515. }
  2516. };
  2517. return values;
  2518. }
  2519. } // class DescendingMap
  2520. /**
  2521. * Implementation of {@link #keySet()}.
  2522. */
  2523. private class KeySet
  2524. extends AbstractSet<K>
  2525. {
  2526. public int size()
  2527. {
  2528. return size;
  2529. }
  2530. public Iterator<K> iterator()
  2531. {
  2532. return new TreeIterator(KEYS);
  2533. }
  2534. public void clear()
  2535. {
  2536. TreeMap.this.clear();
  2537. }
  2538. public boolean contains(Object o)
  2539. {
  2540. return containsKey(o);
  2541. }
  2542. public boolean remove(Object key)
  2543. {
  2544. Node<K,V> n = getNode((K) key);
  2545. if (n == nil)
  2546. return false;
  2547. removeNode(n);
  2548. return true;
  2549. }
  2550. } // class KeySet
  2551. /**
  2552. * Implementation of {@link #navigableKeySet()}.
  2553. *
  2554. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  2555. */
  2556. private final class NavigableKeySet
  2557. extends KeySet
  2558. implements NavigableSet<K>
  2559. {
  2560. public K ceiling(K k)
  2561. {
  2562. return ceilingKey(k);
  2563. }
  2564. public Comparator<? super K> comparator()
  2565. {
  2566. return comparator;
  2567. }
  2568. public Iterator<K> descendingIterator()
  2569. {
  2570. return descendingSet().iterator();
  2571. }
  2572. public NavigableSet<K> descendingSet()
  2573. {
  2574. return new DescendingSet<K>(this);
  2575. }
  2576. public K first()
  2577. {
  2578. return firstKey();
  2579. }
  2580. public K floor(K k)
  2581. {
  2582. return floorKey(k);
  2583. }
  2584. public SortedSet<K> headSet(K to)
  2585. {
  2586. return headSet(to, false);
  2587. }
  2588. public NavigableSet<K> headSet(K to, boolean inclusive)
  2589. {
  2590. return headMap(to, inclusive).navigableKeySet();
  2591. }
  2592. public K higher(K k)
  2593. {
  2594. return higherKey(k);
  2595. }
  2596. public K last()
  2597. {
  2598. return lastKey();
  2599. }
  2600. public K lower(K k)
  2601. {
  2602. return lowerKey(k);
  2603. }
  2604. public K pollFirst()
  2605. {
  2606. return pollFirstEntry().getKey();
  2607. }
  2608. public K pollLast()
  2609. {
  2610. return pollLastEntry().getKey();
  2611. }
  2612. public SortedSet<K> subSet(K from, K to)
  2613. {
  2614. return subSet(from, true, to, false);
  2615. }
  2616. public NavigableSet<K> subSet(K from, boolean fromInclusive,
  2617. K to, boolean toInclusive)
  2618. {
  2619. return subMap(from, fromInclusive,
  2620. to, toInclusive).navigableKeySet();
  2621. }
  2622. public SortedSet<K> tailSet(K from)
  2623. {
  2624. return tailSet(from, true);
  2625. }
  2626. public NavigableSet<K> tailSet(K from, boolean inclusive)
  2627. {
  2628. return tailMap(from, inclusive).navigableKeySet();
  2629. }
  2630. } // class NavigableKeySet
  2631. /**
  2632. * Implementation of {@link #descendingSet()} and associated
  2633. * derivatives. This class provides a view of the
  2634. * original backing set in reverse order, and throws
  2635. * {@link IllegalArgumentException} for attempts to
  2636. * access beyond that range.
  2637. *
  2638. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  2639. */
  2640. private static final class DescendingSet<D>
  2641. implements NavigableSet<D>
  2642. {
  2643. /**
  2644. * The backing {@link NavigableSet}.
  2645. */
  2646. private NavigableSet<D> set;
  2647. /**
  2648. * Create a {@link DescendingSet} around the specified
  2649. * set.
  2650. *
  2651. * @param map the set to wrap.
  2652. */
  2653. public DescendingSet(NavigableSet<D> set)
  2654. {
  2655. this.set = set;
  2656. }
  2657. public boolean add(D e)
  2658. {
  2659. return set.add(e);
  2660. }
  2661. public boolean addAll(Collection<? extends D> c)
  2662. {
  2663. return set.addAll(c);
  2664. }
  2665. public D ceiling(D e)
  2666. {
  2667. return set.floor(e);
  2668. }
  2669. public void clear()
  2670. {
  2671. set.clear();
  2672. }
  2673. public Comparator<? super D> comparator()
  2674. {
  2675. return Collections.reverseOrder(set.comparator());
  2676. }
  2677. public boolean contains(Object o)
  2678. {
  2679. return set.contains(o);
  2680. }
  2681. public boolean containsAll(Collection<?> c)
  2682. {
  2683. return set.containsAll(c);
  2684. }
  2685. public Iterator<D> descendingIterator()
  2686. {
  2687. return descendingSet().iterator();
  2688. }
  2689. public NavigableSet<D> descendingSet()
  2690. {
  2691. return set;
  2692. }
  2693. public boolean equals(Object o)
  2694. {
  2695. return set.equals(o);
  2696. }
  2697. public D first()
  2698. {
  2699. return set.last();
  2700. }
  2701. public D floor(D e)
  2702. {
  2703. return set.ceiling(e);
  2704. }
  2705. public int hashCode()
  2706. {
  2707. return set.hashCode();
  2708. }
  2709. public SortedSet<D> headSet(D to)
  2710. {
  2711. return headSet(to, false);
  2712. }
  2713. public NavigableSet<D> headSet(D to, boolean inclusive)
  2714. {
  2715. return new DescendingSet(set.tailSet(to, inclusive));
  2716. }
  2717. public D higher(D e)
  2718. {
  2719. return set.lower(e);
  2720. }
  2721. public boolean isEmpty()
  2722. {
  2723. return set.isEmpty();
  2724. }
  2725. public Iterator<D> iterator()
  2726. {
  2727. return new Iterator<D>()
  2728. {
  2729. /** The last element returned by a next() call. */
  2730. private D last;
  2731. /** The next element that should be returned by next(). */
  2732. private D next = first();
  2733. public boolean hasNext()
  2734. {
  2735. return next != null;
  2736. }
  2737. public D next()
  2738. {
  2739. if (next == null)
  2740. throw new NoSuchElementException();
  2741. last = next;
  2742. next = higher(last);
  2743. return last;
  2744. }
  2745. public void remove()
  2746. {
  2747. if (last == null)
  2748. throw new IllegalStateException();
  2749. DescendingSet.this.remove(last);
  2750. last = null;
  2751. }
  2752. };
  2753. }
  2754. public D last()
  2755. {
  2756. return set.first();
  2757. }
  2758. public D lower(D e)
  2759. {
  2760. return set.higher(e);
  2761. }
  2762. public D pollFirst()
  2763. {
  2764. return set.pollLast();
  2765. }
  2766. public D pollLast()
  2767. {
  2768. return set.pollFirst();
  2769. }
  2770. public boolean remove(Object o)
  2771. {
  2772. return set.remove(o);
  2773. }
  2774. public boolean removeAll(Collection<?> c)
  2775. {
  2776. return set.removeAll(c);
  2777. }
  2778. public boolean retainAll(Collection<?> c)
  2779. {
  2780. return set.retainAll(c);
  2781. }
  2782. public int size()
  2783. {
  2784. return set.size();
  2785. }
  2786. public SortedSet<D> subSet(D from, D to)
  2787. {
  2788. return subSet(from, true, to, false);
  2789. }
  2790. public NavigableSet<D> subSet(D from, boolean fromInclusive,
  2791. D to, boolean toInclusive)
  2792. {
  2793. return new DescendingSet(set.subSet(from, fromInclusive,
  2794. to, toInclusive));
  2795. }
  2796. public SortedSet<D> tailSet(D from)
  2797. {
  2798. return tailSet(from, true);
  2799. }
  2800. public NavigableSet<D> tailSet(D from, boolean inclusive)
  2801. {
  2802. return new DescendingSet(set.headSet(from, inclusive));
  2803. }
  2804. public Object[] toArray()
  2805. {
  2806. D[] array = (D[]) set.toArray();
  2807. Arrays.sort(array, comparator());
  2808. return array;
  2809. }
  2810. public <T> T[] toArray(T[] a)
  2811. {
  2812. T[] array = set.toArray(a);
  2813. Arrays.sort(array, (Comparator<? super T>) comparator());
  2814. return array;
  2815. }
  2816. public String toString()
  2817. {
  2818. CPStringBuilder r = new CPStringBuilder("[");
  2819. final Iterator<D> it = iterator();
  2820. while (it.hasNext())
  2821. {
  2822. final D o = it.next();
  2823. if (o == this)
  2824. r.append("<this>");
  2825. else
  2826. r.append(o);
  2827. r.append(", ");
  2828. }
  2829. r.replace(r.length() - 2, r.length(), "]");
  2830. return r.toString();
  2831. }
  2832. } // class DescendingSet
  2833. private class EntrySet
  2834. extends AbstractSet<Entry<K,V>>
  2835. {
  2836. public int size()
  2837. {
  2838. return size;
  2839. }
  2840. public Iterator<Map.Entry<K,V>> iterator()
  2841. {
  2842. return new TreeIterator(ENTRIES);
  2843. }
  2844. public void clear()
  2845. {
  2846. TreeMap.this.clear();
  2847. }
  2848. public boolean contains(Object o)
  2849. {
  2850. if (! (o instanceof Map.Entry))
  2851. return false;
  2852. Map.Entry<K,V> me = (Map.Entry<K,V>) o;
  2853. Node<K,V> n = getNode(me.getKey());
  2854. return n != nil && AbstractSet.equals(me.getValue(), n.value);
  2855. }
  2856. public boolean remove(Object o)
  2857. {
  2858. if (! (o instanceof Map.Entry))
  2859. return false;
  2860. Map.Entry<K,V> me = (Map.Entry<K,V>) o;
  2861. Node<K,V> n = getNode(me.getKey());
  2862. if (n != nil && AbstractSet.equals(me.getValue(), n.value))
  2863. {
  2864. removeNode(n);
  2865. return true;
  2866. }
  2867. return false;
  2868. }
  2869. }
  2870. private final class NavigableEntrySet
  2871. extends EntrySet
  2872. implements NavigableSet<Entry<K,V>>
  2873. {
  2874. public Entry<K,V> ceiling(Entry<K,V> e)
  2875. {
  2876. return ceilingEntry(e.getKey());
  2877. }
  2878. public Comparator<? super Entry<K,V>> comparator()
  2879. {
  2880. return new Comparator<Entry<K,V>>()
  2881. {
  2882. public int compare(Entry<K,V> t1, Entry<K,V> t2)
  2883. {
  2884. return comparator.compare(t1.getKey(), t2.getKey());
  2885. }
  2886. };
  2887. }
  2888. public Iterator<Entry<K,V>> descendingIterator()
  2889. {
  2890. return descendingSet().iterator();
  2891. }
  2892. public NavigableSet<Entry<K,V>> descendingSet()
  2893. {
  2894. return new DescendingSet(this);
  2895. }
  2896. public Entry<K,V> first()
  2897. {
  2898. return firstEntry();
  2899. }
  2900. public Entry<K,V> floor(Entry<K,V> e)
  2901. {
  2902. return floorEntry(e.getKey());
  2903. }
  2904. public SortedSet<Entry<K,V>> headSet(Entry<K,V> to)
  2905. {
  2906. return headSet(to, false);
  2907. }
  2908. public NavigableSet<Entry<K,V>> headSet(Entry<K,V> to, boolean inclusive)
  2909. {
  2910. return (NavigableSet<Entry<K,V>>) headMap(to.getKey(), inclusive).entrySet();
  2911. }
  2912. public Entry<K,V> higher(Entry<K,V> e)
  2913. {
  2914. return higherEntry(e.getKey());
  2915. }
  2916. public Entry<K,V> last()
  2917. {
  2918. return lastEntry();
  2919. }
  2920. public Entry<K,V> lower(Entry<K,V> e)
  2921. {
  2922. return lowerEntry(e.getKey());
  2923. }
  2924. public Entry<K,V> pollFirst()
  2925. {
  2926. return pollFirstEntry();
  2927. }
  2928. public Entry<K,V> pollLast()
  2929. {
  2930. return pollLastEntry();
  2931. }
  2932. public SortedSet<Entry<K,V>> subSet(Entry<K,V> from, Entry<K,V> to)
  2933. {
  2934. return subSet(from, true, to, false);
  2935. }
  2936. public NavigableSet<Entry<K,V>> subSet(Entry<K,V> from, boolean fromInclusive,
  2937. Entry<K,V> to, boolean toInclusive)
  2938. {
  2939. return (NavigableSet<Entry<K,V>>) subMap(from.getKey(), fromInclusive,
  2940. to.getKey(), toInclusive).entrySet();
  2941. }
  2942. public SortedSet<Entry<K,V>> tailSet(Entry<K,V> from)
  2943. {
  2944. return tailSet(from, true);
  2945. }
  2946. public NavigableSet<Entry<K,V>> tailSet(Entry<K,V> from, boolean inclusive)
  2947. {
  2948. return (NavigableSet<Entry<K,V>>) tailMap(from.getKey(), inclusive).navigableKeySet();
  2949. }
  2950. } // class NavigableEntrySet
  2951. } // class TreeMap