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
|
/* Collections.java -- Utility class with methods to operate on collections
Copyright (C) 1998, 1999, 2000 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., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
As a special exception, if you link this library with other files to
produce an executable, this library does not by itself cause the
resulting executable to be covered by the GNU General Public License.
This exception does not however invalidate any other reasons why the
executable file might be covered by the GNU General Public License. */
// TO DO:
// ~ Serialization is very much broken. Blame Sun for not specifying it.
// ~ The synchronized* and unmodifiable* methods don't have doc-comments.
package java.util;
import java.io.Serializable;
/**
* Utility class consisting of static methods that operate on, or return
* Collections. Contains methods to sort, search, reverse, fill and shuffle
* Collections, methods to facilitate interoperability with legacy APIs that
* are unaware of collections, a method to return a list which consists of
* multiple copies of one element, and methods which "wrap" collections to give
* them extra properties, such as thread-safety and unmodifiability.
*/
public class Collections
{
/**
* This class is non-instantiable.
*/
private Collections()
{
}
/**
* An immutable, empty Set.
* Note: This implementation isn't Serializable, although it should be by the
* spec.
*/
public static final Set EMPTY_SET = new AbstractSet()
{
public int size()
{
return 0;
}
// This is really cheating! I think it's perfectly valid, though - the
// more conventional code is here, commented out, in case anyone disagrees.
public Iterator iterator()
{
return EMPTY_LIST.iterator();
}
// public Iterator iterator() {
// return new Iterator() {
//
// public boolean hasNext() {
// return false;
// }
//
// public Object next() {
// throw new NoSuchElementException();
// }
//
// public void remove() {
// throw new UnsupportedOperationException();
// }
// };
// }
};
/**
* An immutable, empty List.
* Note: This implementation isn't serializable, although it should be by the
* spec.
*/
public static final List EMPTY_LIST = new AbstractList()
{
public int size()
{
return 0;
}
public Object get(int index)
{
throw new IndexOutOfBoundsException();
}
};
/**
* An immutable, empty Map.
* Note: This implementation isn't serializable, although it should be by the
* spec.
*/
public static final Map EMPTY_MAP = new AbstractMap()
{
public Set entrySet()
{
return EMPTY_SET;
}
};
/**
* Compare two objects with or without a Comparator. If c is null, uses the
* natural ordering. Slightly slower than doing it inline if the JVM isn't
* clever, but worth it for removing a duplicate of the search code.
* Note: This same code is used in Arrays (for sort as well as search)
*/
private static int compare(Object o1, Object o2, Comparator c)
{
if (c == null)
{
return ((Comparable) o1).compareTo(o2);
}
else
{
return c.compare(o1, o2);
}
}
/**
* The hard work for the search routines. If the Comparator given is null,
* uses the natural ordering of the elements.
*/
private static int search(List l, Object key, final Comparator c)
{
int pos = 0;
// We use a linear search using an iterator if we can guess that the list
// is sequential-access.
if (l instanceof AbstractSequentialList)
{
ListIterator itr = l.listIterator();
for (int i = l.size() - 1; i >= 0; --i)
{
final int d = compare(key, itr.next(), c);
if (d == 0)
{
return pos;
}
else if (d < 0)
{
return -pos - 1;
}
pos++;
}
// We assume the list is random-access, and use a binary search
}
else
{
int low = 0;
int hi = l.size() - 1;
while (low <= hi)
{
pos = (low + hi) >> 1;
final int d = compare(key, l.get(pos), c);
if (d == 0)
{
return pos;
}
else if (d < 0)
{
hi = pos - 1;
}
else
{
low = ++pos; // This gets the insertion point right on the last loop
}
}
}
// If we failed to find it, we do the same whichever search we did.
return -pos - 1;
}
/**
* Perform a binary search of a List for a key, using the natural ordering of
* the elements. The list must be sorted (as by the sort() method) - if it is
* not, the behaviour of this method is undefined, and may be an infinite
* loop. Further, the key must be comparable with every item in the list. If
* the list contains the key more than once, any one of them may be found. To
* avoid pathological behaviour on sequential-access lists, a linear search
* is used if (l instanceof AbstractSequentialList). Note: although the
* specification allows for an infinite loop if the list is unsorted, it will
* not happen in this (Classpath) implementation.
*
* @param l the list to search (must be sorted)
* @param key the value to search for
* @returns the index at which the key was found, or -n-1 if it was not
* found, where n is the index of the first value higher than key or
* a.length if there is no such value.
* @exception ClassCastException if key could not be compared with one of the
* elements of l
* @exception NullPointerException if a null element has compareTo called
*/
public static int binarySearch(List l, Object key)
{
return search(l, key, null);
}
/**
* Perform a binary search of a List for a key, using a supplied Comparator.
* The list must be sorted (as by the sort() method with the same Comparator)
* - if it is not, the behaviour of this method is undefined, and may be an
* infinite loop. Further, the key must be comparable with every item in the
* list. If the list contains the key more than once, any one of them may be
* found. To avoid pathological behaviour on sequential-access lists, a
* linear search is used if (l instanceof AbstractSequentialList). Note:
* although the specification allows for an infinite loop if the list is
* unsorted, it will not happen in this (Classpath) implementation.
*
* @param l the list to search (must be sorted)
* @param key the value to search for
* @param c the comparator by which the list is sorted
* @returns the index at which the key was found, or -n-1 if it was not
* found, where n is the index of the first value higher than key or
* a.length if there is no such value.
* @exception ClassCastException if key could not be compared with one of the
* elements of l
*/
public static int binarySearch(List l, Object key, Comparator c)
{
if (c == null)
{
throw new NullPointerException();
}
return search(l, key, c);
}
/**
* Copy one list to another. If the destination list is longer than the
* source list, the remaining elements are unaffected. This method runs in
* linear time.
*
* @param dest the destination list.
* @param source the source list.
* @exception IndexOutOfBoundsException if the destination list is shorter
* than the source list (the elements that can be copied will be, prior to
* the exception being thrown).
* @exception UnsupportedOperationException if dest.listIterator() does not
* support the set operation.
*/
public static void copy(List dest, List source)
{
Iterator i1 = source.iterator();
ListIterator i2 = dest.listIterator();
try
{
for (int i = source.size() - 1; i >= 0; --i)
{
i2.next();
i2.set(i1.next());
}
}
catch (NoSuchElementException x)
{
throw new IndexOutOfBoundsException("Source doesn't fit in dest.");
}
}
/**
* Returns an Enumeration over a collection. This allows interoperability
* with legacy APIs that require an Enumeration as input.
*
* @param c the Collection to iterate over
* @returns an Enumeration backed by an Iterator over c
*/
public static Enumeration enumeration(Collection c)
{
final Iterator i = c.iterator();
return new Enumeration()
{
public final boolean hasMoreElements()
{
return i.hasNext();
}
public final Object nextElement()
{
return i.next();
}
};
}
/**
* Replace every element of a list with a given value. This method runs in
* linear time.
*
* @param l the list to fill.
* @param val the object to vill the list with.
* @exception UnsupportedOperationException if l.listIterator() does not
* support the set operation.
*/
public static void fill(List l, Object val)
{
ListIterator itr = l.listIterator();
for (int i = l.size() - 1; i >= 0; --i)
{
itr.next();
itr.set(val);
}
}
/**
* Find the maximum element in a Collection, according to the natural
* ordering of the elements. This implementation iterates over the
* Collection, so it works in linear time.
*
* @param c the Collection to find the maximum element of
* @returns the maximum element of c
* @exception NoSuchElementException if c is empty
* @exception ClassCastException if elements in c are not mutually comparable
* @exception NullPointerException if null.compareTo is called
*/
public static Object max(Collection c)
{
Iterator itr = c.iterator();
Comparable max = (Comparable) itr.next(); // throws NoSuchElementException
int csize = c.size();
for (int i = 1; i < csize; i++)
{
Object o = itr.next();
if (max.compareTo(o) < 0)
{
max = (Comparable) o;
}
}
return max;
}
/**
* Find the maximum element in a Collection, according to a specified
* Comparator. This implementation iterates over the Collection, so it
* works in linear time.
*
* @param c the Collection to find the maximum element of
* @param order the Comparator to order the elements by
* @returns the maximum element of c
* @exception NoSuchElementException if c is empty
* @exception ClassCastException if elements in c are not mutually comparable
*/
public static Object max(Collection c, Comparator order)
{
Iterator itr = c.iterator();
Object max = itr.next(); // throws NoSuchElementException
int csize = c.size();
for (int i = 1; i < csize; i++)
{
Object o = itr.next();
if (order.compare(max, o) < 0)
max = o;
}
return max;
}
/**
* Find the minimum element in a Collection, according to the natural
* ordering of the elements. This implementation iterates over the
* Collection, so it works in linear time.
*
* @param c the Collection to find the minimum element of
* @returns the minimum element of c
* @exception NoSuchElementException if c is empty
* @exception ClassCastException if elements in c are not mutually comparable
* @exception NullPointerException if null.compareTo is called
*/
public static Object min(Collection c)
{
Iterator itr = c.iterator();
Comparable min = (Comparable) itr.next(); // throws NoSuchElementException
int csize = c.size();
for (int i = 1; i < csize; i++)
{
Object o = itr.next();
if (min.compareTo(o) > 0)
min = (Comparable) o;
}
return min;
}
/**
* Find the minimum element in a Collection, according to a specified
* Comparator. This implementation iterates over the Collection, so it
* works in linear time.
*
* @param c the Collection to find the minimum element of
* @param order the Comparator to order the elements by
* @returns the minimum element of c
* @exception NoSuchElementException if c is empty
* @exception ClassCastException if elements in c are not mutually comparable
*/
public static Object min(Collection c, Comparator order)
{
Iterator itr = c.iterator();
Object min = itr.next(); // throws NoSuchElementExcception
int csize = c.size();
for (int i = 1; i < csize; i++)
{
Object o = itr.next();
if (order.compare(min, o) > 0)
min = o;
}
return min;
}
/**
* Creates an immutable list consisting of the same object repeated n times.
* The returned object is tiny, consisting of only a single reference to the
* object and a count of the number of elements. It is Serializable.
*
* @param n the number of times to repeat the object
* @param o the object to repeat
* @returns a List consisting of n copies of o
* @throws IllegalArgumentException if n < 0
*/
// It's not Serializable, because the serialized form is unspecced.
// Also I'm only assuming that it should be because I don't think it's
// stated - I just would be amazed if it isn't...
public static List nCopies(final int n, final Object o)
{
// Check for insane arguments
if (n < 0)
{
throw new IllegalArgumentException();
}
// Create a minimal implementation of List
return new AbstractList()
{
public int size()
{
return n;
}
public Object get(int index)
{
if (index < 0 || index >= n)
{
throw new IndexOutOfBoundsException();
}
return o;
}
};
}
/**
* Reverse a given list. This method works in linear time.
*
* @param l the list to reverse.
* @exception UnsupportedOperationException if l.listIterator() does not
* support the set operation.
*/
public static void reverse(List l)
{
ListIterator i1 = l.listIterator();
int pos1 = 0;
int pos2 = l.size();
ListIterator i2 = l.listIterator(pos2);
while (pos1 < pos2)
{
Object o = i1.next();
i1.set(i2.previous());
i2.set(o);
++pos1;
--pos2;
}
}
/**
* Get a comparator that implements the reverse of natural ordering. This is
* intended to make it easy to sort into reverse order, by simply passing
* Collections.reverseOrder() to the sort method. The return value of this
* method is Serializable.
*/
// The return value isn't Serializable, because the spec is broken.
public static Comparator reverseOrder()
{
return new Comparator()
{
public int compare(Object a, Object b)
{
return -((Comparable) a).compareTo(b);
}
};
}
/**
* Shuffle a list according to a default source of randomness. The algorithm
* used would result in a perfectly fair shuffle (that is, each element would
* have an equal chance of ending up in any position) with a perfect source
* of randomness; in practice the results are merely very close to perfect.
* <p>
* This method operates in linear time on a random-access list, but may take
* quadratic time on a sequential-access list.
* Note: this (classpath) implementation will never take quadratic time, but
* it does make a copy of the list. This is in line with the behaviour of the
* sort methods and seems preferable.
*
* @param l the list to shuffle.
* @exception UnsupportedOperationException if l.listIterator() does not
* support the set operation.
*/
public static void shuffle(List l)
{
if (defaultRandom == null)
{
synchronized (Collections.class)
{
if (defaultRandom == null)
defaultRandom = new Random();
}
}
shuffle(l, defaultRandom);
}
/** Cache a single Random object for use by shuffle(List). This improves
* performance as well as ensuring that sequential calls to shuffle() will
* not result in the same shuffle order occuring: the resolution of
* System.currentTimeMillis() is not sufficient to guarantee a unique seed.
*/
private static Random defaultRandom = null;
/**
* Shuffle a list according to a given source of randomness. The algorithm
* used iterates backwards over the list, swapping each element with an
* element randomly selected from the elements in positions less than or
* equal to it (using r.nextInt(int)).
* <p>
* This algorithm would result in a perfectly fair shuffle (that is, each
* element would have an equal chance of ending up in any position) if r were
* a perfect source of randomness. In practise (eg if r = new Random()) the
* results are merely very close to perfect.
* <p>
* This method operates in linear time on a random-access list, but may take
* quadratic time on a sequential-access list.
* Note: this (classpath) implementation will never take quadratic time, but
* it does make a copy of the list. This is in line with the behaviour of the
* sort methods and seems preferable.
*
* @param l the list to shuffle.
* @param r the source of randomness to use for the shuffle.
* @exception UnsupportedOperationException if l.listIterator() does not
* support the set operation.
*/
public static void shuffle(List l, Random r)
{
Object[] a = l.toArray(); // Dump l into an array
int lsize = l.size();
ListIterator i = l.listIterator(lsize);
// Iterate backwards over l
for (int pos = lsize - 1; pos >= 0; --pos)
{
// Obtain a random position to swap with. pos + 1 is used so that the
// range of the random number includes the current position.
int swap = r.nextInt(pos + 1);
// Swap the swapth element of the array with the next element of the
// list.
Object o = a[swap];
a[swap] = a[pos];
a[pos] = o;
// Set the element in the original list accordingly.
i.previous();
i.set(o);
}
}
/**
* Obtain an immutable Set consisting of a single element. The return value
* of this method is Serializable.
*
* @param o the single element.
* @returns an immutable Set containing only o.
*/
// It's not serializable because the spec is broken.
public static Set singleton(final Object o)
{
return new AbstractSet()
{
public int size()
{
return 1;
}
public Iterator iterator()
{
return new Iterator()
{
private boolean hasNext = true;
public boolean hasNext()
{
return hasNext;
}
public Object next()
{
if (hasNext)
{
hasNext = false;
return o;
}
else
{
throw new NoSuchElementException();
}
}
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
};
}
/**
* Obtain an immutable List consisting of a single element. The return value
* of this method is Serializable.
*
* @param o the single element.
* @returns an immutable List containing only o.
*/
// It's not serializable because the spec is broken.
public static List singletonList(final Object o)
{
return new AbstractList()
{
public int size()
{
return 1;
}
public Object get(int index)
{
if (index == 0)
{
throw new IndexOutOfBoundsException();
}
else
{
return o;
}
}
};
}
/**
* Obtain an immutable Map consisting of a single key value pair.
* The return value of this method is Serializable.
*
* @param key the single key.
* @param value the single value.
* @returns an immutable Map containing only the single key value pair.
*/
// It's not serializable because the spec is broken.
public static Map singletonMap(final Object key, final Object value)
{
return new AbstractMap()
{
public Set entrySet()
{
return singleton(new HashMap.Entry(key, value));
}
};
}
/**
* Sort a list according to the natural ordering of its elements. The list
* must be modifiable, but can be of fixed size. The sort algorithm is
* precisely that used by Arrays.sort(Object[]), which offers guaranteed
* nlog(n) performance. This implementation dumps the list into an array,
* sorts the array, and then iterates over the list setting each element from
* the array.
*
* @param l the List to sort
* @exception ClassCastException if some items are not mutually comparable
* @exception UnsupportedOperationException if the List is not modifiable
*/
public static void sort(List l)
{
Object[] a = l.toArray();
Arrays.sort(a);
ListIterator i = l.listIterator();
for (int pos = 0; pos < a.length; pos++)
{
i.next();
i.set(a[pos]);
}
}
/**
* Sort a list according to a specified Comparator. The list must be
* modifiable, but can be of fixed size. The sort algorithm is precisely that
* used by Arrays.sort(Object[], Comparator), which offers guaranteed
* nlog(n) performance. This implementation dumps the list into an array,
* sorts the array, and then iterates over the list setting each element from
* the array.
*
* @param l the List to sort
* @param c the Comparator specifying the ordering for the elements
* @exception ClassCastException if c will not compare some pair of items
* @exception UnsupportedOperationException if the List is not modifiable
*/
public static void sort(List l, Comparator c)
{
Object[] a = l.toArray();
Arrays.sort(a, c);
ListIterator i = l.listIterator();
for (int pos = 0; pos < a.length; pos++)
{
i.next();
i.set(a[pos]);
}
}
// All the methods from here on in require doc-comments.
public static Collection synchronizedCollection(Collection c)
{
return new SynchronizedCollection(c);
}
public static List synchronizedList(List l)
{
return new SynchronizedList(l);
}
public static Map synchronizedMap(Map m)
{
return new SynchronizedMap(m);
}
public static Set synchronizedSet(Set s)
{
return new SynchronizedSet(s);
}
public static SortedMap synchronizedSortedMap(SortedMap m)
{
return new SynchronizedSortedMap(m);
}
public static SortedSet synchronizedSortedSet(SortedSet s)
{
return new SynchronizedSortedSet(s);
}
public static Collection unmodifiableCollection(Collection c)
{
return new UnmodifiableCollection(c);
}
public static List unmodifiableList(List l)
{
return new UnmodifiableList(l);
}
public static Map unmodifiableMap(Map m)
{
return new UnmodifiableMap(m);
}
public static Set unmodifiableSet(Set s)
{
return new UnmodifiableSet(s);
}
public static SortedMap unmodifiableSortedMap(SortedMap m)
{
return new UnmodifiableSortedMap(m);
}
public static SortedSet unmodifiableSortedSet(SortedSet s)
{
return new UnmodifiableSortedSet(s);
}
// Sun's spec will need to be checked for the precise names of these
// classes, for serializability's sake. However, from what I understand,
// serialization is broken for these classes anyway.
// Note: although this code is largely uncommented, it is all very
// mechanical and there's nothing really worth commenting.
// When serialization of these classes works, we'll need doc-comments on
// them to document the serialized form.
private static class UnmodifiableIterator implements Iterator
{
private Iterator i;
public UnmodifiableIterator(Iterator i)
{
this.i = i;
}
public Object next()
{
return i.next();
}
public boolean hasNext()
{
return i.hasNext();
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
private static class UnmodifiableListIterator extends UnmodifiableIterator
implements ListIterator
{
// This is stored both here and in the superclass, to avoid excessive
// casting.
private ListIterator li;
public UnmodifiableListIterator(ListIterator li)
{
super(li);
this.li = li;
}
public boolean hasPrevious()
{
return li.hasPrevious();
}
public Object previous()
{
return li.previous();
}
public int nextIndex()
{
return li.nextIndex();
}
public int previousIndex()
{
return li.previousIndex();
}
public void add(Object o)
{
throw new UnsupportedOperationException();
}
public void set(Object o)
{
throw new UnsupportedOperationException();
}
}
private static class UnmodifiableCollection implements Collection,
Serializable
{
Collection c;
public UnmodifiableCollection(Collection c)
{
this.c = c;
}
public boolean add(Object o)
{
throw new UnsupportedOperationException();
}
public boolean addAll(Collection c)
{
throw new UnsupportedOperationException();
}
public void clear()
{
throw new UnsupportedOperationException();
}
public boolean contains(Object o)
{
return c.contains(o);
}
public boolean containsAll(Collection c1)
{
return c.containsAll(c1);
}
public boolean isEmpty()
{
return c.isEmpty();
}
public Iterator iterator()
{
return new UnmodifiableIterator(c.iterator());
}
public boolean remove(Object o)
{
throw new UnsupportedOperationException();
}
public boolean removeAll(Collection c)
{
throw new UnsupportedOperationException();
}
public boolean retainAll(Collection c)
{
throw new UnsupportedOperationException();
}
public int size()
{
return c.size();
}
public Object[] toArray()
{
return c.toArray();
}
public Object[] toArray(Object[]a)
{
return c.toArray(a);
}
public String toString()
{
return c.toString();
}
}
private static class UnmodifiableList extends UnmodifiableCollection
implements List
{
// This is stored both here and in the superclass, to avoid excessive
// casting.
List l;
public UnmodifiableList(List l)
{
super(l);
this.l = l;
}
public void add(int index, Object o)
{
throw new UnsupportedOperationException();
}
public boolean addAll(int index, Collection c)
{
throw new UnsupportedOperationException();
}
public boolean equals(Object o)
{
return l.equals(o);
}
public Object get(int index)
{
return l.get(index);
}
public int hashCode()
{
return l.hashCode();
}
public int indexOf(Object o)
{
return l.indexOf(o);
}
public int lastIndexOf(Object o)
{
return l.lastIndexOf(o);
}
public ListIterator listIterator()
{
return new UnmodifiableListIterator(l.listIterator());
}
public ListIterator listIterator(int index)
{
return new UnmodifiableListIterator(l.listIterator(index));
}
public Object remove(int index)
{
throw new UnsupportedOperationException();
}
public Object set(int index, Object o)
{
throw new UnsupportedOperationException();
}
public List subList(int fromIndex, int toIndex)
{
return new UnmodifiableList(l.subList(fromIndex, toIndex));
}
}
private static class UnmodifiableSet extends UnmodifiableCollection
implements Set
{
public UnmodifiableSet(Set s)
{
super(s);
}
public boolean equals(Object o)
{
return c.equals(o);
}
public int hashCode()
{
return c.hashCode();
}
}
private static class UnmodifiableSortedSet extends UnmodifiableSet
implements SortedSet
{
// This is stored both here and in the superclass, to avoid excessive
// casting.
private SortedSet ss;
public UnmodifiableSortedSet(SortedSet ss)
{
super(ss);
this.ss = ss;
}
public Comparator comparator()
{
return ss.comparator();
}
public Object first()
{
return ss.first();
}
public Object last()
{
return ss.last();
}
public SortedSet headSet(Object toElement)
{
return new UnmodifiableSortedSet(ss.headSet(toElement));
}
public SortedSet tailSet(Object fromElement)
{
return new UnmodifiableSortedSet(ss.tailSet(fromElement));
}
public SortedSet subSet(Object fromElement, Object toElement)
{
return new UnmodifiableSortedSet(ss.subSet(fromElement, toElement));
}
}
private static class UnmodifiableMap implements Map, Serializable
{
Map m;
public UnmodifiableMap(Map m)
{
this.m = m;
}
public void clear()
{
throw new UnsupportedOperationException();
}
public boolean containsKey(Object key)
{
return m.containsKey(key);
}
public boolean containsValue(Object value)
{
return m.containsValue(value);
}
// This is one of the ickiest cases of nesting I've ever seen. It just
// means "return an UnmodifiableSet, except that the iterator() method
// returns an UnmodifiableIterator whos next() method returns an
// unmodifiable wrapper around its normal return value".
public Set entrySet()
{
return new UnmodifiableSet(m.entrySet())
{
public Iterator iterator()
{
return new UnmodifiableIterator(c.iterator())
{
public Object next()
{
final Map.Entry e = (Map.Entry) super.next();
return new Map.Entry()
{
public Object getKey()
{
return e.getKey();
}
public Object getValue()
{
return e.getValue();
}
public Object setValue(Object value)
{
throw new UnsupportedOperationException();
}
public int hashCode()
{
return e.hashCode();
}
public boolean equals(Object o)
{
return e.equals(o);
}
};
}
};
}
};
}
public boolean equals(Object o)
{
return m.equals(o);
}
public Object get(Object key)
{
return m.get(key);
}
public Object put(Object key, Object value)
{
throw new UnsupportedOperationException();
}
public int hashCode()
{
return m.hashCode();
}
public boolean isEmpty()
{
return m.isEmpty();
}
public Set keySet()
{
return new UnmodifiableSet(m.keySet());
}
public void putAll(Map m)
{
throw new UnsupportedOperationException();
}
public Object remove(Object o)
{
throw new UnsupportedOperationException();
}
public int size()
{
return m.size();
}
public Collection values()
{
return new UnmodifiableCollection(m.values());
}
public String toString()
{
return m.toString();
}
}
private static class UnmodifiableSortedMap extends UnmodifiableMap
implements SortedMap
{
// This is stored both here and in the superclass, to avoid excessive
// casting.
private SortedMap sm;
public UnmodifiableSortedMap(SortedMap sm)
{
super(sm);
this.sm = sm;
}
public Comparator comparator()
{
return sm.comparator();
}
public Object firstKey()
{
return sm.firstKey();
}
public Object lastKey()
{
return sm.lastKey();
}
public SortedMap headMap(Object toKey)
{
return new UnmodifiableSortedMap(sm.headMap(toKey));
}
public SortedMap tailMap(Object fromKey)
{
return new UnmodifiableSortedMap(sm.tailMap(fromKey));
}
public SortedMap subMap(Object fromKey, Object toKey)
{
return new UnmodifiableSortedMap(sm.subMap(fromKey, toKey));
}
}
// All the "Synchronized" wrapper objects include a "sync" field which
// specifies what object to synchronize on. That way, nested wrappers such as
// UnmodifiableMap.keySet synchronize on the right things.
private static class SynchronizedIterator implements Iterator
{
Object sync;
private Iterator i;
public SynchronizedIterator(Object sync, Iterator i)
{
this.sync = sync;
this.i = i;
}
public Object next()
{
synchronized(sync)
{
return i.next();
}
}
public boolean hasNext()
{
synchronized(sync)
{
return i.hasNext();
}
}
public void remove()
{
synchronized(sync)
{
i.remove();
}
}
}
private static class SynchronizedListIterator extends SynchronizedIterator
implements ListIterator
{
// This is stored both here and in the superclass, to avoid excessive
// casting.
private ListIterator li;
public SynchronizedListIterator(Object sync, ListIterator li)
{
super(sync, li);
this.li = li;
}
public boolean hasPrevious()
{
synchronized(sync)
{
return li.hasPrevious();
}
}
public Object previous()
{
synchronized(sync)
{
return li.previous();
}
}
public int nextIndex()
{
synchronized(sync)
{
return li.nextIndex();
}
}
public int previousIndex()
{
synchronized(sync)
{
return li.previousIndex();
}
}
public void add(Object o)
{
synchronized(sync)
{
li.add(o);
}
}
public void set(Object o)
{
synchronized(sync)
{
li.set(o);
}
}
}
private static class SynchronizedCollection implements Collection,
Serializable
{
Object sync;
Collection c;
public SynchronizedCollection(Collection c)
{
this.sync = this;
this.c = c;
}
public SynchronizedCollection(Object sync, Collection c)
{
this.c = c;
this.sync = sync;
}
public boolean add(Object o)
{
synchronized(sync)
{
return c.add(o);
}
}
public boolean addAll(Collection col)
{
synchronized(sync)
{
return c.addAll(col);
}
}
public void clear()
{
synchronized(sync)
{
c.clear();
}
}
public boolean contains(Object o)
{
synchronized(sync)
{
return c.contains(o);
}
}
public boolean containsAll(Collection c1)
{
synchronized(sync)
{
return c.containsAll(c1);
}
}
public boolean isEmpty()
{
synchronized(sync)
{
return c.isEmpty();
}
}
public Iterator iterator()
{
synchronized(sync)
{
return new SynchronizedIterator(sync, c.iterator());
}
}
public boolean remove(Object o)
{
synchronized(sync)
{
return c.remove(o);
}
}
public boolean removeAll(Collection col)
{
synchronized(sync)
{
return c.removeAll(col);
}
}
public boolean retainAll(Collection col)
{
synchronized(sync)
{
return c.retainAll(col);
}
}
public int size()
{
synchronized(sync)
{
return c.size();
}
}
public Object[] toArray()
{
synchronized(sync)
{
return c.toArray();
}
}
public Object[] toArray(Object[]a)
{
synchronized(sync)
{
return c.toArray(a);
}
}
public String toString()
{
synchronized(sync)
{
return c.toString();
}
}
}
private static class SynchronizedList extends SynchronizedCollection
implements List
{
// This is stored both here and in the superclass, to avoid excessive
// casting.
List l;
public SynchronizedList(Object sync, List l)
{
super(sync, l);
this.l = l;
}
public SynchronizedList(List l)
{
super(l);
this.l = l;
}
public void add(int index, Object o)
{
synchronized(sync)
{
l.add(index, o);
}
}
public boolean addAll(int index, Collection c)
{
synchronized(sync)
{
return l.addAll(index, c);
}
}
public boolean equals(Object o)
{
synchronized(sync)
{
return l.equals(o);
}
}
public Object get(int index)
{
synchronized(sync)
{
return l.get(index);
}
}
public int hashCode()
{
synchronized(sync)
{
return l.hashCode();
}
}
public int indexOf(Object o)
{
synchronized(sync)
{
return l.indexOf(o);
}
}
public int lastIndexOf(Object o)
{
synchronized(sync)
{
return l.lastIndexOf(o);
}
}
public ListIterator listIterator()
{
synchronized(sync)
{
return new SynchronizedListIterator(sync, l.listIterator());
}
}
public ListIterator listIterator(int index)
{
synchronized(sync)
{
return new SynchronizedListIterator(sync, l.listIterator(index));
}
}
public Object remove(int index)
{
synchronized(sync)
{
return l.remove(index);
}
}
public boolean remove(Object o)
{
synchronized(sync)
{
return l.remove(o);
}
}
public Object set(int index, Object o)
{
synchronized(sync)
{
return l.set(index, o);
}
}
public List subList(int fromIndex, int toIndex)
{
synchronized(sync)
{
return new SynchronizedList(l.subList(fromIndex, toIndex));
}
}
}
private static class SynchronizedSet extends SynchronizedCollection
implements Set
{
public SynchronizedSet(Object sync, Set s)
{
super(sync, s);
}
public SynchronizedSet(Set s)
{
super(s);
}
public boolean equals(Object o)
{
synchronized(sync)
{
return c.equals(o);
}
}
public int hashCode()
{
synchronized(sync)
{
return c.hashCode();
}
}
}
private static class SynchronizedSortedSet extends SynchronizedSet
implements SortedSet
{
// This is stored both here and in the superclass, to avoid excessive
// casting.
private SortedSet ss;
public SynchronizedSortedSet(Object sync, SortedSet ss)
{
super(sync, ss);
this.ss = ss;
}
public SynchronizedSortedSet(SortedSet ss)
{
super(ss);
this.ss = ss;
}
public Comparator comparator()
{
synchronized(sync)
{
return ss.comparator();
}
}
public Object first()
{
synchronized(sync)
{
return ss.first();
}
}
public Object last()
{
synchronized(sync)
{
return ss.last();
}
}
public SortedSet headSet(Object toElement)
{
synchronized(sync)
{
return new SynchronizedSortedSet(sync, ss.headSet(toElement));
}
}
public SortedSet tailSet(Object fromElement)
{
synchronized(sync)
{
return new SynchronizedSortedSet(sync, ss.tailSet(fromElement));
}
}
public SortedSet subSet(Object fromElement, Object toElement)
{
synchronized(sync)
{
return new SynchronizedSortedSet(sync,
ss.subSet(fromElement, toElement));
}
}
}
private static class SynchronizedMap implements Map, Serializable
{
Object sync;
Map m;
public SynchronizedMap(Object sync, Map m)
{
this.sync = sync;
this.m = m;
}
public SynchronizedMap(Map m)
{
this.m = m;
this.sync = this;
}
public void clear()
{
synchronized(sync)
{
m.clear();
}
}
public boolean containsKey(Object key)
{
synchronized(sync)
{
return m.containsKey(key);
}
}
public boolean containsValue(Object value)
{
synchronized(sync)
{
return m.containsValue(value);
}
}
// This is one of the ickiest cases of nesting I've ever seen. It just
// means "return a SynchronizedSet, except that the iterator() method
// returns an SynchronizedIterator whos next() method returns a
// synchronized wrapper around its normal return value".
public Set entrySet()
{
synchronized(sync)
{
return new SynchronizedSet(sync, m.entrySet())
{
public Iterator iterator()
{
synchronized(SynchronizedMap.this.sync)
{
return new SynchronizedIterator(SynchronizedMap.this.sync,
c.iterator())
{
public Object next()
{
synchronized(SynchronizedMap.this.sync)
{
final Map.Entry e = (Map.Entry) super.next();
return new Map.Entry()
{
public Object getKey()
{
synchronized(SynchronizedMap.this.sync)
{
return e.getKey();
}
}
public Object getValue()
{
synchronized(SynchronizedMap.this.sync)
{
return e.getValue();
}
}
public Object setValue(Object value)
{
synchronized(SynchronizedMap.this.sync)
{
return e.setValue(value);
}
}
public int hashCode()
{
synchronized(SynchronizedMap.this.sync)
{
return e.hashCode();
}
}
public boolean equals(Object o)
{
synchronized(SynchronizedMap.this.sync)
{
return e.equals(o);
}
}
};
}
}
};
}
}
};
}
}
public boolean equals(Object o)
{
synchronized(sync)
{
return m.equals(o);
}
}
public Object get(Object key)
{
synchronized(sync)
{
return m.get(key);
}
}
public Object put(Object key, Object value)
{
synchronized(sync)
{
return m.put(key, value);
}
}
public int hashCode()
{
synchronized(sync)
{
return m.hashCode();
}
}
public boolean isEmpty()
{
synchronized(sync)
{
return m.isEmpty();
}
}
public Set keySet()
{
synchronized(sync)
{
return new SynchronizedSet(sync, m.keySet());
}
}
public void putAll(Map map)
{
synchronized(sync)
{
m.putAll(map);
}
}
public Object remove(Object o)
{
synchronized(sync)
{
return m.remove(o);
}
}
public int size()
{
synchronized(sync)
{
return m.size();
}
}
public Collection values()
{
synchronized(sync)
{
return new SynchronizedCollection(sync, m.values());
}
}
public String toString()
{
synchronized(sync)
{
return m.toString();
}
}
}
private static class SynchronizedSortedMap extends SynchronizedMap
implements SortedMap
{
// This is stored both here and in the superclass, to avoid excessive
// casting.
private SortedMap sm;
public SynchronizedSortedMap(Object sync, SortedMap sm)
{
super(sync, sm);
this.sm = sm;
}
public SynchronizedSortedMap(SortedMap sm)
{
super(sm);
this.sm = sm;
}
public Comparator comparator()
{
synchronized(sync)
{
return sm.comparator();
}
}
public Object firstKey()
{
synchronized(sync)
{
return sm.firstKey();
}
}
public Object lastKey()
{
synchronized(sync)
{
return sm.lastKey();
}
}
public SortedMap headMap(Object toKey)
{
return new SynchronizedSortedMap(sync, sm.headMap(toKey));
}
public SortedMap tailMap(Object fromKey)
{
return new SynchronizedSortedMap(sync, sm.tailMap(fromKey));
}
public SortedMap subMap(Object fromKey, Object toKey)
{
return new SynchronizedSortedMap(sync, sm.subMap(fromKey, toKey));
}
}
}
|