summaryrefslogtreecommitdiff
path: root/java/util/TreeMap.java
blob: 87c532fc1edbd648d459b7939613fe006b53a31e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
/* TreeMap.java -- a class providing a basic Red-Black Tree data structure,
   mapping Object --> Object
   Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006  Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package java.util;

import gnu.java.lang.CPStringBuilder;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * This class provides a red-black tree implementation of the SortedMap
 * interface.  Elements in the Map will be sorted by either a user-provided
 * Comparator object, or by the natural ordering of the keys.
 *
 * The algorithms are adopted from Corman, Leiserson, and Rivest's
 * <i>Introduction to Algorithms.</i>  TreeMap guarantees O(log n)
 * insertion and deletion of elements.  That being said, there is a large
 * enough constant coefficient in front of that "log n" (overhead involved
 * in keeping the tree balanced), that TreeMap may not be the best choice
 * for small collections. If something is already sorted, you may want to
 * just use a LinkedHashMap to maintain the order while providing O(1) access.
 *
 * TreeMap is a part of the JDK1.2 Collections API.  Null keys are allowed
 * only if a Comparator is used which can deal with them; natural ordering
 * cannot cope with null.  Null values are always allowed. Note that the
 * ordering must be <i>consistent with equals</i> to correctly implement
 * the Map interface. If this condition is violated, the map is still
 * well-behaved, but you may have suprising results when comparing it to
 * other maps.<p>
 *
 * This implementation is not synchronized. If you need to share this between
 * multiple threads, do something like:<br>
 * <code>SortedMap m
 *       = Collections.synchronizedSortedMap(new TreeMap(...));</code><p>
 *
 * The iterators are <i>fail-fast</i>, meaning that any structural
 * modification, except for <code>remove()</code> called on the iterator
 * itself, cause the iterator to throw a
 * <code>ConcurrentModificationException</code> rather than exhibit
 * non-deterministic behavior.
 *
 * @author Jon Zeppieri
 * @author Bryce McKinlay
 * @author Eric Blake (ebb9@email.byu.edu)
 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
 * @see Map
 * @see HashMap
 * @see Hashtable
 * @see LinkedHashMap
 * @see Comparable
 * @see Comparator
 * @see Collection
 * @see Collections#synchronizedSortedMap(SortedMap)
 * @since 1.2
 * @status updated to 1.6
 */
public class TreeMap<K, V> extends AbstractMap<K, V>
  implements NavigableMap<K, V>, Cloneable, Serializable
{
  // Implementation note:
  // A red-black tree is a binary search tree with the additional properties
  // that all paths to a leaf node visit the same number of black nodes,
  // and no red node has red children. To avoid some null-pointer checks,
  // we use the special node nil which is always black, has no relatives,
  // and has key and value of null (but is not equal to a mapping of null).

  /**
   * Compatible with JDK 1.2.
   */
  private static final long serialVersionUID = 919286545866124006L;

  /**
   * Color status of a node. Package visible for use by nested classes.
   */
  static final int RED = -1,
                   BLACK = 1;

  /**
   * Sentinal node, used to avoid null checks for corner cases and make the
   * delete rebalance code simpler. The rebalance code must never assign
   * the parent, left, or right of nil, but may safely reassign the color
   * to be black. This object must never be used as a key in a TreeMap, or
   * it will break bounds checking of a SubMap.
   */
  static final Node nil = new Node(null, null, BLACK);
  static
    {
      // Nil is self-referential, so we must initialize it after creation.
      nil.parent = nil;
      nil.left = nil;
      nil.right = nil;
    }

  /**
   * The root node of this TreeMap.
   */
  private transient Node root;

  /**
   * The size of this TreeMap. Package visible for use by nested classes.
   */
  transient int size;

  /**
   * The cache for {@link #entrySet()}.
   */
  private transient Set<Map.Entry<K,V>> entries;

  /**
   * The cache for {@link #descendingMap()}.
   */
  private transient NavigableMap<K,V> descendingMap;

  /**
   * The cache for {@link #navigableKeySet()}.
   */
  private transient NavigableSet<K> nKeys;

  /**
   * Counts the number of modifications this TreeMap has undergone, used
   * by Iterators to know when to throw ConcurrentModificationExceptions.
   * Package visible for use by nested classes.
   */
  transient int modCount;

  /**
   * This TreeMap's comparator, or null for natural ordering.
   * Package visible for use by nested classes.
   * @serial the comparator ordering this tree, or null
   */
  final Comparator<? super K> comparator;

  /**
   * Class to represent an entry in the tree. Holds a single key-value pair,
   * plus pointers to parent and child nodes.
   *
   * @author Eric Blake (ebb9@email.byu.edu)
   */
  private static final class Node<K, V> extends AbstractMap.SimpleEntry<K, V>
  {
    // All fields package visible for use by nested classes.
    /** The color of this node. */
    int color;

    /** The left child node. */
    Node<K, V> left = nil;
    /** The right child node. */
    Node<K, V> right = nil;
    /** The parent node. */
    Node<K, V> parent = nil;

    /**
     * Simple constructor.
     * @param key the key
     * @param value the value
     */
    Node(K key, V value, int color)
    {
      super(key, value);
      this.color = color;
    }
  }

  /**
   * Instantiate a new TreeMap with no elements, using the keys' natural
   * ordering to sort. All entries in the map must have a key which implements
   * Comparable, and which are <i>mutually comparable</i>, otherwise map
   * operations may throw a {@link ClassCastException}. Attempts to use
   * a null key will throw a {@link NullPointerException}.
   *
   * @see Comparable
   */
  public TreeMap()
  {
    this((Comparator) null);
  }

  /**
   * Instantiate a new TreeMap with no elements, using the provided comparator
   * to sort. All entries in the map must have keys which are mutually
   * comparable by the Comparator, otherwise map operations may throw a
   * {@link ClassCastException}.
   *
   * @param c the sort order for the keys of this map, or null
   *        for the natural order
   */
  public TreeMap(Comparator<? super K> c)
  {
    comparator = c;
    fabricateTree(0);
  }

  /**
   * Instantiate a new TreeMap, initializing it with all of the elements in
   * the provided Map.  The elements will be sorted using the natural
   * ordering of the keys. This algorithm runs in n*log(n) time. All entries
   * in the map must have keys which implement Comparable and are mutually
   * comparable, otherwise map operations may throw a
   * {@link ClassCastException}.
   *
   * @param map a Map, whose entries will be put into this TreeMap
   * @throws ClassCastException if the keys in the provided Map are not
   *         comparable
   * @throws NullPointerException if map is null
   * @see Comparable
   */
  public TreeMap(Map<? extends K, ? extends V> map)
  {
    this((Comparator) null);
    putAll(map);
  }

  /**
   * Instantiate a new TreeMap, initializing it with all of the elements in
   * the provided SortedMap.  The elements will be sorted using the same
   * comparator as in the provided SortedMap. This runs in linear time.
   *
   * @param sm a SortedMap, whose entries will be put into this TreeMap
   * @throws NullPointerException if sm is null
   */
  public TreeMap(SortedMap<K, ? extends V> sm)
  {
    this(sm.comparator());
    int pos = sm.size();
    Iterator itr = sm.entrySet().iterator();

    fabricateTree(pos);
    Node node = firstNode();

    while (--pos >= 0)
      {
        Map.Entry me = (Map.Entry) itr.next();
        node.key = me.getKey();
        node.value = me.getValue();
        node = successor(node);
      }
  }

  /**
   * Clears the Map so it has no keys. This is O(1).
   */
  public void clear()
  {
    if (size > 0)
      {
        modCount++;
        root = nil;
        size = 0;
      }
  }

  /**
   * Returns a shallow clone of this TreeMap. The Map itself is cloned,
   * but its contents are not.
   *
   * @return the clone
   */
  public Object clone()
  {
    TreeMap copy = null;
    try
      {
        copy = (TreeMap) super.clone();
      }
    catch (CloneNotSupportedException x)
      {
      }
    copy.entries = null;
    copy.fabricateTree(size);

    Node node = firstNode();
    Node cnode = copy.firstNode();

    while (node != nil)
      {
        cnode.key = node.key;
        cnode.value = node.value;
        node = successor(node);
        cnode = copy.successor(cnode);
      }
    return copy;
  }

  /**
   * Return the comparator used to sort this map, or null if it is by
   * natural order.
   *
   * @return the map's comparator
   */
  public Comparator<? super K> comparator()
  {
    return comparator;
  }

  /**
   * Returns true if the map contains a mapping for the given key.
   *
   * @param key the key to look for
   * @return true if the key has a mapping
   * @throws ClassCastException if key is not comparable to map elements
   * @throws NullPointerException if key is null and the comparator is not
   *         tolerant of nulls
   */
  public boolean containsKey(Object key)
  {
    return getNode((K) key) != nil;
  }

  /**
   * Returns true if the map contains at least one mapping to the given value.
   * This requires linear time.
   *
   * @param value the value to look for
   * @return true if the value appears in a mapping
   */
  public boolean containsValue(Object value)
  {
    Node node = firstNode();
    while (node != nil)
      {
        if (equals(value, node.value))
          return true;
        node = successor(node);
      }
    return false;
  }

  /**
   * Returns a "set view" of this TreeMap's entries. The set is backed by
   * the TreeMap, so changes in one show up in the other.  The set supports
   * element removal, but not element addition.<p>
   *
   * Note that the iterators for all three views, from keySet(), entrySet(),
   * and values(), traverse the TreeMap in sorted sequence.
   *
   * @return a set view of the entries
   * @see #keySet()
   * @see #values()
   * @see Map.Entry
   */
  public Set<Map.Entry<K,V>> entrySet()
  {
    if (entries == null)
      // Create an AbstractSet with custom implementations of those methods
      // that can be overriden easily and efficiently.
      entries = new NavigableEntrySet();
    return entries;
  }

  /**
   * Returns the first (lowest) key in the map.
   *
   * @return the first key
   * @throws NoSuchElementException if the map is empty
   */
  public K firstKey()
  {
    if (root == nil)
      throw new NoSuchElementException();
    return firstNode().key;
  }

  /**
   * Return the value in this TreeMap associated with the supplied key,
   * or <code>null</code> if the key maps to nothing.  NOTE: Since the value
   * could also be null, you must use containsKey to see if this key
   * actually maps to something.
   *
   * @param key the key for which to fetch an associated value
   * @return what the key maps to, if present
   * @throws ClassCastException if key is not comparable to elements in the map
   * @throws NullPointerException if key is null but the comparator does not
   *         tolerate nulls
   * @see #put(Object, Object)
   * @see #containsKey(Object)
   */
  public V get(Object key)
  {
    // Exploit fact that nil.value == null.
    return getNode((K) key).value;
  }

  /**
   * Returns a view of this Map including all entries with keys less than
   * <code>toKey</code>. The returned map is backed by the original, so changes
   * in one appear in the other. The submap will throw an
   * {@link IllegalArgumentException} for any attempt to access or add an
   * element beyond the specified cutoff. The returned map does not include
   * the endpoint; if you want inclusion, pass the successor element
   * or call <code>headMap(toKey, true)</code>.  This is equivalent to
   * calling <code>headMap(toKey, false)</code>.
   *
   * @param toKey the (exclusive) cutoff point
   * @return a view of the map less than the cutoff
   * @throws ClassCastException if <code>toKey</code> is not compatible with
   *         the comparator (or is not Comparable, for natural ordering)
   * @throws NullPointerException if toKey is null, but the comparator does not
   *         tolerate null elements
   */
  public SortedMap<K, V> headMap(K toKey)
  {
    return headMap(toKey, false);
  }

  /**
   * Returns a view of this Map including all entries with keys less than
   * (or equal to, if <code>inclusive</code> is true) <code>toKey</code>.
   * The returned map is backed by the original, so changes in one appear
   * in the other. The submap will throw an {@link IllegalArgumentException}
   * for any attempt to access or add an element beyond the specified cutoff.
   *
   * @param toKey the cutoff point
   * @param inclusive true if the cutoff point should be included.
   * @return a view of the map less than (or equal to, if <code>inclusive</code>
   *         is true) the cutoff.
   * @throws ClassCastException if <code>toKey</code> is not compatible with
   *         the comparator (or is not Comparable, for natural ordering)
   * @throws NullPointerException if toKey is null, but the comparator does not
   *         tolerate null elements
   */
  public NavigableMap<K, V> headMap(K toKey, boolean inclusive)
  {
    return new SubMap((K)(Object)nil, inclusive
                      ? successor(getNode(toKey)).key : toKey);
  }

  /**
   * Returns a "set view" of this TreeMap's keys. The set is backed by the
   * TreeMap, so changes in one show up in the other.  The set supports
   * element removal, but not element addition.
   *
   * @return a set view of the keys
   * @see #values()
   * @see #entrySet()
   */
  public Set<K> keySet()
  {
    if (keys == null)
      // Create an AbstractSet with custom implementations of those methods
      // that can be overriden easily and efficiently.
      keys = new KeySet();
    return keys;
  }

  /**
   * Returns the last (highest) key in the map.
   *
   * @return the last key
   * @throws NoSuchElementException if the map is empty
   */
  public K lastKey()
  {
    if (root == nil)
      throw new NoSuchElementException("empty");
    return lastNode().key;
  }

  /**
   * Puts the supplied value into the Map, mapped by the supplied key.
   * The value may be retrieved by any object which <code>equals()</code>
   * this key. NOTE: Since the prior value could also be null, you must
   * first use containsKey if you want to see if you are replacing the
   * key's mapping.
   *
   * @param key the key used to locate the value
   * @param value the value to be stored in the Map
   * @return the prior mapping of the key, or null if there was none
   * @throws ClassCastException if key is not comparable to current map keys
   * @throws NullPointerException if key is null, but the comparator does
   *         not tolerate nulls
   * @see #get(Object)
   * @see Object#equals(Object)
   */
  public V put(K key, V value)
  {
    Node<K,V> current = root;
    Node<K,V> parent = nil;
    int comparison = 0;

    // Find new node's parent.
    while (current != nil)
      {
        parent = current;
        comparison = compare(key, current.key);
        if (comparison > 0)
          current = current.right;
        else if (comparison < 0)
          current = current.left;
        else // Key already in tree.
          return current.setValue(value);
      }

    // Set up new node.
    Node n = new Node(key, value, RED);
    n.parent = parent;

    // Insert node in tree.
    modCount++;
    size++;
    if (parent == nil)
      {
        // Special case inserting into an empty tree.
        root = n;
        return null;
      }
    if (comparison > 0)
      parent.right = n;
    else
      parent.left = n;

    // Rebalance after insert.
    insertFixup(n);
    return null;
  }

  /**
   * Copies all elements of the given map into this TreeMap.  If this map
   * already has a mapping for a key, the new mapping replaces the current
   * one.
   *
   * @param m the map to be added
   * @throws ClassCastException if a key in m is not comparable with keys
   *         in the map
   * @throws NullPointerException if a key in m is null, and the comparator
   *         does not tolerate nulls
   */
  public void putAll(Map<? extends K, ? extends V> m)
  {
    Iterator itr = m.entrySet().iterator();
    int pos = m.size();
    while (--pos >= 0)
      {
        Map.Entry<K,V> e = (Map.Entry<K,V>) itr.next();
        put(e.getKey(), e.getValue());
      }
  }

  /**
   * Removes from the TreeMap and returns the value which is mapped by the
   * supplied key. If the key maps to nothing, then the TreeMap remains
   * unchanged, and <code>null</code> is returned. NOTE: Since the value
   * could also be null, you must use containsKey to see if you are
   * actually removing a mapping.
   *
   * @param key the key used to locate the value to remove
   * @return whatever the key mapped to, if present
   * @throws ClassCastException if key is not comparable to current map keys
   * @throws NullPointerException if key is null, but the comparator does
   *         not tolerate nulls
   */
  public V remove(Object key)
  {
    Node<K, V> n = getNode((K)key);
    if (n == nil)
      return null;
    // Note: removeNode can alter the contents of n, so save value now.
    V result = n.value;
    removeNode(n);
    return result;
  }

  /**
   * Returns the number of key-value mappings currently in this Map.
   *
   * @return the size
   */
  public int size()
  {
    return size;
  }

  /**
   * Returns a view of this Map including all entries with keys greater or
   * equal to <code>fromKey</code> and less than <code>toKey</code> (a
   * half-open interval). The returned map is backed by the original, so
   * changes in one appear in the other. The submap will throw an
   * {@link IllegalArgumentException} for any attempt to access or add an
   * element beyond the specified cutoffs. The returned map includes the low
   * endpoint but not the high; if you want to reverse this behavior on
   * either end, pass in the successor element or call
   * {@link #subMap(K,boolean,K,boolean)}.  This call is equivalent to
   * <code>subMap(fromKey, true, toKey, false)</code>.
   *
   * @param fromKey the (inclusive) low cutoff point
   * @param toKey the (exclusive) high cutoff point
   * @return a view of the map between the cutoffs
   * @throws ClassCastException if either cutoff is not compatible with
   *         the comparator (or is not Comparable, for natural ordering)
   * @throws NullPointerException if fromKey or toKey is null, but the
   *         comparator does not tolerate null elements
   * @throws IllegalArgumentException if fromKey is greater than toKey
   */
  public SortedMap<K, V> subMap(K fromKey, K toKey)
  {
    return subMap(fromKey, true, toKey, false);
  }

  /**
   * Returns a view of this Map including all entries with keys greater (or
   * equal to, if <code>fromInclusive</code> is true) <code>fromKey</code> and
   * less than (or equal to, if <code>toInclusive</code> is true)
   * <code>toKey</code>. The returned map is backed by the original, so
   * changes in one appear in the other. The submap will throw an
   * {@link IllegalArgumentException} for any attempt to access or add an
   * element beyond the specified cutoffs.
   *
   * @param fromKey the low cutoff point
   * @param fromInclusive true if the low cutoff point should be included.
   * @param toKey the high cutoff point
   * @param toInclusive true if the high cutoff point should be included.
   * @return a view of the map for the specified range.
   * @throws ClassCastException if either cutoff is not compatible with
   *         the comparator (or is not Comparable, for natural ordering)
   * @throws NullPointerException if fromKey or toKey is null, but the
   *         comparator does not tolerate null elements
   * @throws IllegalArgumentException if fromKey is greater than toKey
   */
  public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive,
                                   K toKey, boolean toInclusive)
  {
    return new SubMap(fromInclusive ? fromKey : successor(getNode(fromKey)).key,
                      toInclusive ? successor(getNode(toKey)).key : toKey);
  }

  /**
   * Returns a view of this Map including all entries with keys greater or
   * equal to <code>fromKey</code>. The returned map is backed by the
   * original, so changes in one appear in the other. The submap will throw an
   * {@link IllegalArgumentException} for any attempt to access or add an
   * element beyond the specified cutoff. The returned map includes the
   * endpoint; if you want to exclude it, pass in the successor element.
   * This is equivalent to calling <code>tailMap(fromKey, true)</code>.
   *
   * @param fromKey the (inclusive) low cutoff point
   * @return a view of the map above the cutoff
   * @throws ClassCastException if <code>fromKey</code> is not compatible with
   *         the comparator (or is not Comparable, for natural ordering)
   * @throws NullPointerException if fromKey is null, but the comparator
   *         does not tolerate null elements
   */
  public SortedMap<K, V> tailMap(K fromKey)
  {
    return tailMap(fromKey, true);
  }

  /**
   * Returns a view of this Map including all entries with keys greater or
   * equal to <code>fromKey</code>. The returned map is backed by the
   * original, so changes in one appear in the other. The submap will throw an
   * {@link IllegalArgumentException} for any attempt to access or add an
   * element beyond the specified cutoff. The returned map includes the
   * endpoint; if you want to exclude it, pass in the successor element.
   *
   * @param fromKey the low cutoff point
   * @param inclusive true if the cutoff point should be included.
   * @return a view of the map above the cutoff
   * @throws ClassCastException if <code>fromKey</code> is not compatible with
   *         the comparator (or is not Comparable, for natural ordering)
   * @throws NullPointerException if fromKey is null, but the comparator
   *         does not tolerate null elements
   */
  public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive)
  {
    return new SubMap(inclusive ? fromKey : successor(getNode(fromKey)).key,
                      (K)(Object)nil);
  }

  /**
   * Returns a "collection view" (or "bag view") of this TreeMap's values.
   * The collection is backed by the TreeMap, so changes in one show up
   * in the other.  The collection supports element removal, but not element
   * addition.
   *
   * @return a bag view of the values
   * @see #keySet()
   * @see #entrySet()
   */
  public Collection<V> values()
  {
    if (values == null)
      // We don't bother overriding many of the optional methods, as doing so
      // wouldn't provide any significant performance advantage.
      values = new AbstractCollection<V>()
      {
        public int size()
        {
          return size;
        }

        public Iterator<V> iterator()
        {
          return new TreeIterator(VALUES);
        }

        public void clear()
        {
          TreeMap.this.clear();
        }
      };
    return values;
  }

  /**
   * Compares two elements by the set comparator, or by natural ordering.
   * Package visible for use by nested classes.
   *
   * @param o1 the first object
   * @param o2 the second object
   * @throws ClassCastException if o1 and o2 are not mutually comparable,
   *         or are not Comparable with natural ordering
   * @throws NullPointerException if o1 or o2 is null with natural ordering
   */
  final int compare(K o1, K o2)
  {
    return (comparator == null
            ? ((Comparable) o1).compareTo(o2)
            : comparator.compare(o1, o2));
  }

  /**
   * Maintain red-black balance after deleting a node.
   *
   * @param node the child of the node just deleted, possibly nil
   * @param parent the parent of the node just deleted, never nil
   */
  private void deleteFixup(Node<K,V> node, Node<K,V> parent)
  {
    // if (parent == nil)
    //   throw new InternalError();
    // If a black node has been removed, we need to rebalance to avoid
    // violating the "same number of black nodes on any path" rule. If
    // node is red, we can simply recolor it black and all is well.
    while (node != root && node.color == BLACK)
      {
        if (node == parent.left)
          {
            // Rebalance left side.
            Node<K,V> sibling = parent.right;
            // if (sibling == nil)
            //   throw new InternalError();
            if (sibling.color == RED)
              {
                // Case 1: Sibling is red.
                // Recolor sibling and parent, and rotate parent left.
                sibling.color = BLACK;
                parent.color = RED;
                rotateLeft(parent);
                sibling = parent.right;
              }

            if (sibling.left.color == BLACK && sibling.right.color == BLACK)
              {
                // Case 2: Sibling has no red children.
                // Recolor sibling, and move to parent.
                sibling.color = RED;
                node = parent;
                parent = parent.parent;
              }
            else
              {
                if (sibling.right.color == BLACK)
                  {
                    // Case 3: Sibling has red left child.
                    // Recolor sibling and left child, rotate sibling right.
                    sibling.left.color = BLACK;
                    sibling.color = RED;
                    rotateRight(sibling);
                    sibling = parent.right;
                  }
                // Case 4: Sibling has red right child. Recolor sibling,
                // right child, and parent, and rotate parent left.
                sibling.color = parent.color;
                parent.color = BLACK;
                sibling.right.color = BLACK;
                rotateLeft(parent);
                node = root; // Finished.
              }
          }
        else
          {
            // Symmetric "mirror" of left-side case.
            Node<K,V> sibling = parent.left;
            // if (sibling == nil)
            //   throw new InternalError();
            if (sibling.color == RED)
              {
                // Case 1: Sibling is red.
                // Recolor sibling and parent, and rotate parent right.
                sibling.color = BLACK;
                parent.color = RED;
                rotateRight(parent);
                sibling = parent.left;
              }

            if (sibling.right.color == BLACK && sibling.left.color == BLACK)
              {
                // Case 2: Sibling has no red children.
                // Recolor sibling, and move to parent.
                sibling.color = RED;
                node = parent;
                parent = parent.parent;
              }
            else
              {
                if (sibling.left.color == BLACK)
                  {
                    // Case 3: Sibling has red right child.
                    // Recolor sibling and right child, rotate sibling left.
                    sibling.right.color = BLACK;
                    sibling.color = RED;
                    rotateLeft(sibling);
                    sibling = parent.left;
                  }
                // Case 4: Sibling has red left child. Recolor sibling,
                // left child, and parent, and rotate parent right.
                sibling.color = parent.color;
                parent.color = BLACK;
                sibling.left.color = BLACK;
                rotateRight(parent);
                node = root; // Finished.
              }
          }
      }
    node.color = BLACK;
  }

  /**
   * Construct a perfectly balanced tree consisting of n "blank" nodes. This
   * permits a tree to be generated from pre-sorted input in linear time.
   *
   * @param count the number of blank nodes, non-negative
   */
  private void fabricateTree(final int count)
  {
    if (count == 0)
      {
        root = nil;
        size = 0;
        return;
      }

    // We color every row of nodes black, except for the overflow nodes.
    // I believe that this is the optimal arrangement. We construct the tree
    // in place by temporarily linking each node to the next node in the row,
    // then updating those links to the children when working on the next row.

    // Make the root node.
    root = new Node(null, null, BLACK);
    size = count;
    Node row = root;
    int rowsize;

    // Fill each row that is completely full of nodes.
    for (rowsize = 2; rowsize + rowsize <= count; rowsize <<= 1)
      {
        Node parent = row;
        Node last = null;
        for (int i = 0; i < rowsize; i += 2)
          {
            Node left = new Node(null, null, BLACK);
            Node right = new Node(null, null, BLACK);
            left.parent = parent;
            left.right = right;
            right.parent = parent;
            parent.left = left;
            Node next = parent.right;
            parent.right = right;
            parent = next;
            if (last != null)
              last.right = left;
            last = right;
          }
        row = row.left;
      }

    // Now do the partial final row in red.
    int overflow = count - rowsize;
    Node parent = row;
    int i;
    for (i = 0; i < overflow; i += 2)
      {
        Node left = new Node(null, null, RED);
        Node right = new Node(null, null, RED);
        left.parent = parent;
        right.parent = parent;
        parent.left = left;
        Node next = parent.right;
        parent.right = right;
        parent = next;
      }
    // Add a lone left node if necessary.
    if (i - overflow == 0)
      {
        Node left = new Node(null, null, RED);
        left.parent = parent;
        parent.left = left;
        parent = parent.right;
        left.parent.right = nil;
      }
    // Unlink the remaining nodes of the previous row.
    while (parent != nil)
      {
        Node next = parent.right;
        parent.right = nil;
        parent = next;
      }
  }

  /**
   * Returns the first sorted node in the map, or nil if empty. Package
   * visible for use by nested classes.
   *
   * @return the first node
   */
  final Node<K, V> firstNode()
  {
    // Exploit fact that nil.left == nil.
    Node node = root;
    while (node.left != nil)
      node = node.left;
    return node;
  }

  /**
   * Return the TreeMap.Node associated with key, or the nil node if no such
   * node exists in the tree. Package visible for use by nested classes.
   *
   * @param key the key to search for
   * @return the node where the key is found, or nil
   */
  final Node<K, V> getNode(K key)
  {
    Node<K,V> current = root;
    while (current != nil)
      {
        int comparison = compare(key, current.key);
        if (comparison > 0)
          current = current.right;
        else if (comparison < 0)
          current = current.left;
        else
          return current;
      }
    return current;
  }

  /**
   * Find the "highest" node which is &lt; key. If key is nil, return last
   * node. Package visible for use by nested classes.
   *
   * @param key the upper bound, exclusive
   * @return the previous node
   */
  final Node<K,V> highestLessThan(K key)
  {
    return highestLessThan(key, false);
  }

  /**
   * Find the "highest" node which is &lt; (or equal to,
   * if <code>equal</code> is true) key. If key is nil,
   * return last node. Package visible for use by nested
   * classes.
   *
   * @param key the upper bound, exclusive
   * @param equal true if the key should be returned if found.
   * @return the previous node
   */
  final Node<K,V> highestLessThan(K key, boolean equal)
  {
    if (key == nil)
      return lastNode();

    Node<K,V> last = nil;
    Node<K,V> current = root;
    int comparison = 0;

    while (current != nil)
      {
        last = current;
        comparison = compare(key, current.key);
        if (comparison > 0)
          current = current.right;
        else if (comparison < 0)
          current = current.left;
        else // Exact match.
          return (equal ? last : predecessor(last));
      }
    return comparison < 0 ? predecessor(last) : last;
  }

  /**
   * Maintain red-black balance after inserting a new node.
   *
   * @param n the newly inserted node
   */
  private void insertFixup(Node<K,V> n)
  {
    // Only need to rebalance when parent is a RED node, and while at least
    // 2 levels deep into the tree (ie: node has a grandparent). Remember
    // that nil.color == BLACK.
    while (n.parent.color == RED && n.parent.parent != nil)
      {
        if (n.parent == n.parent.parent.left)
          {
            Node uncle = n.parent.parent.right;
            // Uncle may be nil, in which case it is BLACK.
            if (uncle.color == RED)
              {
                // Case 1. Uncle is RED: Change colors of parent, uncle,
                // and grandparent, and move n to grandparent.
                n.parent.color = BLACK;
                uncle.color = BLACK;
                uncle.parent.color = RED;
                n = uncle.parent;
              }
            else
              {
                if (n == n.parent.right)
                  {
                    // Case 2. Uncle is BLACK and x is right child.
                    // Move n to parent, and rotate n left.
                    n = n.parent;
                    rotateLeft(n);
                  }
                // Case 3. Uncle is BLACK and x is left child.
                // Recolor parent, grandparent, and rotate grandparent right.
                n.parent.color = BLACK;
                n.parent.parent.color = RED;
                rotateRight(n.parent.parent);
              }
          }
        else
          {
            // Mirror image of above code.
            Node uncle = n.parent.parent.left;
            // Uncle may be nil, in which case it is BLACK.
            if (uncle.color == RED)
              {
                // Case 1. Uncle is RED: Change colors of parent, uncle,
                // and grandparent, and move n to grandparent.
                n.parent.color = BLACK;
                uncle.color = BLACK;
                uncle.parent.color = RED;
                n = uncle.parent;
              }
            else
              {
                if (n == n.parent.left)
                {
                    // Case 2. Uncle is BLACK and x is left child.
                    // Move n to parent, and rotate n right.
                    n = n.parent;
                    rotateRight(n);
                  }
                // Case 3. Uncle is BLACK and x is right child.
                // Recolor parent, grandparent, and rotate grandparent left.
                n.parent.color = BLACK;
                n.parent.parent.color = RED;
                rotateLeft(n.parent.parent);
              }
          }
      }
    root.color = BLACK;
  }

  /**
   * Returns the last sorted node in the map, or nil if empty.
   *
   * @return the last node
   */
  private Node<K,V> lastNode()
  {
    // Exploit fact that nil.right == nil.
    Node node = root;
    while (node.right != nil)
      node = node.right;
    return node;
  }

  /**
   * Find the "lowest" node which is &gt;= key. If key is nil, return either
   * nil or the first node, depending on the parameter first.  Package visible
   * for use by nested classes.
   *
   * @param key the lower bound, inclusive
   * @param first true to return the first element instead of nil for nil key
   * @return the next node
   */
  final Node<K,V> lowestGreaterThan(K key, boolean first)
  {
    return lowestGreaterThan(key, first, true);
  }

  /**
   * Find the "lowest" node which is &gt; (or equal to, if <code>equal</code>
   * is true) key. If key is nil, return either nil or the first node, depending
   * on the parameter first.  Package visible for use by nested classes.
   *
   * @param key the lower bound, inclusive
   * @param first true to return the first element instead of nil for nil key
   * @param equal true if the key should be returned if found.
   * @return the next node
   */
  final Node<K,V> lowestGreaterThan(K key, boolean first, boolean equal)
  {
    if (key == nil)
      return first ? firstNode() : nil;

    Node<K,V> last = nil;
    Node<K,V> current = root;
    int comparison = 0;

    while (current != nil)
      {
        last = current;
        comparison = compare(key, current.key);
        if (comparison > 0)
          current = current.right;
        else if (comparison < 0)
          current = current.left;
        else
          return (equal ? current : successor(current));
      }
    return comparison > 0 ? successor(last) : last;
  }

  /**
   * Return the node preceding the given one, or nil if there isn't one.
   *
   * @param node the current node, not nil
   * @return the prior node in sorted order
   */
  private Node<K,V> predecessor(Node<K,V> node)
  {
    if (node.left != nil)
      {
        node = node.left;
        while (node.right != nil)
          node = node.right;
        return node;
      }

    Node parent = node.parent;
    // Exploit fact that nil.left == nil and node is non-nil.
    while (node == parent.left)
      {
        node = parent;
        parent = node.parent;
      }
    return parent;
  }

  /**
   * Construct a tree from sorted keys in linear time. Package visible for
   * use by TreeSet.
   *
   * @param s the stream to read from
   * @param count the number of keys to read
   * @param readValues true to read values, false to insert "" as the value
   * @throws ClassNotFoundException if the underlying stream fails
   * @throws IOException if the underlying stream fails
   * @see #readObject(ObjectInputStream)
   * @see TreeSet#readObject(ObjectInputStream)
   */
  final void putFromObjStream(ObjectInputStream s, int count,
                              boolean readValues)
    throws IOException, ClassNotFoundException
  {
    fabricateTree(count);
    Node node = firstNode();

    while (--count >= 0)
      {
        node.key = s.readObject();
        node.value = readValues ? s.readObject() : "";
        node = successor(node);
      }
  }

  /**
   * Construct a tree from sorted keys in linear time, with values of "".
   * Package visible for use by TreeSet, which uses a value type of String.
   *
   * @param keys the iterator over the sorted keys
   * @param count the number of nodes to insert
   * @see TreeSet#TreeSet(SortedSet)
   */
  final void putKeysLinear(Iterator<K> keys, int count)
  {
    fabricateTree(count);
    Node<K,V> node = firstNode();

    while (--count >= 0)
      {
        node.key = keys.next();
        node.value = (V) "";
        node = successor(node);
      }
  }

  /**
   * Deserializes this object from the given stream.
   *
   * @param s the stream to read from
   * @throws ClassNotFoundException if the underlying stream fails
   * @throws IOException if the underlying stream fails
   * @serialData the <i>size</i> (int), followed by key (Object) and value
   *             (Object) pairs in sorted order
   */
  private void readObject(ObjectInputStream s)
    throws IOException, ClassNotFoundException
  {
    s.defaultReadObject();
    int size = s.readInt();
    putFromObjStream(s, size, true);
  }

  /**
   * Remove node from tree. This will increment modCount and decrement size.
   * Node must exist in the tree. Package visible for use by nested classes.
   *
   * @param node the node to remove
   */
  final void removeNode(Node<K,V> node)
  {
    Node<K,V> splice;
    Node<K,V> child;

    modCount++;
    size--;

    // Find splice, the node at the position to actually remove from the tree.
    if (node.left == nil)
      {
        // Node to be deleted has 0 or 1 children.
        splice = node;
        child = node.right;
      }
    else if (node.right == nil)
      {
        // Node to be deleted has 1 child.
        splice = node;
        child = node.left;
      }
    else
      {
        // Node has 2 children. Splice is node's predecessor, and we swap
        // its contents into node.
        splice = node.left;
        while (splice.right != nil)
          splice = splice.right;
        child = splice.left;
        node.key = splice.key;
        node.value = splice.value;
      }

    // Unlink splice from the tree.
    Node parent = splice.parent;
    if (child != nil)
      child.parent = parent;
    if (parent == nil)
      {
        // Special case for 0 or 1 node remaining.
        root = child;
        return;
      }
    if (splice == parent.left)
      parent.left = child;
    else
      parent.right = child;

    if (splice.color == BLACK)
      deleteFixup(child, parent);
  }

  /**
   * Rotate node n to the left.
   *
   * @param node the node to rotate
   */
  private void rotateLeft(Node<K,V> node)
  {
    Node child = node.right;
    // if (node == nil || child == nil)
    //   throw new InternalError();

    // Establish node.right link.
    node.right = child.left;
    if (child.left != nil)
      child.left.parent = node;

    // Establish child->parent link.
    child.parent = node.parent;
    if (node.parent != nil)
      {
        if (node == node.parent.left)
          node.parent.left = child;
        else
          node.parent.right = child;
      }
    else
      root = child;

    // Link n and child.
    child.left = node;
    node.parent = child;
  }

  /**
   * Rotate node n to the right.
   *
   * @param node the node to rotate
   */
  private void rotateRight(Node<K,V> node)
  {
    Node child = node.left;
    // if (node == nil || child == nil)
    //   throw new InternalError();

    // Establish node.left link.
    node.left = child.right;
    if (child.right != nil)
      child.right.parent = node;

    // Establish child->parent link.
    child.parent = node.parent;
    if (node.parent != nil)
      {
        if (node == node.parent.right)
          node.parent.right = child;
        else
          node.parent.left = child;
      }
    else
      root = child;

    // Link n and child.
    child.right = node;
    node.parent = child;
  }

  /**
   * Return the node following the given one, or nil if there isn't one.
   * Package visible for use by nested classes.
   *
   * @param node the current node, not nil
   * @return the next node in sorted order
   */
  final Node<K,V> successor(Node<K,V> node)
  {
    if (node.right != nil)
      {
        node = node.right;
        while (node.left != nil)
          node = node.left;
        return node;
      }

    Node<K,V> parent = node.parent;
    // Exploit fact that nil.right == nil and node is non-nil.
    while (node == parent.right)
      {
        node = parent;
        parent = parent.parent;
      }
    return parent;
  }

  /**
   * Serializes this object to the given stream.
   *
   * @param s the stream to write to
   * @throws IOException if the underlying stream fails
   * @serialData the <i>size</i> (int), followed by key (Object) and value
   *             (Object) pairs in sorted order
   */
  private void writeObject(ObjectOutputStream s) throws IOException
  {
    s.defaultWriteObject();

    Node node = firstNode();
    s.writeInt(size);
    while (node != nil)
      {
        s.writeObject(node.key);
        s.writeObject(node.value);
        node = successor(node);
      }
  }

  /**
   * Iterate over TreeMap's entries. This implementation is parameterized
   * to give a sequential view of keys, values, or entries.
   *
   * @author Eric Blake (ebb9@email.byu.edu)
   */
  private final class TreeIterator implements Iterator
  {
    /**
     * The type of this Iterator: {@link #KEYS}, {@link #VALUES},
     * or {@link #ENTRIES}.
     */
    private final int type;
    /** The number of modifications to the backing Map that we know about. */
    private int knownMod = modCount;
    /** The last Entry returned by a next() call. */
    private Node last;
    /** The next entry that should be returned by next(). */
    private Node next;
    /**
     * The last node visible to this iterator. This is used when iterating
     * on a SubMap.
     */
    private final Node max;

    /**
     * Construct a new TreeIterator with the supplied type.
     * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
     */
    TreeIterator(int type)
    {
      this(type, firstNode(), nil);
    }

    /**
     * Construct a new TreeIterator with the supplied type. Iteration will
     * be from "first" (inclusive) to "max" (exclusive).
     *
     * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
     * @param first where to start iteration, nil for empty iterator
     * @param max the cutoff for iteration, nil for all remaining nodes
     */
    TreeIterator(int type, Node first, Node max)
    {
      this.type = type;
      this.next = first;
      this.max = max;
    }

    /**
     * Returns true if the Iterator has more elements.
     * @return true if there are more elements
     */
    public boolean hasNext()
    {
      return next != max;
    }

    /**
     * Returns the next element in the Iterator's sequential view.
     * @return the next element
     * @throws ConcurrentModificationException if the TreeMap was modified
     * @throws NoSuchElementException if there is none
     */
    public Object next()
    {
      if (knownMod != modCount)
        throw new ConcurrentModificationException();
      if (next == max)
        throw new NoSuchElementException();
      last = next;
      next = successor(last);

      if (type == VALUES)
        return last.value;
      else if (type == KEYS)
        return last.key;
      return last;
    }

    /**
     * Removes from the backing TreeMap the last element which was fetched
     * with the <code>next()</code> method.
     * @throws ConcurrentModificationException if the TreeMap was modified
     * @throws IllegalStateException if called when there is no last element
     */
    public void remove()
    {
      if (last == null)
        throw new IllegalStateException();
      if (knownMod != modCount)
        throw new ConcurrentModificationException();

      removeNode(last);
      last = null;
      knownMod++;
    }
  } // class TreeIterator

  /**
   * Implementation of {@link #subMap(Object, Object)} and other map
   * ranges. This class provides a view of a portion of the original backing
   * map, and throws {@link IllegalArgumentException} for attempts to
   * access beyond that range.
   *
   * @author Eric Blake (ebb9@email.byu.edu)
   */
  private final class SubMap
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>
  {
    /**
     * The lower range of this view, inclusive, or nil for unbounded.
     * Package visible for use by nested classes.
     */
    final K minKey;

    /**
     * The upper range of this view, exclusive, or nil for unbounded.
     * Package visible for use by nested classes.
     */
    final K maxKey;

    /**
     * The cache for {@link #entrySet()}.
     */
    private Set<Map.Entry<K,V>> entries;

    /**
     * The cache for {@link #descendingMap()}.
     */
    private NavigableMap<K,V> descendingMap;

    /**
     * The cache for {@link #navigableKeySet()}.
     */
    private NavigableSet<K> nKeys;

    /**
     * Create a SubMap representing the elements between minKey (inclusive)
     * and maxKey (exclusive). If minKey is nil, SubMap has no lower bound
     * (headMap). If maxKey is nil, the SubMap has no upper bound (tailMap).
     *
     * @param minKey the lower bound
     * @param maxKey the upper bound
     * @throws IllegalArgumentException if minKey &gt; maxKey
     */
    SubMap(K minKey, K maxKey)
    {
      if (minKey != nil && maxKey != nil && compare(minKey, maxKey) > 0)
        throw new IllegalArgumentException("fromKey > toKey");
      this.minKey = minKey;
      this.maxKey = maxKey;
    }

    /**
     * Check if "key" is in within the range bounds for this SubMap. The
     * lower ("from") SubMap range is inclusive, and the upper ("to") bound
     * is exclusive. Package visible for use by nested classes.
     *
     * @param key the key to check
     * @return true if the key is in range
     */
    boolean keyInRange(K key)
    {
      return ((minKey == nil || compare(key, minKey) >= 0)
              && (maxKey == nil || compare(key, maxKey) < 0));
    }

    public Entry<K,V> ceilingEntry(K key)
    {
      Entry<K,V> n = TreeMap.this.ceilingEntry(key);
      if (n != null && keyInRange(n.getKey()))
        return n;
      return null;
    }

    public K ceilingKey(K key)
    {
      K found = TreeMap.this.ceilingKey(key);
      if (keyInRange(found))
        return found;
      else
        return null;
    }

    public NavigableSet<K> descendingKeySet()
    {
      return descendingMap().navigableKeySet();
    }

    public NavigableMap<K,V> descendingMap()
    {
      if (descendingMap == null)
        descendingMap = new DescendingMap(this);
      return descendingMap;
    }

    public void clear()
    {
      Node next = lowestGreaterThan(minKey, true);
      Node max = lowestGreaterThan(maxKey, false);
      while (next != max)
        {
          Node current = next;
          next = successor(current);
          removeNode(current);
        }
    }

    public Comparator<? super K> comparator()
    {
      return comparator;
    }

    public boolean containsKey(Object key)
    {
      return keyInRange((K) key) && TreeMap.this.containsKey(key);
    }

    public boolean containsValue(Object value)
    {
      Node node = lowestGreaterThan(minKey, true);
      Node max = lowestGreaterThan(maxKey, false);
      while (node != max)
        {
          if (equals(value, node.getValue()))
            return true;
          node = successor(node);
        }
      return false;
    }

    public Set<Map.Entry<K,V>> entrySet()
    {
      if (entries == null)
        // Create an AbstractSet with custom implementations of those methods
        // that can be overriden easily and efficiently.
        entries = new SubMap.NavigableEntrySet();
      return entries;
    }

    public Entry<K,V> firstEntry()
    {
      Node<K,V> node = lowestGreaterThan(minKey, true);
      if (node == nil || ! keyInRange(node.key))
        return null;
      return node;
    }

    public K firstKey()
    {
      Entry<K,V> e = firstEntry();
      if (e == null)
        throw new NoSuchElementException();
      return e.getKey();
    }

    public Entry<K,V> floorEntry(K key)
    {
      Entry<K,V> n = TreeMap.this.floorEntry(key);
      if (n != null && keyInRange(n.getKey()))
        return n;
      return null;
    }

    public K floorKey(K key)
    {
      K found = TreeMap.this.floorKey(key);
      if (keyInRange(found))
        return found;
      else
        return null;
    }

    public V get(Object key)
    {
      if (keyInRange((K) key))
        return TreeMap.this.get(key);
      return null;
    }

    public SortedMap<K,V> headMap(K toKey)
    {
      return headMap(toKey, false);
    }

    public NavigableMap<K,V> headMap(K toKey, boolean inclusive)
    {
      if (!keyInRange(toKey))
        throw new IllegalArgumentException("Key outside submap range");
      return new SubMap(minKey, (inclusive ?
                                 successor(getNode(toKey)).key : toKey));
    }

    public Set<K> keySet()
    {
      if (this.keys == null)
        // Create an AbstractSet with custom implementations of those methods
        // that can be overriden easily and efficiently.
        this.keys = new SubMap.KeySet();
      return this.keys;
    }

    public Entry<K,V> higherEntry(K key)
    {
      Entry<K,V> n = TreeMap.this.higherEntry(key);
      if (n != null && keyInRange(n.getKey()))
        return n;
      return null;
    }

    public K higherKey(K key)
    {
      K found = TreeMap.this.higherKey(key);
      if (keyInRange(found))
        return found;
      else
        return null;
    }

    public Entry<K,V> lastEntry()
    {
      return lowerEntry(maxKey);
    }

    public K lastKey()
    {
      Entry<K,V> e = lastEntry();
      if (e == null)
        throw new NoSuchElementException();
      return e.getKey();
    }

    public Entry<K,V> lowerEntry(K key)
    {
      Entry<K,V> n = TreeMap.this.lowerEntry(key);
      if (n != null && keyInRange(n.getKey()))
        return n;
      return null;
    }

    public K lowerKey(K key)
    {
      K found = TreeMap.this.lowerKey(key);
      if (keyInRange(found))
        return found;
      else
        return null;
    }

    public NavigableSet<K> navigableKeySet()
    {
      if (this.nKeys == null)
        // Create an AbstractSet with custom implementations of those methods
        // that can be overriden easily and efficiently.
        this.nKeys = new SubMap.NavigableKeySet();
      return this.nKeys;
    }

    public Entry<K,V> pollFirstEntry()
    {
      Entry<K,V> e = firstEntry();
      if (e != null)
        removeNode((Node<K,V>) e);
      return e;
    }

    public Entry<K,V> pollLastEntry()
    {
      Entry<K,V> e = lastEntry();
      if (e != null)
        removeNode((Node<K,V>) e);
      return e;
    }

    public V put(K key, V value)
    {
      if (! keyInRange(key))
        throw new IllegalArgumentException("Key outside range");
      return TreeMap.this.put(key, value);
    }

    public V remove(Object key)
    {
      if (keyInRange((K)key))
        return TreeMap.this.remove(key);
      return null;
    }

    public int size()
    {
      Node node = lowestGreaterThan(minKey, true);
      Node max = lowestGreaterThan(maxKey, false);
      int count = 0;
      while (node != max)
        {
          count++;
          node = successor(node);
        }
      return count;
    }

    public SortedMap<K,V> subMap(K fromKey, K toKey)
    {
      return subMap(fromKey, true, toKey, false);
    }

    public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
                                    K toKey, boolean toInclusive)
    {
      if (! keyInRange(fromKey) || ! keyInRange(toKey))
        throw new IllegalArgumentException("key outside range");
      return new SubMap(fromInclusive ? fromKey : successor(getNode(fromKey)).key,
                        toInclusive ? successor(getNode(toKey)).key : toKey);
    }

    public SortedMap<K, V> tailMap(K fromKey)
    {
      return tailMap(fromKey, true);
    }

    public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive)
    {
      if (! keyInRange(fromKey))
        throw new IllegalArgumentException("key outside range");
      return new SubMap(inclusive ? fromKey : successor(getNode(fromKey)).key,
                        maxKey);
    }

    public Collection<V> values()
    {
      if (this.values == null)
        // Create an AbstractCollection with custom implementations of those
        // methods that can be overriden easily and efficiently.
        this.values = new AbstractCollection()
        {
          public int size()
          {
            return SubMap.this.size();
          }

          public Iterator<V> iterator()
          {
            Node first = lowestGreaterThan(minKey, true);
            Node max = lowestGreaterThan(maxKey, false);
            return new TreeIterator(VALUES, first, max);
          }

          public void clear()
          {
            SubMap.this.clear();
          }
        };
      return this.values;
    }

    private class KeySet
      extends AbstractSet<K>
    {
      public int size()
      {
        return SubMap.this.size();
      }

      public Iterator<K> iterator()
      {
        Node first = lowestGreaterThan(minKey, true);
        Node max = lowestGreaterThan(maxKey, false);
        return new TreeIterator(KEYS, first, max);
      }

      public void clear()
      {
        SubMap.this.clear();
      }

      public boolean contains(Object o)
      {
        if (! keyInRange((K) o))
          return false;
        return getNode((K) o) != nil;
      }

      public boolean remove(Object o)
      {
        if (! keyInRange((K) o))
          return false;
        Node n = getNode((K) o);
        if (n != nil)
          {
            removeNode(n);
            return true;
          }
        return false;
      }

    } // class SubMap.KeySet

    private final class NavigableKeySet
      extends KeySet
      implements NavigableSet<K>
    {

      public K ceiling(K k)
      {
        return SubMap.this.ceilingKey(k);
      }

      public Comparator<? super K> comparator()
      {
        return comparator;
      }

      public Iterator<K> descendingIterator()
      {
        return descendingSet().iterator();
      }

      public NavigableSet<K> descendingSet()
      {
        return new DescendingSet(this);
      }

      public K first()
      {
        return SubMap.this.firstKey();
      }

      public K floor(K k)
      {
        return SubMap.this.floorKey(k);
      }

      public SortedSet<K> headSet(K to)
      {
        return headSet(to, false);
      }

      public NavigableSet<K> headSet(K to, boolean inclusive)
      {
        return SubMap.this.headMap(to, inclusive).navigableKeySet();
      }

      public K higher(K k)
      {
        return SubMap.this.higherKey(k);
      }

      public K last()
      {
        return SubMap.this.lastKey();
      }

      public K lower(K k)
      {
        return SubMap.this.lowerKey(k);
      }

      public K pollFirst()
      {
        return SubMap.this.pollFirstEntry().getKey();
      }

      public K pollLast()
      {
        return SubMap.this.pollLastEntry().getKey();
      }

      public SortedSet<K> subSet(K from, K to)
      {
        return subSet(from, true, to, false);
      }

      public NavigableSet<K> subSet(K from, boolean fromInclusive,
                                    K to, boolean toInclusive)
      {
        return SubMap.this.subMap(from, fromInclusive,
                                  to, toInclusive).navigableKeySet();
      }

      public SortedSet<K> tailSet(K from)
      {
        return tailSet(from, true);
      }

      public NavigableSet<K> tailSet(K from, boolean inclusive)
      {
        return SubMap.this.tailMap(from, inclusive).navigableKeySet();
      }

  } // class SubMap.NavigableKeySet

  /**
   * Implementation of {@link #entrySet()}.
   */
  private class EntrySet
    extends AbstractSet<Entry<K,V>>
  {

    public int size()
    {
      return SubMap.this.size();
    }

    public Iterator<Map.Entry<K,V>> iterator()
    {
      Node first = lowestGreaterThan(minKey, true);
      Node max = lowestGreaterThan(maxKey, false);
      return new TreeIterator(ENTRIES, first, max);
    }

    public void clear()
    {
      SubMap.this.clear();
    }

    public boolean contains(Object o)
    {
      if (! (o instanceof Map.Entry))
        return false;
      Map.Entry<K,V> me = (Map.Entry<K,V>) o;
      K key = me.getKey();
      if (! keyInRange(key))
        return false;
      Node<K,V> n = getNode(key);
      return n != nil && AbstractSet.equals(me.getValue(), n.value);
    }

    public boolean remove(Object o)
    {
      if (! (o instanceof Map.Entry))
        return false;
      Map.Entry<K,V> me = (Map.Entry<K,V>) o;
      K key = me.getKey();
      if (! keyInRange(key))
        return false;
      Node<K,V> n = getNode(key);
      if (n != nil && AbstractSet.equals(me.getValue(), n.value))
        {
          removeNode(n);
          return true;
        }
      return false;
    }
  } // class SubMap.EntrySet

    private final class NavigableEntrySet
      extends EntrySet
      implements NavigableSet<Entry<K,V>>
    {

      public Entry<K,V> ceiling(Entry<K,V> e)
      {
        return SubMap.this.ceilingEntry(e.getKey());
      }

      public Comparator<? super Entry<K,V>> comparator()
      {
        return new Comparator<Entry<K,V>>()
          {
            public int compare(Entry<K,V> t1, Entry<K,V> t2)
              {
                return comparator.compare(t1.getKey(), t2.getKey());
              }
          };
      }

      public Iterator<Entry<K,V>> descendingIterator()
      {
        return descendingSet().iterator();
      }

      public NavigableSet<Entry<K,V>> descendingSet()
      {
        return new DescendingSet(this);
      }

      public Entry<K,V> first()
      {
        return SubMap.this.firstEntry();
      }

      public Entry<K,V> floor(Entry<K,V> e)
      {
        return SubMap.this.floorEntry(e.getKey());
      }

      public SortedSet<Entry<K,V>> headSet(Entry<K,V> to)
      {
        return headSet(to, false);
      }

      public NavigableSet<Entry<K,V>> headSet(Entry<K,V> to, boolean inclusive)
      {
        return (NavigableSet<Entry<K,V>>)
          SubMap.this.headMap(to.getKey(), inclusive).entrySet();
      }

      public Entry<K,V> higher(Entry<K,V> e)
      {
        return SubMap.this.higherEntry(e.getKey());
      }

      public Entry<K,V> last()
      {
        return SubMap.this.lastEntry();
      }

      public Entry<K,V> lower(Entry<K,V> e)
      {
        return SubMap.this.lowerEntry(e.getKey());
      }

      public Entry<K,V> pollFirst()
      {
        return SubMap.this.pollFirstEntry();
      }

      public Entry<K,V> pollLast()
      {
        return SubMap.this.pollLastEntry();
      }

      public SortedSet<Entry<K,V>> subSet(Entry<K,V> from, Entry<K,V> to)
      {
        return subSet(from, true, to, false);
      }

      public NavigableSet<Entry<K,V>> subSet(Entry<K,V> from, boolean fromInclusive,
                                             Entry<K,V> to, boolean toInclusive)
      {
        return (NavigableSet<Entry<K,V>>)
          SubMap.this.subMap(from.getKey(), fromInclusive,
                             to.getKey(), toInclusive).entrySet();
      }

      public SortedSet<Entry<K,V>> tailSet(Entry<K,V> from)
      {
        return tailSet(from, true);
      }

      public NavigableSet<Entry<K,V>> tailSet(Entry<K,V> from, boolean inclusive)
      {
        return (NavigableSet<Entry<K,V>>)
          SubMap.this.tailMap(from.getKey(), inclusive).navigableKeySet();
      }

  } // class SubMap.NavigableEntrySet

} // class SubMap

  /**
   * Returns the entry associated with the least or lowest key
   * that is greater than or equal to the specified key, or
   * <code>null</code> if there is no such key.
   *
   * @param key the key relative to the returned entry.
   * @return the entry with the least key greater than or equal
   *         to the given key, or <code>null</code> if there is
   *         no such key.
   * @throws ClassCastException if the specified key can not
   *                            be compared with those in the map.
   * @throws NullPointerException if the key is <code>null</code>
   *                              and this map either uses natural
   *                              ordering or a comparator that does
   *                              not permit null keys.
   * @since 1.6
   */
  public Entry<K,V> ceilingEntry(K key)
  {
    Node<K,V> n = lowestGreaterThan(key, false);
    return (n == nil) ? null : n;
  }

  /**
   * Returns the the least or lowest key that is greater than
   * or equal to the specified key, or <code>null</code> if
   * there is no such key.
   *
   * @param key the key relative to the returned entry.
   * @return the least key greater than or equal to the given key,
   *         or <code>null</code> if there is no such key.
   * @throws ClassCastException if the specified key can not
   *                            be compared with those in the map.
   * @throws NullPointerException if the key is <code>null</code>
   *                              and this map either uses natural
   *                              ordering or a comparator that does
   *                              not permit null keys.
   * @since 1.6
   */
  public K ceilingKey(K key)
  {
    Entry<K,V> e = ceilingEntry(key);
    return (e == null) ? null : e.getKey();
  }

  /**
   * Returns a reverse ordered {@link NavigableSet} view of this
   * map's keys. The set is backed by the {@link TreeMap}, so changes
   * in one show up in the other.  The set supports element removal,
   * but not element addition.
   *
   * @return a reverse ordered set view of the keys.
   * @since 1.6
   * @see #descendingMap()
   */
  public NavigableSet<K> descendingKeySet()
  {
    return descendingMap().navigableKeySet();
  }

  /**
   * Returns a view of the map in reverse order.  The descending map
   * is backed by the original map, so that changes affect both maps.
   * Any changes occurring to either map while an iteration is taking
   * place (with the exception of a {@link Iterator#remove()} operation)
   * result in undefined behaviour from the iteration.  The ordering
   * of the descending map is the same as for a map with a
   * {@link Comparator} given by {@link Collections#reverseOrder()},
   * and calling {@link #descendingMap()} on the descending map itself
   * results in a view equivalent to the original map.
   *
   * @return a reverse order view of the map.
   * @since 1.6
   */
  public NavigableMap<K,V> descendingMap()
  {
    if (descendingMap == null)
      descendingMap = new DescendingMap<K,V>(this);
    return descendingMap;
  }

  /**
   * Returns the entry associated with the least or lowest key
   * in the map, or <code>null</code> if the map is empty.
   *
   * @return the lowest entry, or <code>null</code> if the map
   *         is empty.
   * @since 1.6
   */
  public Entry<K,V> firstEntry()
  {
    Node<K,V> n = firstNode();
    return (n == nil) ? null : n;
  }

  /**
   * Returns the entry associated with the greatest or highest key
   * that is less than or equal to the specified key, or
   * <code>null</code> if there is no such key.
   *
   * @param key the key relative to the returned entry.
   * @return the entry with the greatest key less than or equal
   *         to the given key, or <code>null</code> if there is
   *         no such key.
   * @throws ClassCastException if the specified key can not
   *                            be compared with those in the map.
   * @throws NullPointerException if the key is <code>null</code>
   *                              and this map either uses natural
   *                              ordering or a comparator that does
   *                              not permit null keys.
   * @since 1.6
   */
  public Entry<K,V> floorEntry(K key)
  {
    Node<K,V> n = highestLessThan(key, true);
    return (n == nil) ? null : n;
  }

  /**
   * Returns the the greatest or highest key that is less than
   * or equal to the specified key, or <code>null</code> if
   * there is no such key.
   *
   * @param key the key relative to the returned entry.
   * @return the greatest key less than or equal to the given key,
   *         or <code>null</code> if there is no such key.
   * @throws ClassCastException if the specified key can not
   *                            be compared with those in the map.
   * @throws NullPointerException if the key is <code>null</code>
   *                              and this map either uses natural
   *                              ordering or a comparator that does
   *                              not permit null keys.
   * @since 1.6
   */
  public K floorKey(K key)
  {
    Entry<K,V> e = floorEntry(key);
    return (e == null) ? null : e.getKey();
  }

  /**
   * Returns the entry associated with the least or lowest key
   * that is strictly greater than the specified key, or
   * <code>null</code> if there is no such key.
   *
   * @param key the key relative to the returned entry.
   * @return the entry with the least key greater than
   *         the given key, or <code>null</code> if there is
   *         no such key.
   * @throws ClassCastException if the specified key can not
   *                            be compared with those in the map.
   * @throws NullPointerException if the key is <code>null</code>
   *                              and this map either uses natural
   *                              ordering or a comparator that does
   *                              not permit null keys.
   * @since 1.6
   */
  public Entry<K,V> higherEntry(K key)
  {
    Node<K,V> n = lowestGreaterThan(key, false, false);
    return (n == nil) ? null : n;
  }

  /**
   * Returns the the least or lowest key that is strictly
   * greater than the specified key, or <code>null</code> if
   * there is no such key.
   *
   * @param key the key relative to the returned entry.
   * @return the least key greater than the given key,
   *         or <code>null</code> if there is no such key.
   * @throws ClassCastException if the specified key can not
   *                            be compared with those in the map.
   * @throws NullPointerException if the key is <code>null</code>
   *                              and this map either uses natural
   *                              ordering or a comparator that does
   *                              not permit null keys.
   * @since 1.6
   */
  public K higherKey(K key)
  {
    Entry<K,V> e = higherEntry(key);
    return (e == null) ? null : e.getKey();
  }

  /**
   * Returns the entry associated with the greatest or highest key
   * in the map, or <code>null</code> if the map is empty.
   *
   * @return the highest entry, or <code>null</code> if the map
   *         is empty.
   * @since 1.6
   */
  public Entry<K,V> lastEntry()
  {
    Node<K,V> n = lastNode();
    return (n == nil) ? null : n;
  }

  /**
   * Returns the entry associated with the greatest or highest key
   * that is strictly less than the specified key, or
   * <code>null</code> if there is no such key.
   *
   * @param key the key relative to the returned entry.
   * @return the entry with the greatest key less than
   *         the given key, or <code>null</code> if there is
   *         no such key.
   * @throws ClassCastException if the specified key can not
   *                            be compared with those in the map.
   * @throws NullPointerException if the key is <code>null</code>
   *                              and this map either uses natural
   *                              ordering or a comparator that does
   *                              not permit null keys.
   * @since 1.6
   */
  public Entry<K,V> lowerEntry(K key)
  {
    Node<K,V> n = highestLessThan(key);
    return (n == nil) ? null : n;
  }

  /**
   * Returns the the greatest or highest key that is strictly
   * less than the specified key, or <code>null</code> if
   * there is no such key.
   *
   * @param key the key relative to the returned entry.
   * @return the greatest key less than the given key,
   *         or <code>null</code> if there is no such key.
   * @throws ClassCastException if the specified key can not
   *                            be compared with those in the map.
   * @throws NullPointerException if the key is <code>null</code>
   *                              and this map either uses natural
   *                              ordering or a comparator that does
   *                              not permit null keys.
   * @since 1.6
   */
  public K lowerKey(K key)
  {
    Entry<K,V> e = lowerEntry(key);
    return (e == null) ? null : e.getKey();
  }

  /**
   * Returns a {@link NavigableSet} view of this map's keys. The set is
   * backed by the {@link TreeMap}, so changes in one show up in the other.
   * Any changes occurring to either while an iteration is taking
   * place (with the exception of a {@link Iterator#remove()} operation)
   * result in undefined behaviour from the iteration.  The ordering
   * The set supports element removal, but not element addition.
   *
   * @return a {@link NavigableSet} view of the keys.
   * @since 1.6
   */
  public NavigableSet<K> navigableKeySet()
  {
    if (nKeys == null)
      nKeys = new NavigableKeySet();
    return nKeys;
  }

  /**
   * Removes and returns the entry associated with the least
   * or lowest key in the map, or <code>null</code> if the map
   * is empty.
   *
   * @return the removed first entry, or <code>null</code> if the
   *         map is empty.
   * @since 1.6
   */
  public Entry<K,V> pollFirstEntry()
  {
    Entry<K,V> e = firstEntry();
    if (e != null)
      removeNode((Node<K,V>)e);
    return e;
  }

  /**
   * Removes and returns the entry associated with the greatest
   * or highest key in the map, or <code>null</code> if the map
   * is empty.
   *
   * @return the removed last entry, or <code>null</code> if the
   *         map is empty.
   * @since 1.6
   */
  public Entry<K,V> pollLastEntry()
  {
    Entry<K,V> e = lastEntry();
    if (e != null)
      removeNode((Node<K,V>)e);
    return e;
  }

  /**
   * Implementation of {@link #descendingMap()} and associated
   * derivatives. This class provides a view of the
   * original backing map in reverse order, and throws
   * {@link IllegalArgumentException} for attempts to
   * access beyond that range.
   *
   * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
   */
  private static final class DescendingMap<DK,DV>
    implements NavigableMap<DK,DV>
  {

    /**
     * The cache for {@link #entrySet()}.
     */
    private Set<Map.Entry<DK,DV>> entries;

    /**
     * The cache for {@link #keySet()}.
     */
    private Set<DK> keys;

    /**
     * The cache for {@link #navigableKeySet()}.
     */
    private NavigableSet<DK> nKeys;

    /**
     * The cache for {@link #values()}.
     */
    private Collection<DV> values;

    /**
     * The backing {@link NavigableMap}.
     */
    private NavigableMap<DK,DV> map;

    /**
     * Create a {@link DescendingMap} around the specified
     * map.
     *
     * @param map the map to wrap.
     */
    public DescendingMap(NavigableMap<DK,DV> map)
    {
      this.map = map;
    }

    public Map.Entry<DK,DV> ceilingEntry(DK key)
    {
      return map.floorEntry(key);
    }

    public DK ceilingKey(DK key)
    {
      return map.floorKey(key);
    }

    public void clear()
    {
      map.clear();
    }

    public Comparator<? super DK> comparator()
    {
      return Collections.reverseOrder(map.comparator());
    }

    public boolean containsKey(Object o)
    {
      return map.containsKey(o);
    }

    public boolean containsValue(Object o)
    {
      return map.containsValue(o);
    }

    public NavigableSet<DK> descendingKeySet()
    {
      return descendingMap().navigableKeySet();
    }

    public NavigableMap<DK,DV> descendingMap()
    {
      return map;
    }

    public Set<Entry<DK,DV>> entrySet()
    {
      if (entries == null)
        entries =
          new DescendingSet<Entry<DK,DV>>((NavigableSet<Entry<DK,DV>>)
                                          map.entrySet());
      return entries;
    }

    public boolean equals(Object o)
    {
      return map.equals(o);
    }

    public Entry<DK,DV> firstEntry()
    {
      return map.lastEntry();
    }

    public DK firstKey()
    {
      return map.lastKey();
    }

    public Entry<DK,DV> floorEntry(DK key)
    {
      return map.ceilingEntry(key);
    }

    public DK floorKey(DK key)
    {
      return map.ceilingKey(key);
    }

    public DV get(Object key)
    {
      return map.get(key);
    }

    public int hashCode()
    {
      return map.hashCode();
    }

    public SortedMap<DK,DV> headMap(DK toKey)
    {
      return headMap(toKey, false);
    }

    public NavigableMap<DK,DV> headMap(DK toKey, boolean inclusive)
    {
      return new DescendingMap(map.tailMap(toKey, inclusive));
    }

    public Entry<DK,DV> higherEntry(DK key)
    {
      return map.lowerEntry(key);
    }

    public DK higherKey(DK key)
    {
      return map.lowerKey(key);
    }

    public Set<DK> keySet()
    {
      if (keys == null)
        keys = new DescendingSet<DK>(map.navigableKeySet());
      return keys;
    }

    public boolean isEmpty()
    {
      return map.isEmpty();
    }

    public Entry<DK,DV> lastEntry()
    {
      return map.firstEntry();
    }

    public DK lastKey()
    {
      return map.firstKey();
    }

    public Entry<DK,DV> lowerEntry(DK key)
    {
      return map.higherEntry(key);
    }

    public DK lowerKey(DK key)
    {
      return map.higherKey(key);
    }

    public NavigableSet<DK> navigableKeySet()
    {
      if (nKeys == null)
        nKeys = new DescendingSet<DK>(map.navigableKeySet());
      return nKeys;
    }

    public Entry<DK,DV> pollFirstEntry()
    {
      return pollLastEntry();
    }

    public Entry<DK,DV> pollLastEntry()
    {
      return pollFirstEntry();
    }

    public DV put(DK key, DV value)
    {
      return map.put(key, value);
    }

    public void putAll(Map<? extends DK, ? extends DV> m)
    {
      map.putAll(m);
    }

    public DV remove(Object key)
    {
      return map.remove(key);
    }

    public int size()
    {
      return map.size();
    }

    public SortedMap<DK,DV> subMap(DK fromKey, DK toKey)
    {
      return subMap(fromKey, true, toKey, false);
    }

    public NavigableMap<DK,DV> subMap(DK fromKey, boolean fromInclusive,
                                      DK toKey, boolean toInclusive)
    {
      return new DescendingMap(map.subMap(fromKey, fromInclusive,
                                          toKey, toInclusive));
    }

    public SortedMap<DK,DV> tailMap(DK fromKey)
    {
      return tailMap(fromKey, true);
    }

    public NavigableMap<DK,DV> tailMap(DK fromKey, boolean inclusive)
    {
      return new DescendingMap(map.headMap(fromKey, inclusive));
    }

    public String toString()
    {
      CPStringBuilder r = new CPStringBuilder("{");
      final Iterator<Entry<DK,DV>> it = entrySet().iterator();
      while (it.hasNext())
      {
        final Entry<DK,DV> e = it.next();
        r.append(e.getKey());
        r.append('=');
        r.append(e.getValue());
        r.append(", ");
      }
      r.replace(r.length() - 2, r.length(), "}");
      return r.toString();
    }

    public Collection<DV> values()
    {
      if (values == null)
        // Create an AbstractCollection with custom implementations of those
        // methods that can be overriden easily and efficiently.
        values = new AbstractCollection()
          {
            public int size()
            {
              return DescendingMap.this.size();
            }

            public Iterator<DV> iterator()
            {
              return new Iterator<DV>()
                {
                  /** The last Entry returned by a next() call. */
                  private Entry<DK,DV> last;

                  /** The next entry that should be returned by next(). */
                  private Entry<DK,DV> next = firstEntry();

                  public boolean hasNext()
                  {
                    return next != null;
                  }

                  public DV next()
                  {
                    if (next == null)
                      throw new NoSuchElementException();
                    last = next;
                    next = higherEntry(last.getKey());

                    return last.getValue();
                  }

                  public void remove()
                  {
                    if (last == null)
                      throw new IllegalStateException();

                    DescendingMap.this.remove(last.getKey());
                    last = null;
                  }
                };
            }

            public void clear()
            {
              DescendingMap.this.clear();
            }
          };
      return values;
    }

  } // class DescendingMap

  /**
   * Implementation of {@link #keySet()}.
   */
  private class KeySet
    extends AbstractSet<K>
  {

    public int size()
    {
      return size;
    }

    public Iterator<K> iterator()
    {
      return new TreeIterator(KEYS);
    }

    public void clear()
    {
      TreeMap.this.clear();
    }

    public boolean contains(Object o)
    {
      return containsKey(o);
    }

    public boolean remove(Object key)
    {
      Node<K,V> n = getNode((K) key);
      if (n == nil)
        return false;
      removeNode(n);
      return true;
    }
  } // class KeySet

  /**
   * Implementation of {@link #navigableKeySet()}.
   *
   * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
   */
  private final class NavigableKeySet
    extends KeySet
    implements NavigableSet<K>
  {

    public K ceiling(K k)
    {
      return ceilingKey(k);
    }

    public Comparator<? super K> comparator()
    {
      return comparator;
    }

    public Iterator<K> descendingIterator()
    {
      return descendingSet().iterator();
    }

    public NavigableSet<K> descendingSet()
    {
      return new DescendingSet<K>(this);
    }

    public K first()
    {
      return firstKey();
    }

    public K floor(K k)
    {
      return floorKey(k);
    }

    public SortedSet<K> headSet(K to)
    {
      return headSet(to, false);
    }

    public NavigableSet<K> headSet(K to, boolean inclusive)
    {
      return headMap(to, inclusive).navigableKeySet();
    }

    public K higher(K k)
    {
      return higherKey(k);
    }

    public K last()
    {
      return lastKey();
    }

    public K lower(K k)
    {
      return lowerKey(k);
    }

    public K pollFirst()
    {
      return pollFirstEntry().getKey();
    }

    public K pollLast()
    {
      return pollLastEntry().getKey();
    }

    public SortedSet<K> subSet(K from, K to)
    {
      return subSet(from, true, to, false);
    }

    public NavigableSet<K> subSet(K from, boolean fromInclusive,
                                  K to, boolean toInclusive)
    {
      return subMap(from, fromInclusive,
                    to, toInclusive).navigableKeySet();
    }

    public SortedSet<K> tailSet(K from)
    {
      return tailSet(from, true);
    }

    public NavigableSet<K> tailSet(K from, boolean inclusive)
    {
      return tailMap(from, inclusive).navigableKeySet();
    }


  } // class NavigableKeySet

  /**
   * Implementation of {@link #descendingSet()} and associated
   * derivatives. This class provides a view of the
   * original backing set in reverse order, and throws
   * {@link IllegalArgumentException} for attempts to
   * access beyond that range.
   *
   * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
   */
  private static final class DescendingSet<D>
    implements NavigableSet<D>
  {

    /**
     * The backing {@link NavigableSet}.
     */
    private NavigableSet<D> set;

    /**
     * Create a {@link DescendingSet} around the specified
     * set.
     *
     * @param map the set to wrap.
     */
    public DescendingSet(NavigableSet<D> set)
    {
      this.set = set;
    }

    public boolean add(D e)
    {
      return set.add(e);
    }

    public boolean addAll(Collection<? extends D> c)
    {
      return set.addAll(c);
    }

    public D ceiling(D e)
    {
      return set.floor(e);
    }

    public void clear()
    {
      set.clear();
    }

    public Comparator<? super D> comparator()
    {
      return Collections.reverseOrder(set.comparator());
    }

    public boolean contains(Object o)
    {
      return set.contains(o);
    }

    public boolean containsAll(Collection<?> c)
    {
      return set.containsAll(c);
    }

    public Iterator<D> descendingIterator()
    {
      return descendingSet().iterator();
    }

    public NavigableSet<D> descendingSet()
    {
      return set;
    }

    public boolean equals(Object o)
    {
      return set.equals(o);
    }

    public D first()
    {
      return set.last();
    }

    public D floor(D e)
    {
      return set.ceiling(e);
    }

    public int hashCode()
    {
      return set.hashCode();
    }

    public SortedSet<D> headSet(D to)
    {
      return headSet(to, false);
    }

    public NavigableSet<D> headSet(D to, boolean inclusive)
    {
      return new DescendingSet(set.tailSet(to, inclusive));
    }

    public D higher(D e)
    {
      return set.lower(e);
    }

    public boolean isEmpty()
    {
      return set.isEmpty();
    }

    public Iterator<D> iterator()
    {
      return new Iterator<D>()
        {

          /** The last element returned by a next() call. */
          private D last;

          /** The next element that should be returned by next(). */
          private D next = first();

          public boolean hasNext()
          {
            return next != null;
          }

          public D next()
          {
            if (next == null)
              throw new NoSuchElementException();
            last = next;
            next = higher(last);

            return last;
          }

          public void remove()
          {
            if (last == null)
              throw new IllegalStateException();

            DescendingSet.this.remove(last);
            last = null;
          }
        };
    }

    public D last()
    {
      return set.first();
    }

    public D lower(D e)
    {
      return set.higher(e);
    }

    public D pollFirst()
    {
      return set.pollLast();
    }

    public D pollLast()
    {
      return set.pollFirst();
    }

    public boolean remove(Object o)
    {
      return set.remove(o);
    }

    public boolean removeAll(Collection<?> c)
    {
      return set.removeAll(c);
    }

    public boolean retainAll(Collection<?> c)
    {
      return set.retainAll(c);
    }

    public int size()
    {
      return set.size();
    }

    public SortedSet<D> subSet(D from, D to)
    {
      return subSet(from, true, to, false);
    }

    public NavigableSet<D> subSet(D from, boolean fromInclusive,
                                  D to, boolean toInclusive)
    {
      return new DescendingSet(set.subSet(from, fromInclusive,
                                          to, toInclusive));
    }

    public SortedSet<D> tailSet(D from)
    {
      return tailSet(from, true);
    }

    public NavigableSet<D> tailSet(D from, boolean inclusive)
    {
      return new DescendingSet(set.headSet(from, inclusive));
    }

    public Object[] toArray()
    {
      D[] array = (D[]) set.toArray();
      Arrays.sort(array, comparator());
      return array;
    }

    public <T> T[] toArray(T[] a)
    {
      T[] array = set.toArray(a);
      Arrays.sort(array, (Comparator<? super T>) comparator());
      return array;
    }

    public String toString()
    {
      CPStringBuilder r = new CPStringBuilder("[");
      final Iterator<D> it = iterator();
      while (it.hasNext())
      {
        final D o = it.next();
        if (o == this)
          r.append("<this>");
        else
          r.append(o);
        r.append(", ");
      }
      r.replace(r.length() - 2, r.length(), "]");
      return r.toString();
    }

  } // class DescendingSet

  private class EntrySet
    extends AbstractSet<Entry<K,V>>
  {
    public int size()
    {
      return size;
    }

    public Iterator<Map.Entry<K,V>> iterator()
    {
      return new TreeIterator(ENTRIES);
    }

    public void clear()
    {
      TreeMap.this.clear();
    }

    public boolean contains(Object o)
    {
      if (! (o instanceof Map.Entry))
        return false;
      Map.Entry<K,V> me = (Map.Entry<K,V>) o;
      Node<K,V> n = getNode(me.getKey());
      return n != nil && AbstractSet.equals(me.getValue(), n.value);
    }

    public boolean remove(Object o)
    {
      if (! (o instanceof Map.Entry))
        return false;
      Map.Entry<K,V> me = (Map.Entry<K,V>) o;
      Node<K,V> n = getNode(me.getKey());
      if (n != nil && AbstractSet.equals(me.getValue(), n.value))
        {
          removeNode(n);
          return true;
        }
      return false;
    }
  }

  private final class NavigableEntrySet
    extends EntrySet
    implements NavigableSet<Entry<K,V>>
  {

    public Entry<K,V> ceiling(Entry<K,V> e)
    {
      return ceilingEntry(e.getKey());
    }

    public Comparator<? super Entry<K,V>> comparator()
    {
      return new Comparator<Entry<K,V>>()
        {
          public int compare(Entry<K,V> t1, Entry<K,V> t2)
          {
            return comparator.compare(t1.getKey(), t2.getKey());
          }
        };
    }

    public Iterator<Entry<K,V>> descendingIterator()
    {
      return descendingSet().iterator();
    }

    public NavigableSet<Entry<K,V>> descendingSet()
    {
      return new DescendingSet(this);
    }

    public Entry<K,V> first()
    {
      return firstEntry();
    }

    public Entry<K,V> floor(Entry<K,V> e)
    {
      return floorEntry(e.getKey());
    }

    public SortedSet<Entry<K,V>> headSet(Entry<K,V> to)
    {
      return headSet(to, false);
    }

    public NavigableSet<Entry<K,V>> headSet(Entry<K,V> to, boolean inclusive)
    {
      return (NavigableSet<Entry<K,V>>) headMap(to.getKey(), inclusive).entrySet();
    }

    public Entry<K,V> higher(Entry<K,V> e)
    {
      return higherEntry(e.getKey());
    }

    public Entry<K,V> last()
    {
      return lastEntry();
    }

    public Entry<K,V> lower(Entry<K,V> e)
    {
      return lowerEntry(e.getKey());
    }

    public Entry<K,V> pollFirst()
    {
      return pollFirstEntry();
    }

    public Entry<K,V> pollLast()
    {
      return pollLastEntry();
    }

    public SortedSet<Entry<K,V>> subSet(Entry<K,V> from, Entry<K,V> to)
    {
      return subSet(from, true, to, false);
    }

    public NavigableSet<Entry<K,V>> subSet(Entry<K,V> from, boolean fromInclusive,
                                           Entry<K,V> to, boolean toInclusive)
    {
      return (NavigableSet<Entry<K,V>>) subMap(from.getKey(), fromInclusive,
                                               to.getKey(), toInclusive).entrySet();
    }

    public SortedSet<Entry<K,V>> tailSet(Entry<K,V> from)
    {
      return tailSet(from, true);
    }

    public NavigableSet<Entry<K,V>> tailSet(Entry<K,V> from, boolean inclusive)
    {
      return (NavigableSet<Entry<K,V>>) tailMap(from.getKey(), inclusive).navigableKeySet();
    }

  } // class NavigableEntrySet

} // class TreeMap