Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/java/util/Collections.java
41152 views
1
/*
2
* Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package java.util;
27
28
import java.io.IOException;
29
import java.io.ObjectInputStream;
30
import java.io.ObjectOutputStream;
31
import java.io.Serializable;
32
import java.lang.reflect.Array;
33
import java.util.function.BiConsumer;
34
import java.util.function.BiFunction;
35
import java.util.function.Consumer;
36
import java.util.function.Function;
37
import java.util.function.IntFunction;
38
import java.util.function.Predicate;
39
import java.util.function.UnaryOperator;
40
import java.util.stream.IntStream;
41
import java.util.stream.Stream;
42
import java.util.stream.StreamSupport;
43
import jdk.internal.access.SharedSecrets;
44
45
/**
46
* This class consists exclusively of static methods that operate on or return
47
* collections. It contains polymorphic algorithms that operate on
48
* collections, "wrappers", which return a new collection backed by a
49
* specified collection, and a few other odds and ends.
50
*
51
* <p>The methods of this class all throw a {@code NullPointerException}
52
* if the collections or class objects provided to them are null.
53
*
54
* <p>The documentation for the polymorphic algorithms contained in this class
55
* generally includes a brief description of the <i>implementation</i>. Such
56
* descriptions should be regarded as <i>implementation notes</i>, rather than
57
* parts of the <i>specification</i>. Implementors should feel free to
58
* substitute other algorithms, so long as the specification itself is adhered
59
* to. (For example, the algorithm used by {@code sort} does not have to be
60
* a mergesort, but it does have to be <i>stable</i>.)
61
*
62
* <p>The "destructive" algorithms contained in this class, that is, the
63
* algorithms that modify the collection on which they operate, are specified
64
* to throw {@code UnsupportedOperationException} if the collection does not
65
* support the appropriate mutation primitive(s), such as the {@code set}
66
* method. These algorithms may, but are not required to, throw this
67
* exception if an invocation would have no effect on the collection. For
68
* example, invoking the {@code sort} method on an unmodifiable list that is
69
* already sorted may or may not throw {@code UnsupportedOperationException}.
70
*
71
* <p>This class is a member of the
72
* <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
73
* Java Collections Framework</a>.
74
*
75
* @author Josh Bloch
76
* @author Neal Gafter
77
* @see Collection
78
* @see Set
79
* @see List
80
* @see Map
81
* @since 1.2
82
*/
83
84
public class Collections {
85
// Suppresses default constructor, ensuring non-instantiability.
86
private Collections() {
87
}
88
89
// Algorithms
90
91
/*
92
* Tuning parameters for algorithms - Many of the List algorithms have
93
* two implementations, one of which is appropriate for RandomAccess
94
* lists, the other for "sequential." Often, the random access variant
95
* yields better performance on small sequential access lists. The
96
* tuning parameters below determine the cutoff point for what constitutes
97
* a "small" sequential access list for each algorithm. The values below
98
* were empirically determined to work well for LinkedList. Hopefully
99
* they should be reasonable for other sequential access List
100
* implementations. Those doing performance work on this code would
101
* do well to validate the values of these parameters from time to time.
102
* (The first word of each tuning parameter name is the algorithm to which
103
* it applies.)
104
*/
105
private static final int BINARYSEARCH_THRESHOLD = 5000;
106
private static final int REVERSE_THRESHOLD = 18;
107
private static final int SHUFFLE_THRESHOLD = 5;
108
private static final int FILL_THRESHOLD = 25;
109
private static final int ROTATE_THRESHOLD = 100;
110
private static final int COPY_THRESHOLD = 10;
111
private static final int REPLACEALL_THRESHOLD = 11;
112
private static final int INDEXOFSUBLIST_THRESHOLD = 35;
113
114
/**
115
* Sorts the specified list into ascending order, according to the
116
* {@linkplain Comparable natural ordering} of its elements.
117
* All elements in the list must implement the {@link Comparable}
118
* interface. Furthermore, all elements in the list must be
119
* <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)}
120
* must not throw a {@code ClassCastException} for any elements
121
* {@code e1} and {@code e2} in the list).
122
*
123
* <p>This sort is guaranteed to be <i>stable</i>: equal elements will
124
* not be reordered as a result of the sort.
125
*
126
* <p>The specified list must be modifiable, but need not be resizable.
127
*
128
* @implNote
129
* This implementation defers to the {@link List#sort(Comparator)}
130
* method using the specified list and a {@code null} comparator.
131
*
132
* @param <T> the class of the objects in the list
133
* @param list the list to be sorted.
134
* @throws ClassCastException if the list contains elements that are not
135
* <i>mutually comparable</i> (for example, strings and integers).
136
* @throws UnsupportedOperationException if the specified list's
137
* list-iterator does not support the {@code set} operation.
138
* @throws IllegalArgumentException (optional) if the implementation
139
* detects that the natural ordering of the list elements is
140
* found to violate the {@link Comparable} contract
141
* @see List#sort(Comparator)
142
*/
143
@SuppressWarnings("unchecked")
144
public static <T extends Comparable<? super T>> void sort(List<T> list) {
145
list.sort(null);
146
}
147
148
/**
149
* Sorts the specified list according to the order induced by the
150
* specified comparator. All elements in the list must be <i>mutually
151
* comparable</i> using the specified comparator (that is,
152
* {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
153
* for any elements {@code e1} and {@code e2} in the list).
154
*
155
* <p>This sort is guaranteed to be <i>stable</i>: equal elements will
156
* not be reordered as a result of the sort.
157
*
158
* <p>The specified list must be modifiable, but need not be resizable.
159
*
160
* @implNote
161
* This implementation defers to the {@link List#sort(Comparator)}
162
* method using the specified list and comparator.
163
*
164
* @param <T> the class of the objects in the list
165
* @param list the list to be sorted.
166
* @param c the comparator to determine the order of the list. A
167
* {@code null} value indicates that the elements' <i>natural
168
* ordering</i> should be used.
169
* @throws ClassCastException if the list contains elements that are not
170
* <i>mutually comparable</i> using the specified comparator.
171
* @throws UnsupportedOperationException if the specified list's
172
* list-iterator does not support the {@code set} operation.
173
* @throws IllegalArgumentException (optional) if the comparator is
174
* found to violate the {@link Comparator} contract
175
* @see List#sort(Comparator)
176
*/
177
@SuppressWarnings({"unchecked", "rawtypes"})
178
public static <T> void sort(List<T> list, Comparator<? super T> c) {
179
list.sort(c);
180
}
181
182
183
/**
184
* Searches the specified list for the specified object using the binary
185
* search algorithm. The list must be sorted into ascending order
186
* according to the {@linkplain Comparable natural ordering} of its
187
* elements (as by the {@link #sort(List)} method) prior to making this
188
* call. If it is not sorted, the results are undefined. If the list
189
* contains multiple elements equal to the specified object, there is no
190
* guarantee which one will be found.
191
*
192
* <p>This method runs in log(n) time for a "random access" list (which
193
* provides near-constant-time positional access). If the specified list
194
* does not implement the {@link RandomAccess} interface and is large,
195
* this method will do an iterator-based binary search that performs
196
* O(n) link traversals and O(log n) element comparisons.
197
*
198
* @param <T> the class of the objects in the list
199
* @param list the list to be searched.
200
* @param key the key to be searched for.
201
* @return the index of the search key, if it is contained in the list;
202
* otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The
203
* <i>insertion point</i> is defined as the point at which the
204
* key would be inserted into the list: the index of the first
205
* element greater than the key, or {@code list.size()} if all
206
* elements in the list are less than the specified key. Note
207
* that this guarantees that the return value will be &gt;= 0 if
208
* and only if the key is found.
209
* @throws ClassCastException if the list contains elements that are not
210
* <i>mutually comparable</i> (for example, strings and
211
* integers), or the search key is not mutually comparable
212
* with the elements of the list.
213
*/
214
public static <T>
215
int binarySearch(List<? extends Comparable<? super T>> list, T key) {
216
if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
217
return Collections.indexedBinarySearch(list, key);
218
else
219
return Collections.iteratorBinarySearch(list, key);
220
}
221
222
private static <T>
223
int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key) {
224
int low = 0;
225
int high = list.size()-1;
226
227
while (low <= high) {
228
int mid = (low + high) >>> 1;
229
Comparable<? super T> midVal = list.get(mid);
230
int cmp = midVal.compareTo(key);
231
232
if (cmp < 0)
233
low = mid + 1;
234
else if (cmp > 0)
235
high = mid - 1;
236
else
237
return mid; // key found
238
}
239
return -(low + 1); // key not found
240
}
241
242
private static <T>
243
int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key)
244
{
245
int low = 0;
246
int high = list.size()-1;
247
ListIterator<? extends Comparable<? super T>> i = list.listIterator();
248
249
while (low <= high) {
250
int mid = (low + high) >>> 1;
251
Comparable<? super T> midVal = get(i, mid);
252
int cmp = midVal.compareTo(key);
253
254
if (cmp < 0)
255
low = mid + 1;
256
else if (cmp > 0)
257
high = mid - 1;
258
else
259
return mid; // key found
260
}
261
return -(low + 1); // key not found
262
}
263
264
/**
265
* Gets the ith element from the given list by repositioning the specified
266
* list listIterator.
267
*/
268
private static <T> T get(ListIterator<? extends T> i, int index) {
269
T obj = null;
270
int pos = i.nextIndex();
271
if (pos <= index) {
272
do {
273
obj = i.next();
274
} while (pos++ < index);
275
} else {
276
do {
277
obj = i.previous();
278
} while (--pos > index);
279
}
280
return obj;
281
}
282
283
/**
284
* Searches the specified list for the specified object using the binary
285
* search algorithm. The list must be sorted into ascending order
286
* according to the specified comparator (as by the
287
* {@link #sort(List, Comparator) sort(List, Comparator)}
288
* method), prior to making this call. If it is
289
* not sorted, the results are undefined. If the list contains multiple
290
* elements equal to the specified object, there is no guarantee which one
291
* will be found.
292
*
293
* <p>This method runs in log(n) time for a "random access" list (which
294
* provides near-constant-time positional access). If the specified list
295
* does not implement the {@link RandomAccess} interface and is large,
296
* this method will do an iterator-based binary search that performs
297
* O(n) link traversals and O(log n) element comparisons.
298
*
299
* @param <T> the class of the objects in the list
300
* @param list the list to be searched.
301
* @param key the key to be searched for.
302
* @param c the comparator by which the list is ordered.
303
* A {@code null} value indicates that the elements'
304
* {@linkplain Comparable natural ordering} should be used.
305
* @return the index of the search key, if it is contained in the list;
306
* otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The
307
* <i>insertion point</i> is defined as the point at which the
308
* key would be inserted into the list: the index of the first
309
* element greater than the key, or {@code list.size()} if all
310
* elements in the list are less than the specified key. Note
311
* that this guarantees that the return value will be &gt;= 0 if
312
* and only if the key is found.
313
* @throws ClassCastException if the list contains elements that are not
314
* <i>mutually comparable</i> using the specified comparator,
315
* or the search key is not mutually comparable with the
316
* elements of the list using this comparator.
317
*/
318
@SuppressWarnings("unchecked")
319
public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) {
320
if (c==null)
321
return binarySearch((List<? extends Comparable<? super T>>) list, key);
322
323
if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
324
return Collections.indexedBinarySearch(list, key, c);
325
else
326
return Collections.iteratorBinarySearch(list, key, c);
327
}
328
329
private static <T> int indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {
330
int low = 0;
331
int high = l.size()-1;
332
333
while (low <= high) {
334
int mid = (low + high) >>> 1;
335
T midVal = l.get(mid);
336
int cmp = c.compare(midVal, key);
337
338
if (cmp < 0)
339
low = mid + 1;
340
else if (cmp > 0)
341
high = mid - 1;
342
else
343
return mid; // key found
344
}
345
return -(low + 1); // key not found
346
}
347
348
private static <T> int iteratorBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {
349
int low = 0;
350
int high = l.size()-1;
351
ListIterator<? extends T> i = l.listIterator();
352
353
while (low <= high) {
354
int mid = (low + high) >>> 1;
355
T midVal = get(i, mid);
356
int cmp = c.compare(midVal, key);
357
358
if (cmp < 0)
359
low = mid + 1;
360
else if (cmp > 0)
361
high = mid - 1;
362
else
363
return mid; // key found
364
}
365
return -(low + 1); // key not found
366
}
367
368
/**
369
* Reverses the order of the elements in the specified list.<p>
370
*
371
* This method runs in linear time.
372
*
373
* @param list the list whose elements are to be reversed.
374
* @throws UnsupportedOperationException if the specified list or
375
* its list-iterator does not support the {@code set} operation.
376
*/
377
@SuppressWarnings({"rawtypes", "unchecked"})
378
public static void reverse(List<?> list) {
379
int size = list.size();
380
if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
381
for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
382
swap(list, i, j);
383
} else {
384
// instead of using a raw type here, it's possible to capture
385
// the wildcard but it will require a call to a supplementary
386
// private method
387
ListIterator fwd = list.listIterator();
388
ListIterator rev = list.listIterator(size);
389
for (int i=0, mid=list.size()>>1; i<mid; i++) {
390
Object tmp = fwd.next();
391
fwd.set(rev.previous());
392
rev.set(tmp);
393
}
394
}
395
}
396
397
/**
398
* Randomly permutes the specified list using a default source of
399
* randomness. All permutations occur with approximately equal
400
* likelihood.
401
*
402
* <p>The hedge "approximately" is used in the foregoing description because
403
* default source of randomness is only approximately an unbiased source
404
* of independently chosen bits. If it were a perfect source of randomly
405
* chosen bits, then the algorithm would choose permutations with perfect
406
* uniformity.
407
*
408
* <p>This implementation traverses the list backwards, from the last
409
* element up to the second, repeatedly swapping a randomly selected element
410
* into the "current position". Elements are randomly selected from the
411
* portion of the list that runs from the first element to the current
412
* position, inclusive.
413
*
414
* <p>This method runs in linear time. If the specified list does not
415
* implement the {@link RandomAccess} interface and is large, this
416
* implementation dumps the specified list into an array before shuffling
417
* it, and dumps the shuffled array back into the list. This avoids the
418
* quadratic behavior that would result from shuffling a "sequential
419
* access" list in place.
420
*
421
* @param list the list to be shuffled.
422
* @throws UnsupportedOperationException if the specified list or
423
* its list-iterator does not support the {@code set} operation.
424
*/
425
public static void shuffle(List<?> list) {
426
Random rnd = r;
427
if (rnd == null)
428
r = rnd = new Random(); // harmless race.
429
shuffle(list, rnd);
430
}
431
432
private static Random r;
433
434
/**
435
* Randomly permute the specified list using the specified source of
436
* randomness. All permutations occur with equal likelihood
437
* assuming that the source of randomness is fair.<p>
438
*
439
* This implementation traverses the list backwards, from the last element
440
* up to the second, repeatedly swapping a randomly selected element into
441
* the "current position". Elements are randomly selected from the
442
* portion of the list that runs from the first element to the current
443
* position, inclusive.<p>
444
*
445
* This method runs in linear time. If the specified list does not
446
* implement the {@link RandomAccess} interface and is large, this
447
* implementation dumps the specified list into an array before shuffling
448
* it, and dumps the shuffled array back into the list. This avoids the
449
* quadratic behavior that would result from shuffling a "sequential
450
* access" list in place.
451
*
452
* @param list the list to be shuffled.
453
* @param rnd the source of randomness to use to shuffle the list.
454
* @throws UnsupportedOperationException if the specified list or its
455
* list-iterator does not support the {@code set} operation.
456
*/
457
@SuppressWarnings({"rawtypes", "unchecked"})
458
public static void shuffle(List<?> list, Random rnd) {
459
int size = list.size();
460
if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
461
for (int i=size; i>1; i--)
462
swap(list, i-1, rnd.nextInt(i));
463
} else {
464
Object[] arr = list.toArray();
465
466
// Shuffle array
467
for (int i=size; i>1; i--)
468
swap(arr, i-1, rnd.nextInt(i));
469
470
// Dump array back into list
471
// instead of using a raw type here, it's possible to capture
472
// the wildcard but it will require a call to a supplementary
473
// private method
474
ListIterator it = list.listIterator();
475
for (Object e : arr) {
476
it.next();
477
it.set(e);
478
}
479
}
480
}
481
482
/**
483
* Swaps the elements at the specified positions in the specified list.
484
* (If the specified positions are equal, invoking this method leaves
485
* the list unchanged.)
486
*
487
* @param list The list in which to swap elements.
488
* @param i the index of one element to be swapped.
489
* @param j the index of the other element to be swapped.
490
* @throws IndexOutOfBoundsException if either {@code i} or {@code j}
491
* is out of range (i &lt; 0 || i &gt;= list.size()
492
* || j &lt; 0 || j &gt;= list.size()).
493
* @since 1.4
494
*/
495
@SuppressWarnings({"rawtypes", "unchecked"})
496
public static void swap(List<?> list, int i, int j) {
497
// instead of using a raw type here, it's possible to capture
498
// the wildcard but it will require a call to a supplementary
499
// private method
500
final List l = list;
501
l.set(i, l.set(j, l.get(i)));
502
}
503
504
/**
505
* Swaps the two specified elements in the specified array.
506
*/
507
private static void swap(Object[] arr, int i, int j) {
508
Object tmp = arr[i];
509
arr[i] = arr[j];
510
arr[j] = tmp;
511
}
512
513
/**
514
* Replaces all of the elements of the specified list with the specified
515
* element. <p>
516
*
517
* This method runs in linear time.
518
*
519
* @param <T> the class of the objects in the list
520
* @param list the list to be filled with the specified element.
521
* @param obj The element with which to fill the specified list.
522
* @throws UnsupportedOperationException if the specified list or its
523
* list-iterator does not support the {@code set} operation.
524
*/
525
public static <T> void fill(List<? super T> list, T obj) {
526
int size = list.size();
527
528
if (size < FILL_THRESHOLD || list instanceof RandomAccess) {
529
for (int i=0; i<size; i++)
530
list.set(i, obj);
531
} else {
532
ListIterator<? super T> itr = list.listIterator();
533
for (int i=0; i<size; i++) {
534
itr.next();
535
itr.set(obj);
536
}
537
}
538
}
539
540
/**
541
* Copies all of the elements from one list into another. After the
542
* operation, the index of each copied element in the destination list
543
* will be identical to its index in the source list. The destination
544
* list's size must be greater than or equal to the source list's size.
545
* If it is greater, the remaining elements in the destination list are
546
* unaffected. <p>
547
*
548
* This method runs in linear time.
549
*
550
* @param <T> the class of the objects in the lists
551
* @param dest The destination list.
552
* @param src The source list.
553
* @throws IndexOutOfBoundsException if the destination list is too small
554
* to contain the entire source List.
555
* @throws UnsupportedOperationException if the destination list's
556
* list-iterator does not support the {@code set} operation.
557
*/
558
public static <T> void copy(List<? super T> dest, List<? extends T> src) {
559
int srcSize = src.size();
560
if (srcSize > dest.size())
561
throw new IndexOutOfBoundsException("Source does not fit in dest");
562
563
if (srcSize < COPY_THRESHOLD ||
564
(src instanceof RandomAccess && dest instanceof RandomAccess)) {
565
for (int i=0; i<srcSize; i++)
566
dest.set(i, src.get(i));
567
} else {
568
ListIterator<? super T> di=dest.listIterator();
569
ListIterator<? extends T> si=src.listIterator();
570
for (int i=0; i<srcSize; i++) {
571
di.next();
572
di.set(si.next());
573
}
574
}
575
}
576
577
/**
578
* Returns the minimum element of the given collection, according to the
579
* <i>natural ordering</i> of its elements. All elements in the
580
* collection must implement the {@code Comparable} interface.
581
* Furthermore, all elements in the collection must be <i>mutually
582
* comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a
583
* {@code ClassCastException} for any elements {@code e1} and
584
* {@code e2} in the collection).<p>
585
*
586
* This method iterates over the entire collection, hence it requires
587
* time proportional to the size of the collection.
588
*
589
* @param <T> the class of the objects in the collection
590
* @param coll the collection whose minimum element is to be determined.
591
* @return the minimum element of the given collection, according
592
* to the <i>natural ordering</i> of its elements.
593
* @throws ClassCastException if the collection contains elements that are
594
* not <i>mutually comparable</i> (for example, strings and
595
* integers).
596
* @throws NoSuchElementException if the collection is empty.
597
* @see Comparable
598
*/
599
public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
600
Iterator<? extends T> i = coll.iterator();
601
T candidate = i.next();
602
603
while (i.hasNext()) {
604
T next = i.next();
605
if (next.compareTo(candidate) < 0)
606
candidate = next;
607
}
608
return candidate;
609
}
610
611
/**
612
* Returns the minimum element of the given collection, according to the
613
* order induced by the specified comparator. All elements in the
614
* collection must be <i>mutually comparable</i> by the specified
615
* comparator (that is, {@code comp.compare(e1, e2)} must not throw a
616
* {@code ClassCastException} for any elements {@code e1} and
617
* {@code e2} in the collection).<p>
618
*
619
* This method iterates over the entire collection, hence it requires
620
* time proportional to the size of the collection.
621
*
622
* @param <T> the class of the objects in the collection
623
* @param coll the collection whose minimum element is to be determined.
624
* @param comp the comparator with which to determine the minimum element.
625
* A {@code null} value indicates that the elements' <i>natural
626
* ordering</i> should be used.
627
* @return the minimum element of the given collection, according
628
* to the specified comparator.
629
* @throws ClassCastException if the collection contains elements that are
630
* not <i>mutually comparable</i> using the specified comparator.
631
* @throws NoSuchElementException if the collection is empty.
632
* @see Comparable
633
*/
634
@SuppressWarnings({"unchecked", "rawtypes"})
635
public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {
636
if (comp==null)
637
return (T)min((Collection) coll);
638
639
Iterator<? extends T> i = coll.iterator();
640
T candidate = i.next();
641
642
while (i.hasNext()) {
643
T next = i.next();
644
if (comp.compare(next, candidate) < 0)
645
candidate = next;
646
}
647
return candidate;
648
}
649
650
/**
651
* Returns the maximum element of the given collection, according to the
652
* <i>natural ordering</i> of its elements. All elements in the
653
* collection must implement the {@code Comparable} interface.
654
* Furthermore, all elements in the collection must be <i>mutually
655
* comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a
656
* {@code ClassCastException} for any elements {@code e1} and
657
* {@code e2} in the collection).<p>
658
*
659
* This method iterates over the entire collection, hence it requires
660
* time proportional to the size of the collection.
661
*
662
* @param <T> the class of the objects in the collection
663
* @param coll the collection whose maximum element is to be determined.
664
* @return the maximum element of the given collection, according
665
* to the <i>natural ordering</i> of its elements.
666
* @throws ClassCastException if the collection contains elements that are
667
* not <i>mutually comparable</i> (for example, strings and
668
* integers).
669
* @throws NoSuchElementException if the collection is empty.
670
* @see Comparable
671
*/
672
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
673
Iterator<? extends T> i = coll.iterator();
674
T candidate = i.next();
675
676
while (i.hasNext()) {
677
T next = i.next();
678
if (next.compareTo(candidate) > 0)
679
candidate = next;
680
}
681
return candidate;
682
}
683
684
/**
685
* Returns the maximum element of the given collection, according to the
686
* order induced by the specified comparator. All elements in the
687
* collection must be <i>mutually comparable</i> by the specified
688
* comparator (that is, {@code comp.compare(e1, e2)} must not throw a
689
* {@code ClassCastException} for any elements {@code e1} and
690
* {@code e2} in the collection).<p>
691
*
692
* This method iterates over the entire collection, hence it requires
693
* time proportional to the size of the collection.
694
*
695
* @param <T> the class of the objects in the collection
696
* @param coll the collection whose maximum element is to be determined.
697
* @param comp the comparator with which to determine the maximum element.
698
* A {@code null} value indicates that the elements' <i>natural
699
* ordering</i> should be used.
700
* @return the maximum element of the given collection, according
701
* to the specified comparator.
702
* @throws ClassCastException if the collection contains elements that are
703
* not <i>mutually comparable</i> using the specified comparator.
704
* @throws NoSuchElementException if the collection is empty.
705
* @see Comparable
706
*/
707
@SuppressWarnings({"unchecked", "rawtypes"})
708
public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {
709
if (comp==null)
710
return (T)max((Collection) coll);
711
712
Iterator<? extends T> i = coll.iterator();
713
T candidate = i.next();
714
715
while (i.hasNext()) {
716
T next = i.next();
717
if (comp.compare(next, candidate) > 0)
718
candidate = next;
719
}
720
return candidate;
721
}
722
723
/**
724
* Rotates the elements in the specified list by the specified distance.
725
* After calling this method, the element at index {@code i} will be
726
* the element previously at index {@code (i - distance)} mod
727
* {@code list.size()}, for all values of {@code i} between {@code 0}
728
* and {@code list.size()-1}, inclusive. (This method has no effect on
729
* the size of the list.)
730
*
731
* <p>For example, suppose {@code list} comprises{@code [t, a, n, k, s]}.
732
* After invoking {@code Collections.rotate(list, 1)} (or
733
* {@code Collections.rotate(list, -4)}), {@code list} will comprise
734
* {@code [s, t, a, n, k]}.
735
*
736
* <p>Note that this method can usefully be applied to sublists to
737
* move one or more elements within a list while preserving the
738
* order of the remaining elements. For example, the following idiom
739
* moves the element at index {@code j} forward to position
740
* {@code k} (which must be greater than or equal to {@code j}):
741
* <pre>
742
* Collections.rotate(list.subList(j, k+1), -1);
743
* </pre>
744
* To make this concrete, suppose {@code list} comprises
745
* {@code [a, b, c, d, e]}. To move the element at index {@code 1}
746
* ({@code b}) forward two positions, perform the following invocation:
747
* <pre>
748
* Collections.rotate(l.subList(1, 4), -1);
749
* </pre>
750
* The resulting list is {@code [a, c, d, b, e]}.
751
*
752
* <p>To move more than one element forward, increase the absolute value
753
* of the rotation distance. To move elements backward, use a positive
754
* shift distance.
755
*
756
* <p>If the specified list is small or implements the {@link
757
* RandomAccess} interface, this implementation exchanges the first
758
* element into the location it should go, and then repeatedly exchanges
759
* the displaced element into the location it should go until a displaced
760
* element is swapped into the first element. If necessary, the process
761
* is repeated on the second and successive elements, until the rotation
762
* is complete. If the specified list is large and doesn't implement the
763
* {@code RandomAccess} interface, this implementation breaks the
764
* list into two sublist views around index {@code -distance mod size}.
765
* Then the {@link #reverse(List)} method is invoked on each sublist view,
766
* and finally it is invoked on the entire list. For a more complete
767
* description of both algorithms, see Section 2.3 of Jon Bentley's
768
* <i>Programming Pearls</i> (Addison-Wesley, 1986).
769
*
770
* @param list the list to be rotated.
771
* @param distance the distance to rotate the list. There are no
772
* constraints on this value; it may be zero, negative, or
773
* greater than {@code list.size()}.
774
* @throws UnsupportedOperationException if the specified list or
775
* its list-iterator does not support the {@code set} operation.
776
* @since 1.4
777
*/
778
public static void rotate(List<?> list, int distance) {
779
if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD)
780
rotate1(list, distance);
781
else
782
rotate2(list, distance);
783
}
784
785
private static <T> void rotate1(List<T> list, int distance) {
786
int size = list.size();
787
if (size == 0)
788
return;
789
distance = distance % size;
790
if (distance < 0)
791
distance += size;
792
if (distance == 0)
793
return;
794
795
for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) {
796
T displaced = list.get(cycleStart);
797
int i = cycleStart;
798
do {
799
i += distance;
800
if (i >= size)
801
i -= size;
802
displaced = list.set(i, displaced);
803
nMoved ++;
804
} while (i != cycleStart);
805
}
806
}
807
808
private static void rotate2(List<?> list, int distance) {
809
int size = list.size();
810
if (size == 0)
811
return;
812
int mid = -distance % size;
813
if (mid < 0)
814
mid += size;
815
if (mid == 0)
816
return;
817
818
reverse(list.subList(0, mid));
819
reverse(list.subList(mid, size));
820
reverse(list);
821
}
822
823
/**
824
* Replaces all occurrences of one specified value in a list with another.
825
* More formally, replaces with {@code newVal} each element {@code e}
826
* in {@code list} such that
827
* {@code (oldVal==null ? e==null : oldVal.equals(e))}.
828
* (This method has no effect on the size of the list.)
829
*
830
* @param <T> the class of the objects in the list
831
* @param list the list in which replacement is to occur.
832
* @param oldVal the old value to be replaced.
833
* @param newVal the new value with which {@code oldVal} is to be
834
* replaced.
835
* @return {@code true} if {@code list} contained one or more elements
836
* {@code e} such that
837
* {@code (oldVal==null ? e==null : oldVal.equals(e))}.
838
* @throws UnsupportedOperationException if the specified list or
839
* its list-iterator does not support the {@code set} operation.
840
* @since 1.4
841
*/
842
public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) {
843
boolean result = false;
844
int size = list.size();
845
if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) {
846
if (oldVal==null) {
847
for (int i=0; i<size; i++) {
848
if (list.get(i)==null) {
849
list.set(i, newVal);
850
result = true;
851
}
852
}
853
} else {
854
for (int i=0; i<size; i++) {
855
if (oldVal.equals(list.get(i))) {
856
list.set(i, newVal);
857
result = true;
858
}
859
}
860
}
861
} else {
862
ListIterator<T> itr=list.listIterator();
863
if (oldVal==null) {
864
for (int i=0; i<size; i++) {
865
if (itr.next()==null) {
866
itr.set(newVal);
867
result = true;
868
}
869
}
870
} else {
871
for (int i=0; i<size; i++) {
872
if (oldVal.equals(itr.next())) {
873
itr.set(newVal);
874
result = true;
875
}
876
}
877
}
878
}
879
return result;
880
}
881
882
/**
883
* Returns the starting position of the first occurrence of the specified
884
* target list within the specified source list, or -1 if there is no
885
* such occurrence. More formally, returns the lowest index {@code i}
886
* such that {@code source.subList(i, i+target.size()).equals(target)},
887
* or -1 if there is no such index. (Returns -1 if
888
* {@code target.size() > source.size()})
889
*
890
* <p>This implementation uses the "brute force" technique of scanning
891
* over the source list, looking for a match with the target at each
892
* location in turn.
893
*
894
* @param source the list in which to search for the first occurrence
895
* of {@code target}.
896
* @param target the list to search for as a subList of {@code source}.
897
* @return the starting position of the first occurrence of the specified
898
* target list within the specified source list, or -1 if there
899
* is no such occurrence.
900
* @since 1.4
901
*/
902
public static int indexOfSubList(List<?> source, List<?> target) {
903
int sourceSize = source.size();
904
int targetSize = target.size();
905
int maxCandidate = sourceSize - targetSize;
906
907
if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
908
(source instanceof RandomAccess&&target instanceof RandomAccess)) {
909
nextCand:
910
for (int candidate = 0; candidate <= maxCandidate; candidate++) {
911
for (int i=0, j=candidate; i<targetSize; i++, j++)
912
if (!eq(target.get(i), source.get(j)))
913
continue nextCand; // Element mismatch, try next cand
914
return candidate; // All elements of candidate matched target
915
}
916
} else { // Iterator version of above algorithm
917
ListIterator<?> si = source.listIterator();
918
nextCand:
919
for (int candidate = 0; candidate <= maxCandidate; candidate++) {
920
ListIterator<?> ti = target.listIterator();
921
for (int i=0; i<targetSize; i++) {
922
if (!eq(ti.next(), si.next())) {
923
// Back up source iterator to next candidate
924
for (int j=0; j<i; j++)
925
si.previous();
926
continue nextCand;
927
}
928
}
929
return candidate;
930
}
931
}
932
return -1; // No candidate matched the target
933
}
934
935
/**
936
* Returns the starting position of the last occurrence of the specified
937
* target list within the specified source list, or -1 if there is no such
938
* occurrence. More formally, returns the highest index {@code i}
939
* such that {@code source.subList(i, i+target.size()).equals(target)},
940
* or -1 if there is no such index. (Returns -1 if
941
* {@code target.size() > source.size()})
942
*
943
* <p>This implementation uses the "brute force" technique of iterating
944
* over the source list, looking for a match with the target at each
945
* location in turn.
946
*
947
* @param source the list in which to search for the last occurrence
948
* of {@code target}.
949
* @param target the list to search for as a subList of {@code source}.
950
* @return the starting position of the last occurrence of the specified
951
* target list within the specified source list, or -1 if there
952
* is no such occurrence.
953
* @since 1.4
954
*/
955
public static int lastIndexOfSubList(List<?> source, List<?> target) {
956
int sourceSize = source.size();
957
int targetSize = target.size();
958
int maxCandidate = sourceSize - targetSize;
959
960
if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
961
source instanceof RandomAccess) { // Index access version
962
nextCand:
963
for (int candidate = maxCandidate; candidate >= 0; candidate--) {
964
for (int i=0, j=candidate; i<targetSize; i++, j++)
965
if (!eq(target.get(i), source.get(j)))
966
continue nextCand; // Element mismatch, try next cand
967
return candidate; // All elements of candidate matched target
968
}
969
} else { // Iterator version of above algorithm
970
if (maxCandidate < 0)
971
return -1;
972
ListIterator<?> si = source.listIterator(maxCandidate);
973
nextCand:
974
for (int candidate = maxCandidate; candidate >= 0; candidate--) {
975
ListIterator<?> ti = target.listIterator();
976
for (int i=0; i<targetSize; i++) {
977
if (!eq(ti.next(), si.next())) {
978
if (candidate != 0) {
979
// Back up source iterator to next candidate
980
for (int j=0; j<=i+1; j++)
981
si.previous();
982
}
983
continue nextCand;
984
}
985
}
986
return candidate;
987
}
988
}
989
return -1; // No candidate matched the target
990
}
991
992
993
// Unmodifiable Wrappers
994
995
/**
996
* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
997
* specified collection. Query operations on the returned collection "read through"
998
* to the specified collection, and attempts to modify the returned
999
* collection, whether direct or via its iterator, result in an
1000
* {@code UnsupportedOperationException}.<p>
1001
*
1002
* The returned collection does <i>not</i> pass the hashCode and equals
1003
* operations through to the backing collection, but relies on
1004
* {@code Object}'s {@code equals} and {@code hashCode} methods. This
1005
* is necessary to preserve the contracts of these operations in the case
1006
* that the backing collection is a set or a list.<p>
1007
*
1008
* The returned collection will be serializable if the specified collection
1009
* is serializable.
1010
*
1011
* @implNote This method may return its argument if the argument is already unmodifiable.
1012
* @param <T> the class of the objects in the collection
1013
* @param c the collection for which an unmodifiable view is to be
1014
* returned.
1015
* @return an unmodifiable view of the specified collection.
1016
*/
1017
@SuppressWarnings("unchecked")
1018
public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
1019
if (c.getClass() == UnmodifiableCollection.class) {
1020
return (Collection<T>) c;
1021
}
1022
return new UnmodifiableCollection<>(c);
1023
}
1024
1025
/**
1026
* @serial include
1027
*/
1028
static class UnmodifiableCollection<E> implements Collection<E>, Serializable {
1029
@java.io.Serial
1030
private static final long serialVersionUID = 1820017752578914078L;
1031
1032
@SuppressWarnings("serial") // Conditionally serializable
1033
final Collection<? extends E> c;
1034
1035
UnmodifiableCollection(Collection<? extends E> c) {
1036
if (c==null)
1037
throw new NullPointerException();
1038
this.c = c;
1039
}
1040
1041
public int size() {return c.size();}
1042
public boolean isEmpty() {return c.isEmpty();}
1043
public boolean contains(Object o) {return c.contains(o);}
1044
public Object[] toArray() {return c.toArray();}
1045
public <T> T[] toArray(T[] a) {return c.toArray(a);}
1046
public <T> T[] toArray(IntFunction<T[]> f) {return c.toArray(f);}
1047
public String toString() {return c.toString();}
1048
1049
public Iterator<E> iterator() {
1050
return new Iterator<E>() {
1051
private final Iterator<? extends E> i = c.iterator();
1052
1053
public boolean hasNext() {return i.hasNext();}
1054
public E next() {return i.next();}
1055
public void remove() {
1056
throw new UnsupportedOperationException();
1057
}
1058
@Override
1059
public void forEachRemaining(Consumer<? super E> action) {
1060
// Use backing collection version
1061
i.forEachRemaining(action);
1062
}
1063
};
1064
}
1065
1066
public boolean add(E e) {
1067
throw new UnsupportedOperationException();
1068
}
1069
public boolean remove(Object o) {
1070
throw new UnsupportedOperationException();
1071
}
1072
1073
public boolean containsAll(Collection<?> coll) {
1074
return c.containsAll(coll);
1075
}
1076
public boolean addAll(Collection<? extends E> coll) {
1077
throw new UnsupportedOperationException();
1078
}
1079
public boolean removeAll(Collection<?> coll) {
1080
throw new UnsupportedOperationException();
1081
}
1082
public boolean retainAll(Collection<?> coll) {
1083
throw new UnsupportedOperationException();
1084
}
1085
public void clear() {
1086
throw new UnsupportedOperationException();
1087
}
1088
1089
// Override default methods in Collection
1090
@Override
1091
public void forEach(Consumer<? super E> action) {
1092
c.forEach(action);
1093
}
1094
@Override
1095
public boolean removeIf(Predicate<? super E> filter) {
1096
throw new UnsupportedOperationException();
1097
}
1098
@SuppressWarnings("unchecked")
1099
@Override
1100
public Spliterator<E> spliterator() {
1101
return (Spliterator<E>)c.spliterator();
1102
}
1103
@SuppressWarnings("unchecked")
1104
@Override
1105
public Stream<E> stream() {
1106
return (Stream<E>)c.stream();
1107
}
1108
@SuppressWarnings("unchecked")
1109
@Override
1110
public Stream<E> parallelStream() {
1111
return (Stream<E>)c.parallelStream();
1112
}
1113
}
1114
1115
/**
1116
* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1117
* specified set. Query operations on the returned set "read through" to the specified
1118
* set, and attempts to modify the returned set, whether direct or via its
1119
* iterator, result in an {@code UnsupportedOperationException}.<p>
1120
*
1121
* The returned set will be serializable if the specified set
1122
* is serializable.
1123
*
1124
* @implNote This method may return its argument if the argument is already unmodifiable.
1125
* @param <T> the class of the objects in the set
1126
* @param s the set for which an unmodifiable view is to be returned.
1127
* @return an unmodifiable view of the specified set.
1128
*/
1129
@SuppressWarnings("unchecked")
1130
public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
1131
// Not checking for subclasses because of heap pollution and information leakage.
1132
if (s.getClass() == UnmodifiableSet.class) {
1133
return (Set<T>) s;
1134
}
1135
return new UnmodifiableSet<>(s);
1136
}
1137
1138
/**
1139
* @serial include
1140
*/
1141
static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
1142
implements Set<E>, Serializable {
1143
@java.io.Serial
1144
private static final long serialVersionUID = -9215047833775013803L;
1145
1146
UnmodifiableSet(Set<? extends E> s) {super(s);}
1147
public boolean equals(Object o) {return o == this || c.equals(o);}
1148
public int hashCode() {return c.hashCode();}
1149
}
1150
1151
/**
1152
* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1153
* specified sorted set. Query operations on the returned sorted set "read
1154
* through" to the specified sorted set. Attempts to modify the returned
1155
* sorted set, whether direct, via its iterator, or via its
1156
* {@code subSet}, {@code headSet}, or {@code tailSet} views, result in
1157
* an {@code UnsupportedOperationException}.<p>
1158
*
1159
* The returned sorted set will be serializable if the specified sorted set
1160
* is serializable.
1161
*
1162
* @implNote This method may return its argument if the argument is already unmodifiable.
1163
* @param <T> the class of the objects in the set
1164
* @param s the sorted set for which an unmodifiable view is to be
1165
* returned.
1166
* @return an unmodifiable view of the specified sorted set.
1167
*/
1168
public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
1169
// Not checking for subclasses because of heap pollution and information leakage.
1170
if (s.getClass() == UnmodifiableSortedSet.class) {
1171
return s;
1172
}
1173
return new UnmodifiableSortedSet<>(s);
1174
}
1175
1176
/**
1177
* @serial include
1178
*/
1179
static class UnmodifiableSortedSet<E>
1180
extends UnmodifiableSet<E>
1181
implements SortedSet<E>, Serializable {
1182
@java.io.Serial
1183
private static final long serialVersionUID = -4929149591599911165L;
1184
@SuppressWarnings("serial") // Conditionally serializable
1185
private final SortedSet<E> ss;
1186
1187
UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}
1188
1189
public Comparator<? super E> comparator() {return ss.comparator();}
1190
1191
public SortedSet<E> subSet(E fromElement, E toElement) {
1192
return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement));
1193
}
1194
public SortedSet<E> headSet(E toElement) {
1195
return new UnmodifiableSortedSet<>(ss.headSet(toElement));
1196
}
1197
public SortedSet<E> tailSet(E fromElement) {
1198
return new UnmodifiableSortedSet<>(ss.tailSet(fromElement));
1199
}
1200
1201
public E first() {return ss.first();}
1202
public E last() {return ss.last();}
1203
}
1204
1205
/**
1206
* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1207
* specified navigable set. Query operations on the returned navigable set "read
1208
* through" to the specified navigable set. Attempts to modify the returned
1209
* navigable set, whether direct, via its iterator, or via its
1210
* {@code subSet}, {@code headSet}, or {@code tailSet} views, result in
1211
* an {@code UnsupportedOperationException}.<p>
1212
*
1213
* The returned navigable set will be serializable if the specified
1214
* navigable set is serializable.
1215
*
1216
* @implNote This method may return its argument if the argument is already unmodifiable.
1217
* @param <T> the class of the objects in the set
1218
* @param s the navigable set for which an unmodifiable view is to be
1219
* returned
1220
* @return an unmodifiable view of the specified navigable set
1221
* @since 1.8
1222
*/
1223
public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s) {
1224
if (s.getClass() == UnmodifiableNavigableSet.class) {
1225
return s;
1226
}
1227
return new UnmodifiableNavigableSet<>(s);
1228
}
1229
1230
/**
1231
* Wraps a navigable set and disables all of the mutative operations.
1232
*
1233
* @param <E> type of elements
1234
* @serial include
1235
*/
1236
static class UnmodifiableNavigableSet<E>
1237
extends UnmodifiableSortedSet<E>
1238
implements NavigableSet<E>, Serializable {
1239
1240
@java.io.Serial
1241
private static final long serialVersionUID = -6027448201786391929L;
1242
1243
/**
1244
* A singleton empty unmodifiable navigable set used for
1245
* {@link #emptyNavigableSet()}.
1246
*
1247
* @param <E> type of elements, if there were any, and bounds
1248
*/
1249
private static class EmptyNavigableSet<E> extends UnmodifiableNavigableSet<E>
1250
implements Serializable {
1251
@java.io.Serial
1252
private static final long serialVersionUID = -6291252904449939134L;
1253
1254
public EmptyNavigableSet() {
1255
super(new TreeSet<>());
1256
}
1257
1258
@java.io.Serial
1259
private Object readResolve() { return EMPTY_NAVIGABLE_SET; }
1260
}
1261
1262
@SuppressWarnings("rawtypes")
1263
private static final NavigableSet<?> EMPTY_NAVIGABLE_SET =
1264
new EmptyNavigableSet<>();
1265
1266
/**
1267
* The instance we are protecting.
1268
*/
1269
@SuppressWarnings("serial") // Conditionally serializable
1270
private final NavigableSet<E> ns;
1271
1272
UnmodifiableNavigableSet(NavigableSet<E> s) {super(s); ns = s;}
1273
1274
public E lower(E e) { return ns.lower(e); }
1275
public E floor(E e) { return ns.floor(e); }
1276
public E ceiling(E e) { return ns.ceiling(e); }
1277
public E higher(E e) { return ns.higher(e); }
1278
public E pollFirst() { throw new UnsupportedOperationException(); }
1279
public E pollLast() { throw new UnsupportedOperationException(); }
1280
public NavigableSet<E> descendingSet()
1281
{ return new UnmodifiableNavigableSet<>(ns.descendingSet()); }
1282
public Iterator<E> descendingIterator()
1283
{ return descendingSet().iterator(); }
1284
1285
public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
1286
return new UnmodifiableNavigableSet<>(
1287
ns.subSet(fromElement, fromInclusive, toElement, toInclusive));
1288
}
1289
1290
public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1291
return new UnmodifiableNavigableSet<>(
1292
ns.headSet(toElement, inclusive));
1293
}
1294
1295
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1296
return new UnmodifiableNavigableSet<>(
1297
ns.tailSet(fromElement, inclusive));
1298
}
1299
}
1300
1301
/**
1302
* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1303
* specified list. Query operations on the returned list "read through" to the
1304
* specified list, and attempts to modify the returned list, whether
1305
* direct or via its iterator, result in an
1306
* {@code UnsupportedOperationException}.<p>
1307
*
1308
* The returned list will be serializable if the specified list
1309
* is serializable. Similarly, the returned list will implement
1310
* {@link RandomAccess} if the specified list does.
1311
*
1312
* @implNote This method may return its argument if the argument is already unmodifiable.
1313
* @param <T> the class of the objects in the list
1314
* @param list the list for which an unmodifiable view is to be returned.
1315
* @return an unmodifiable view of the specified list.
1316
*/
1317
@SuppressWarnings("unchecked")
1318
public static <T> List<T> unmodifiableList(List<? extends T> list) {
1319
if (list.getClass() == UnmodifiableList.class || list.getClass() == UnmodifiableRandomAccessList.class) {
1320
return (List<T>) list;
1321
}
1322
1323
return (list instanceof RandomAccess ?
1324
new UnmodifiableRandomAccessList<>(list) :
1325
new UnmodifiableList<>(list));
1326
}
1327
1328
/**
1329
* @serial include
1330
*/
1331
static class UnmodifiableList<E> extends UnmodifiableCollection<E>
1332
implements List<E> {
1333
@java.io.Serial
1334
private static final long serialVersionUID = -283967356065247728L;
1335
1336
@SuppressWarnings("serial") // Conditionally serializable
1337
final List<? extends E> list;
1338
1339
UnmodifiableList(List<? extends E> list) {
1340
super(list);
1341
this.list = list;
1342
}
1343
1344
public boolean equals(Object o) {return o == this || list.equals(o);}
1345
public int hashCode() {return list.hashCode();}
1346
1347
public E get(int index) {return list.get(index);}
1348
public E set(int index, E element) {
1349
throw new UnsupportedOperationException();
1350
}
1351
public void add(int index, E element) {
1352
throw new UnsupportedOperationException();
1353
}
1354
public E remove(int index) {
1355
throw new UnsupportedOperationException();
1356
}
1357
public int indexOf(Object o) {return list.indexOf(o);}
1358
public int lastIndexOf(Object o) {return list.lastIndexOf(o);}
1359
public boolean addAll(int index, Collection<? extends E> c) {
1360
throw new UnsupportedOperationException();
1361
}
1362
1363
@Override
1364
public void replaceAll(UnaryOperator<E> operator) {
1365
throw new UnsupportedOperationException();
1366
}
1367
@Override
1368
public void sort(Comparator<? super E> c) {
1369
throw new UnsupportedOperationException();
1370
}
1371
1372
public ListIterator<E> listIterator() {return listIterator(0);}
1373
1374
public ListIterator<E> listIterator(final int index) {
1375
return new ListIterator<E>() {
1376
private final ListIterator<? extends E> i
1377
= list.listIterator(index);
1378
1379
public boolean hasNext() {return i.hasNext();}
1380
public E next() {return i.next();}
1381
public boolean hasPrevious() {return i.hasPrevious();}
1382
public E previous() {return i.previous();}
1383
public int nextIndex() {return i.nextIndex();}
1384
public int previousIndex() {return i.previousIndex();}
1385
1386
public void remove() {
1387
throw new UnsupportedOperationException();
1388
}
1389
public void set(E e) {
1390
throw new UnsupportedOperationException();
1391
}
1392
public void add(E e) {
1393
throw new UnsupportedOperationException();
1394
}
1395
1396
@Override
1397
public void forEachRemaining(Consumer<? super E> action) {
1398
i.forEachRemaining(action);
1399
}
1400
};
1401
}
1402
1403
public List<E> subList(int fromIndex, int toIndex) {
1404
return new UnmodifiableList<>(list.subList(fromIndex, toIndex));
1405
}
1406
1407
/**
1408
* UnmodifiableRandomAccessList instances are serialized as
1409
* UnmodifiableList instances to allow them to be deserialized
1410
* in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList).
1411
* This method inverts the transformation. As a beneficial
1412
* side-effect, it also grafts the RandomAccess marker onto
1413
* UnmodifiableList instances that were serialized in pre-1.4 JREs.
1414
*
1415
* Note: Unfortunately, UnmodifiableRandomAccessList instances
1416
* serialized in 1.4.1 and deserialized in 1.4 will become
1417
* UnmodifiableList instances, as this method was missing in 1.4.
1418
*/
1419
@java.io.Serial
1420
private Object readResolve() {
1421
return (list instanceof RandomAccess
1422
? new UnmodifiableRandomAccessList<>(list)
1423
: this);
1424
}
1425
}
1426
1427
/**
1428
* @serial include
1429
*/
1430
static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E>
1431
implements RandomAccess
1432
{
1433
UnmodifiableRandomAccessList(List<? extends E> list) {
1434
super(list);
1435
}
1436
1437
public List<E> subList(int fromIndex, int toIndex) {
1438
return new UnmodifiableRandomAccessList<>(
1439
list.subList(fromIndex, toIndex));
1440
}
1441
1442
@java.io.Serial
1443
private static final long serialVersionUID = -2542308836966382001L;
1444
1445
/**
1446
* Allows instances to be deserialized in pre-1.4 JREs (which do
1447
* not have UnmodifiableRandomAccessList). UnmodifiableList has
1448
* a readResolve method that inverts this transformation upon
1449
* deserialization.
1450
*/
1451
@java.io.Serial
1452
private Object writeReplace() {
1453
return new UnmodifiableList<>(list);
1454
}
1455
}
1456
1457
/**
1458
* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1459
* specified map. Query operations on the returned map "read through"
1460
* to the specified map, and attempts to modify the returned
1461
* map, whether direct or via its collection views, result in an
1462
* {@code UnsupportedOperationException}.<p>
1463
*
1464
* The returned map will be serializable if the specified map
1465
* is serializable.
1466
*
1467
* @implNote This method may return its argument if the argument is already unmodifiable.
1468
* @param <K> the class of the map keys
1469
* @param <V> the class of the map values
1470
* @param m the map for which an unmodifiable view is to be returned.
1471
* @return an unmodifiable view of the specified map.
1472
*/
1473
@SuppressWarnings("unchecked")
1474
public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
1475
// Not checking for subclasses because of heap pollution and information leakage.
1476
if (m.getClass() == UnmodifiableMap.class) {
1477
return (Map<K,V>) m;
1478
}
1479
return new UnmodifiableMap<>(m);
1480
}
1481
1482
/**
1483
* @serial include
1484
*/
1485
private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {
1486
@java.io.Serial
1487
private static final long serialVersionUID = -1034234728574286014L;
1488
1489
@SuppressWarnings("serial") // Conditionally serializable
1490
private final Map<? extends K, ? extends V> m;
1491
1492
UnmodifiableMap(Map<? extends K, ? extends V> m) {
1493
if (m==null)
1494
throw new NullPointerException();
1495
this.m = m;
1496
}
1497
1498
public int size() {return m.size();}
1499
public boolean isEmpty() {return m.isEmpty();}
1500
public boolean containsKey(Object key) {return m.containsKey(key);}
1501
public boolean containsValue(Object val) {return m.containsValue(val);}
1502
public V get(Object key) {return m.get(key);}
1503
1504
public V put(K key, V value) {
1505
throw new UnsupportedOperationException();
1506
}
1507
public V remove(Object key) {
1508
throw new UnsupportedOperationException();
1509
}
1510
public void putAll(Map<? extends K, ? extends V> m) {
1511
throw new UnsupportedOperationException();
1512
}
1513
public void clear() {
1514
throw new UnsupportedOperationException();
1515
}
1516
1517
private transient Set<K> keySet;
1518
private transient Set<Map.Entry<K,V>> entrySet;
1519
private transient Collection<V> values;
1520
1521
public Set<K> keySet() {
1522
if (keySet==null)
1523
keySet = unmodifiableSet(m.keySet());
1524
return keySet;
1525
}
1526
1527
public Set<Map.Entry<K,V>> entrySet() {
1528
if (entrySet==null)
1529
entrySet = new UnmodifiableEntrySet<>(m.entrySet());
1530
return entrySet;
1531
}
1532
1533
public Collection<V> values() {
1534
if (values==null)
1535
values = unmodifiableCollection(m.values());
1536
return values;
1537
}
1538
1539
public boolean equals(Object o) {return o == this || m.equals(o);}
1540
public int hashCode() {return m.hashCode();}
1541
public String toString() {return m.toString();}
1542
1543
// Override default methods in Map
1544
@Override
1545
@SuppressWarnings("unchecked")
1546
public V getOrDefault(Object k, V defaultValue) {
1547
// Safe cast as we don't change the value
1548
return ((Map<K, V>)m).getOrDefault(k, defaultValue);
1549
}
1550
1551
@Override
1552
public void forEach(BiConsumer<? super K, ? super V> action) {
1553
m.forEach(action);
1554
}
1555
1556
@Override
1557
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1558
throw new UnsupportedOperationException();
1559
}
1560
1561
@Override
1562
public V putIfAbsent(K key, V value) {
1563
throw new UnsupportedOperationException();
1564
}
1565
1566
@Override
1567
public boolean remove(Object key, Object value) {
1568
throw new UnsupportedOperationException();
1569
}
1570
1571
@Override
1572
public boolean replace(K key, V oldValue, V newValue) {
1573
throw new UnsupportedOperationException();
1574
}
1575
1576
@Override
1577
public V replace(K key, V value) {
1578
throw new UnsupportedOperationException();
1579
}
1580
1581
@Override
1582
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
1583
throw new UnsupportedOperationException();
1584
}
1585
1586
@Override
1587
public V computeIfPresent(K key,
1588
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1589
throw new UnsupportedOperationException();
1590
}
1591
1592
@Override
1593
public V compute(K key,
1594
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1595
throw new UnsupportedOperationException();
1596
}
1597
1598
@Override
1599
public V merge(K key, V value,
1600
BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1601
throw new UnsupportedOperationException();
1602
}
1603
1604
/**
1605
* We need this class in addition to UnmodifiableSet as
1606
* Map.Entries themselves permit modification of the backing Map
1607
* via their setValue operation. This class is subtle: there are
1608
* many possible attacks that must be thwarted.
1609
*
1610
* @serial include
1611
*/
1612
static class UnmodifiableEntrySet<K,V>
1613
extends UnmodifiableSet<Map.Entry<K,V>> {
1614
@java.io.Serial
1615
private static final long serialVersionUID = 7854390611657943733L;
1616
1617
@SuppressWarnings({"unchecked", "rawtypes"})
1618
UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) {
1619
// Need to cast to raw in order to work around a limitation in the type system
1620
super((Set)s);
1621
}
1622
1623
static <K, V> Consumer<Map.Entry<? extends K, ? extends V>> entryConsumer(
1624
Consumer<? super Entry<K, V>> action) {
1625
return e -> action.accept(new UnmodifiableEntry<>(e));
1626
}
1627
1628
public void forEach(Consumer<? super Entry<K, V>> action) {
1629
Objects.requireNonNull(action);
1630
c.forEach(entryConsumer(action));
1631
}
1632
1633
static final class UnmodifiableEntrySetSpliterator<K, V>
1634
implements Spliterator<Entry<K,V>> {
1635
final Spliterator<Map.Entry<K, V>> s;
1636
1637
UnmodifiableEntrySetSpliterator(Spliterator<Entry<K, V>> s) {
1638
this.s = s;
1639
}
1640
1641
@Override
1642
public boolean tryAdvance(Consumer<? super Entry<K, V>> action) {
1643
Objects.requireNonNull(action);
1644
return s.tryAdvance(entryConsumer(action));
1645
}
1646
1647
@Override
1648
public void forEachRemaining(Consumer<? super Entry<K, V>> action) {
1649
Objects.requireNonNull(action);
1650
s.forEachRemaining(entryConsumer(action));
1651
}
1652
1653
@Override
1654
public Spliterator<Entry<K, V>> trySplit() {
1655
Spliterator<Entry<K, V>> split = s.trySplit();
1656
return split == null
1657
? null
1658
: new UnmodifiableEntrySetSpliterator<>(split);
1659
}
1660
1661
@Override
1662
public long estimateSize() {
1663
return s.estimateSize();
1664
}
1665
1666
@Override
1667
public long getExactSizeIfKnown() {
1668
return s.getExactSizeIfKnown();
1669
}
1670
1671
@Override
1672
public int characteristics() {
1673
return s.characteristics();
1674
}
1675
1676
@Override
1677
public boolean hasCharacteristics(int characteristics) {
1678
return s.hasCharacteristics(characteristics);
1679
}
1680
1681
@Override
1682
public Comparator<? super Entry<K, V>> getComparator() {
1683
return s.getComparator();
1684
}
1685
}
1686
1687
@SuppressWarnings("unchecked")
1688
public Spliterator<Entry<K,V>> spliterator() {
1689
return new UnmodifiableEntrySetSpliterator<>(
1690
(Spliterator<Map.Entry<K, V>>) c.spliterator());
1691
}
1692
1693
@Override
1694
public Stream<Entry<K,V>> stream() {
1695
return StreamSupport.stream(spliterator(), false);
1696
}
1697
1698
@Override
1699
public Stream<Entry<K,V>> parallelStream() {
1700
return StreamSupport.stream(spliterator(), true);
1701
}
1702
1703
public Iterator<Map.Entry<K,V>> iterator() {
1704
return new Iterator<Map.Entry<K,V>>() {
1705
private final Iterator<? extends Map.Entry<? extends K, ? extends V>> i = c.iterator();
1706
1707
public boolean hasNext() {
1708
return i.hasNext();
1709
}
1710
public Map.Entry<K,V> next() {
1711
return new UnmodifiableEntry<>(i.next());
1712
}
1713
public void remove() {
1714
throw new UnsupportedOperationException();
1715
}
1716
public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {
1717
i.forEachRemaining(entryConsumer(action));
1718
}
1719
};
1720
}
1721
1722
@SuppressWarnings("unchecked")
1723
public Object[] toArray() {
1724
Object[] a = c.toArray();
1725
for (int i=0; i<a.length; i++)
1726
a[i] = new UnmodifiableEntry<>((Map.Entry<? extends K, ? extends V>)a[i]);
1727
return a;
1728
}
1729
1730
@SuppressWarnings("unchecked")
1731
public <T> T[] toArray(T[] a) {
1732
// We don't pass a to c.toArray, to avoid window of
1733
// vulnerability wherein an unscrupulous multithreaded client
1734
// could get his hands on raw (unwrapped) Entries from c.
1735
Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
1736
1737
for (int i=0; i<arr.length; i++)
1738
arr[i] = new UnmodifiableEntry<>((Map.Entry<? extends K, ? extends V>)arr[i]);
1739
1740
if (arr.length > a.length)
1741
return (T[])arr;
1742
1743
System.arraycopy(arr, 0, a, 0, arr.length);
1744
if (a.length > arr.length)
1745
a[arr.length] = null;
1746
return a;
1747
}
1748
1749
/**
1750
* This method is overridden to protect the backing set against
1751
* an object with a nefarious equals function that senses
1752
* that the equality-candidate is Map.Entry and calls its
1753
* setValue method.
1754
*/
1755
public boolean contains(Object o) {
1756
if (!(o instanceof Map.Entry))
1757
return false;
1758
return c.contains(
1759
new UnmodifiableEntry<>((Map.Entry<?,?>) o));
1760
}
1761
1762
/**
1763
* The next two methods are overridden to protect against
1764
* an unscrupulous List whose contains(Object o) method senses
1765
* when o is a Map.Entry, and calls o.setValue.
1766
*/
1767
public boolean containsAll(Collection<?> coll) {
1768
for (Object e : coll) {
1769
if (!contains(e)) // Invokes safe contains() above
1770
return false;
1771
}
1772
return true;
1773
}
1774
public boolean equals(Object o) {
1775
if (o == this)
1776
return true;
1777
1778
return o instanceof Set<?> s
1779
&& s.size() == c.size()
1780
&& containsAll(s); // Invokes safe containsAll() above
1781
}
1782
1783
/**
1784
* This "wrapper class" serves two purposes: it prevents
1785
* the client from modifying the backing Map, by short-circuiting
1786
* the setValue method, and it protects the backing Map against
1787
* an ill-behaved Map.Entry that attempts to modify another
1788
* Map Entry when asked to perform an equality check.
1789
*/
1790
private static class UnmodifiableEntry<K,V> implements Map.Entry<K,V> {
1791
private Map.Entry<? extends K, ? extends V> e;
1792
1793
UnmodifiableEntry(Map.Entry<? extends K, ? extends V> e)
1794
{this.e = Objects.requireNonNull(e);}
1795
1796
public K getKey() {return e.getKey();}
1797
public V getValue() {return e.getValue();}
1798
public V setValue(V value) {
1799
throw new UnsupportedOperationException();
1800
}
1801
public int hashCode() {return e.hashCode();}
1802
public boolean equals(Object o) {
1803
if (this == o)
1804
return true;
1805
return o instanceof Map.Entry<?, ?> t
1806
&& eq(e.getKey(), t.getKey())
1807
&& eq(e.getValue(), t.getValue());
1808
}
1809
public String toString() {return e.toString();}
1810
}
1811
}
1812
}
1813
1814
/**
1815
* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1816
* specified sorted map. Query operations on the returned sorted map "read through"
1817
* to the specified sorted map. Attempts to modify the returned
1818
* sorted map, whether direct, via its collection views, or via its
1819
* {@code subMap}, {@code headMap}, or {@code tailMap} views, result in
1820
* an {@code UnsupportedOperationException}.<p>
1821
*
1822
* The returned sorted map will be serializable if the specified sorted map
1823
* is serializable.
1824
*
1825
* @implNote This method may return its argument if the argument is already unmodifiable.
1826
* @param <K> the class of the map keys
1827
* @param <V> the class of the map values
1828
* @param m the sorted map for which an unmodifiable view is to be
1829
* returned.
1830
* @return an unmodifiable view of the specified sorted map.
1831
*/
1832
@SuppressWarnings("unchecked")
1833
public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {
1834
// Not checking for subclasses because of heap pollution and information leakage.
1835
if (m.getClass() == UnmodifiableSortedMap.class) {
1836
return (SortedMap<K,V>) m;
1837
}
1838
return new UnmodifiableSortedMap<>(m);
1839
}
1840
1841
/**
1842
* @serial include
1843
*/
1844
static class UnmodifiableSortedMap<K,V>
1845
extends UnmodifiableMap<K,V>
1846
implements SortedMap<K,V>, Serializable {
1847
@java.io.Serial
1848
private static final long serialVersionUID = -8806743815996713206L;
1849
1850
@SuppressWarnings("serial") // Conditionally serializable
1851
private final SortedMap<K, ? extends V> sm;
1852
1853
UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m; }
1854
public Comparator<? super K> comparator() { return sm.comparator(); }
1855
public SortedMap<K,V> subMap(K fromKey, K toKey)
1856
{ return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey)); }
1857
public SortedMap<K,V> headMap(K toKey)
1858
{ return new UnmodifiableSortedMap<>(sm.headMap(toKey)); }
1859
public SortedMap<K,V> tailMap(K fromKey)
1860
{ return new UnmodifiableSortedMap<>(sm.tailMap(fromKey)); }
1861
public K firstKey() { return sm.firstKey(); }
1862
public K lastKey() { return sm.lastKey(); }
1863
}
1864
1865
/**
1866
* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1867
* specified navigable map. Query operations on the returned navigable map "read
1868
* through" to the specified navigable map. Attempts to modify the returned
1869
* navigable map, whether direct, via its collection views, or via its
1870
* {@code subMap}, {@code headMap}, or {@code tailMap} views, result in
1871
* an {@code UnsupportedOperationException}.<p>
1872
*
1873
* The returned navigable map will be serializable if the specified
1874
* navigable map is serializable.
1875
*
1876
* @implNote This method may return its argument if the argument is already unmodifiable.
1877
* @param <K> the class of the map keys
1878
* @param <V> the class of the map values
1879
* @param m the navigable map for which an unmodifiable view is to be
1880
* returned
1881
* @return an unmodifiable view of the specified navigable map
1882
* @since 1.8
1883
*/
1884
@SuppressWarnings("unchecked")
1885
public static <K,V> NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> m) {
1886
if (m.getClass() == UnmodifiableNavigableMap.class) {
1887
return (NavigableMap<K,V>) m;
1888
}
1889
return new UnmodifiableNavigableMap<>(m);
1890
}
1891
1892
/**
1893
* @serial include
1894
*/
1895
static class UnmodifiableNavigableMap<K,V>
1896
extends UnmodifiableSortedMap<K,V>
1897
implements NavigableMap<K,V>, Serializable {
1898
@java.io.Serial
1899
private static final long serialVersionUID = -4858195264774772197L;
1900
1901
/**
1902
* A class for the {@link EMPTY_NAVIGABLE_MAP} which needs readResolve
1903
* to preserve singleton property.
1904
*
1905
* @param <K> type of keys, if there were any, and of bounds
1906
* @param <V> type of values, if there were any
1907
*/
1908
private static class EmptyNavigableMap<K,V> extends UnmodifiableNavigableMap<K,V>
1909
implements Serializable {
1910
1911
@java.io.Serial
1912
private static final long serialVersionUID = -2239321462712562324L;
1913
1914
EmptyNavigableMap() { super(new TreeMap<>()); }
1915
1916
@Override
1917
public NavigableSet<K> navigableKeySet()
1918
{ return emptyNavigableSet(); }
1919
1920
@java.io.Serial
1921
private Object readResolve() { return EMPTY_NAVIGABLE_MAP; }
1922
}
1923
1924
/**
1925
* Singleton for {@link emptyNavigableMap()} which is also immutable.
1926
*/
1927
private static final EmptyNavigableMap<?,?> EMPTY_NAVIGABLE_MAP =
1928
new EmptyNavigableMap<>();
1929
1930
/**
1931
* The instance we wrap and protect.
1932
*/
1933
@SuppressWarnings("serial") // Conditionally serializable
1934
private final NavigableMap<K, ? extends V> nm;
1935
1936
UnmodifiableNavigableMap(NavigableMap<K, ? extends V> m)
1937
{super(m); nm = m;}
1938
1939
public K lowerKey(K key) { return nm.lowerKey(key); }
1940
public K floorKey(K key) { return nm.floorKey(key); }
1941
public K ceilingKey(K key) { return nm.ceilingKey(key); }
1942
public K higherKey(K key) { return nm.higherKey(key); }
1943
1944
@SuppressWarnings("unchecked")
1945
public Entry<K, V> lowerEntry(K key) {
1946
Entry<K,V> lower = (Entry<K, V>) nm.lowerEntry(key);
1947
return (null != lower)
1948
? new UnmodifiableEntrySet.UnmodifiableEntry<>(lower)
1949
: null;
1950
}
1951
1952
@SuppressWarnings("unchecked")
1953
public Entry<K, V> floorEntry(K key) {
1954
Entry<K,V> floor = (Entry<K, V>) nm.floorEntry(key);
1955
return (null != floor)
1956
? new UnmodifiableEntrySet.UnmodifiableEntry<>(floor)
1957
: null;
1958
}
1959
1960
@SuppressWarnings("unchecked")
1961
public Entry<K, V> ceilingEntry(K key) {
1962
Entry<K,V> ceiling = (Entry<K, V>) nm.ceilingEntry(key);
1963
return (null != ceiling)
1964
? new UnmodifiableEntrySet.UnmodifiableEntry<>(ceiling)
1965
: null;
1966
}
1967
1968
1969
@SuppressWarnings("unchecked")
1970
public Entry<K, V> higherEntry(K key) {
1971
Entry<K,V> higher = (Entry<K, V>) nm.higherEntry(key);
1972
return (null != higher)
1973
? new UnmodifiableEntrySet.UnmodifiableEntry<>(higher)
1974
: null;
1975
}
1976
1977
@SuppressWarnings("unchecked")
1978
public Entry<K, V> firstEntry() {
1979
Entry<K,V> first = (Entry<K, V>) nm.firstEntry();
1980
return (null != first)
1981
? new UnmodifiableEntrySet.UnmodifiableEntry<>(first)
1982
: null;
1983
}
1984
1985
@SuppressWarnings("unchecked")
1986
public Entry<K, V> lastEntry() {
1987
Entry<K,V> last = (Entry<K, V>) nm.lastEntry();
1988
return (null != last)
1989
? new UnmodifiableEntrySet.UnmodifiableEntry<>(last)
1990
: null;
1991
}
1992
1993
public Entry<K, V> pollFirstEntry()
1994
{ throw new UnsupportedOperationException(); }
1995
public Entry<K, V> pollLastEntry()
1996
{ throw new UnsupportedOperationException(); }
1997
public NavigableMap<K, V> descendingMap()
1998
{ return unmodifiableNavigableMap(nm.descendingMap()); }
1999
public NavigableSet<K> navigableKeySet()
2000
{ return unmodifiableNavigableSet(nm.navigableKeySet()); }
2001
public NavigableSet<K> descendingKeySet()
2002
{ return unmodifiableNavigableSet(nm.descendingKeySet()); }
2003
2004
public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
2005
return unmodifiableNavigableMap(
2006
nm.subMap(fromKey, fromInclusive, toKey, toInclusive));
2007
}
2008
2009
public NavigableMap<K, V> headMap(K toKey, boolean inclusive)
2010
{ return unmodifiableNavigableMap(nm.headMap(toKey, inclusive)); }
2011
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive)
2012
{ return unmodifiableNavigableMap(nm.tailMap(fromKey, inclusive)); }
2013
}
2014
2015
// Synch Wrappers
2016
2017
/**
2018
* Returns a synchronized (thread-safe) collection backed by the specified
2019
* collection. In order to guarantee serial access, it is critical that
2020
* <strong>all</strong> access to the backing collection is accomplished
2021
* through the returned collection.<p>
2022
*
2023
* It is imperative that the user manually synchronize on the returned
2024
* collection when traversing it via {@link Iterator}, {@link Spliterator}
2025
* or {@link Stream}:
2026
* <pre>
2027
* Collection c = Collections.synchronizedCollection(myCollection);
2028
* ...
2029
* synchronized (c) {
2030
* Iterator i = c.iterator(); // Must be in the synchronized block
2031
* while (i.hasNext())
2032
* foo(i.next());
2033
* }
2034
* </pre>
2035
* Failure to follow this advice may result in non-deterministic behavior.
2036
*
2037
* <p>The returned collection does <i>not</i> pass the {@code hashCode}
2038
* and {@code equals} operations through to the backing collection, but
2039
* relies on {@code Object}'s equals and hashCode methods. This is
2040
* necessary to preserve the contracts of these operations in the case
2041
* that the backing collection is a set or a list.<p>
2042
*
2043
* The returned collection will be serializable if the specified collection
2044
* is serializable.
2045
*
2046
* @param <T> the class of the objects in the collection
2047
* @param c the collection to be "wrapped" in a synchronized collection.
2048
* @return a synchronized view of the specified collection.
2049
*/
2050
public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
2051
return new SynchronizedCollection<>(c);
2052
}
2053
2054
static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {
2055
return new SynchronizedCollection<>(c, mutex);
2056
}
2057
2058
/**
2059
* @serial include
2060
*/
2061
static class SynchronizedCollection<E> implements Collection<E>, Serializable {
2062
@java.io.Serial
2063
private static final long serialVersionUID = 3053995032091335093L;
2064
2065
@SuppressWarnings("serial") // Conditionally serializable
2066
final Collection<E> c; // Backing Collection
2067
@SuppressWarnings("serial") // Conditionally serializable
2068
final Object mutex; // Object on which to synchronize
2069
2070
SynchronizedCollection(Collection<E> c) {
2071
this.c = Objects.requireNonNull(c);
2072
mutex = this;
2073
}
2074
2075
SynchronizedCollection(Collection<E> c, Object mutex) {
2076
this.c = Objects.requireNonNull(c);
2077
this.mutex = Objects.requireNonNull(mutex);
2078
}
2079
2080
public int size() {
2081
synchronized (mutex) {return c.size();}
2082
}
2083
public boolean isEmpty() {
2084
synchronized (mutex) {return c.isEmpty();}
2085
}
2086
public boolean contains(Object o) {
2087
synchronized (mutex) {return c.contains(o);}
2088
}
2089
public Object[] toArray() {
2090
synchronized (mutex) {return c.toArray();}
2091
}
2092
public <T> T[] toArray(T[] a) {
2093
synchronized (mutex) {return c.toArray(a);}
2094
}
2095
public <T> T[] toArray(IntFunction<T[]> f) {
2096
synchronized (mutex) {return c.toArray(f);}
2097
}
2098
2099
public Iterator<E> iterator() {
2100
return c.iterator(); // Must be manually synched by user!
2101
}
2102
2103
public boolean add(E e) {
2104
synchronized (mutex) {return c.add(e);}
2105
}
2106
public boolean remove(Object o) {
2107
synchronized (mutex) {return c.remove(o);}
2108
}
2109
2110
public boolean containsAll(Collection<?> coll) {
2111
synchronized (mutex) {return c.containsAll(coll);}
2112
}
2113
public boolean addAll(Collection<? extends E> coll) {
2114
synchronized (mutex) {return c.addAll(coll);}
2115
}
2116
public boolean removeAll(Collection<?> coll) {
2117
synchronized (mutex) {return c.removeAll(coll);}
2118
}
2119
public boolean retainAll(Collection<?> coll) {
2120
synchronized (mutex) {return c.retainAll(coll);}
2121
}
2122
public void clear() {
2123
synchronized (mutex) {c.clear();}
2124
}
2125
public String toString() {
2126
synchronized (mutex) {return c.toString();}
2127
}
2128
// Override default methods in Collection
2129
@Override
2130
public void forEach(Consumer<? super E> consumer) {
2131
synchronized (mutex) {c.forEach(consumer);}
2132
}
2133
@Override
2134
public boolean removeIf(Predicate<? super E> filter) {
2135
synchronized (mutex) {return c.removeIf(filter);}
2136
}
2137
@Override
2138
public Spliterator<E> spliterator() {
2139
return c.spliterator(); // Must be manually synched by user!
2140
}
2141
@Override
2142
public Stream<E> stream() {
2143
return c.stream(); // Must be manually synched by user!
2144
}
2145
@Override
2146
public Stream<E> parallelStream() {
2147
return c.parallelStream(); // Must be manually synched by user!
2148
}
2149
@java.io.Serial
2150
private void writeObject(ObjectOutputStream s) throws IOException {
2151
synchronized (mutex) {s.defaultWriteObject();}
2152
}
2153
}
2154
2155
/**
2156
* Returns a synchronized (thread-safe) set backed by the specified
2157
* set. In order to guarantee serial access, it is critical that
2158
* <strong>all</strong> access to the backing set is accomplished
2159
* through the returned set.<p>
2160
*
2161
* It is imperative that the user manually synchronize on the returned
2162
* collection when traversing it via {@link Iterator}, {@link Spliterator}
2163
* or {@link Stream}:
2164
* <pre>
2165
* Set s = Collections.synchronizedSet(new HashSet());
2166
* ...
2167
* synchronized (s) {
2168
* Iterator i = s.iterator(); // Must be in the synchronized block
2169
* while (i.hasNext())
2170
* foo(i.next());
2171
* }
2172
* </pre>
2173
* Failure to follow this advice may result in non-deterministic behavior.
2174
*
2175
* <p>The returned set will be serializable if the specified set is
2176
* serializable.
2177
*
2178
* @param <T> the class of the objects in the set
2179
* @param s the set to be "wrapped" in a synchronized set.
2180
* @return a synchronized view of the specified set.
2181
*/
2182
public static <T> Set<T> synchronizedSet(Set<T> s) {
2183
return new SynchronizedSet<>(s);
2184
}
2185
2186
static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {
2187
return new SynchronizedSet<>(s, mutex);
2188
}
2189
2190
/**
2191
* @serial include
2192
*/
2193
static class SynchronizedSet<E>
2194
extends SynchronizedCollection<E>
2195
implements Set<E> {
2196
@java.io.Serial
2197
private static final long serialVersionUID = 487447009682186044L;
2198
2199
SynchronizedSet(Set<E> s) {
2200
super(s);
2201
}
2202
SynchronizedSet(Set<E> s, Object mutex) {
2203
super(s, mutex);
2204
}
2205
2206
public boolean equals(Object o) {
2207
if (this == o)
2208
return true;
2209
synchronized (mutex) {return c.equals(o);}
2210
}
2211
public int hashCode() {
2212
synchronized (mutex) {return c.hashCode();}
2213
}
2214
}
2215
2216
/**
2217
* Returns a synchronized (thread-safe) sorted set backed by the specified
2218
* sorted set. In order to guarantee serial access, it is critical that
2219
* <strong>all</strong> access to the backing sorted set is accomplished
2220
* through the returned sorted set (or its views).<p>
2221
*
2222
* It is imperative that the user manually synchronize on the returned
2223
* sorted set when traversing it or any of its {@code subSet},
2224
* {@code headSet}, or {@code tailSet} views via {@link Iterator},
2225
* {@link Spliterator} or {@link Stream}:
2226
* <pre>
2227
* SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
2228
* ...
2229
* synchronized (s) {
2230
* Iterator i = s.iterator(); // Must be in the synchronized block
2231
* while (i.hasNext())
2232
* foo(i.next());
2233
* }
2234
* </pre>
2235
* or:
2236
* <pre>
2237
* SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
2238
* SortedSet s2 = s.headSet(foo);
2239
* ...
2240
* synchronized (s) { // Note: s, not s2!!!
2241
* Iterator i = s2.iterator(); // Must be in the synchronized block
2242
* while (i.hasNext())
2243
* foo(i.next());
2244
* }
2245
* </pre>
2246
* Failure to follow this advice may result in non-deterministic behavior.
2247
*
2248
* <p>The returned sorted set will be serializable if the specified
2249
* sorted set is serializable.
2250
*
2251
* @param <T> the class of the objects in the set
2252
* @param s the sorted set to be "wrapped" in a synchronized sorted set.
2253
* @return a synchronized view of the specified sorted set.
2254
*/
2255
public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) {
2256
return new SynchronizedSortedSet<>(s);
2257
}
2258
2259
/**
2260
* @serial include
2261
*/
2262
static class SynchronizedSortedSet<E>
2263
extends SynchronizedSet<E>
2264
implements SortedSet<E>
2265
{
2266
@java.io.Serial
2267
private static final long serialVersionUID = 8695801310862127406L;
2268
2269
@SuppressWarnings("serial") // Conditionally serializable
2270
private final SortedSet<E> ss;
2271
2272
SynchronizedSortedSet(SortedSet<E> s) {
2273
super(s);
2274
ss = s;
2275
}
2276
SynchronizedSortedSet(SortedSet<E> s, Object mutex) {
2277
super(s, mutex);
2278
ss = s;
2279
}
2280
2281
public Comparator<? super E> comparator() {
2282
synchronized (mutex) {return ss.comparator();}
2283
}
2284
2285
public SortedSet<E> subSet(E fromElement, E toElement) {
2286
synchronized (mutex) {
2287
return new SynchronizedSortedSet<>(
2288
ss.subSet(fromElement, toElement), mutex);
2289
}
2290
}
2291
public SortedSet<E> headSet(E toElement) {
2292
synchronized (mutex) {
2293
return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex);
2294
}
2295
}
2296
public SortedSet<E> tailSet(E fromElement) {
2297
synchronized (mutex) {
2298
return new SynchronizedSortedSet<>(ss.tailSet(fromElement),mutex);
2299
}
2300
}
2301
2302
public E first() {
2303
synchronized (mutex) {return ss.first();}
2304
}
2305
public E last() {
2306
synchronized (mutex) {return ss.last();}
2307
}
2308
}
2309
2310
/**
2311
* Returns a synchronized (thread-safe) navigable set backed by the
2312
* specified navigable set. In order to guarantee serial access, it is
2313
* critical that <strong>all</strong> access to the backing navigable set is
2314
* accomplished through the returned navigable set (or its views).<p>
2315
*
2316
* It is imperative that the user manually synchronize on the returned
2317
* navigable set when traversing it, or any of its {@code subSet},
2318
* {@code headSet}, or {@code tailSet} views, via {@link Iterator},
2319
* {@link Spliterator} or {@link Stream}:
2320
* <pre>
2321
* NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());
2322
* ...
2323
* synchronized (s) {
2324
* Iterator i = s.iterator(); // Must be in the synchronized block
2325
* while (i.hasNext())
2326
* foo(i.next());
2327
* }
2328
* </pre>
2329
* or:
2330
* <pre>
2331
* NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());
2332
* NavigableSet s2 = s.headSet(foo, true);
2333
* ...
2334
* synchronized (s) { // Note: s, not s2!!!
2335
* Iterator i = s2.iterator(); // Must be in the synchronized block
2336
* while (i.hasNext())
2337
* foo(i.next());
2338
* }
2339
* </pre>
2340
* Failure to follow this advice may result in non-deterministic behavior.
2341
*
2342
* <p>The returned navigable set will be serializable if the specified
2343
* navigable set is serializable.
2344
*
2345
* @param <T> the class of the objects in the set
2346
* @param s the navigable set to be "wrapped" in a synchronized navigable
2347
* set
2348
* @return a synchronized view of the specified navigable set
2349
* @since 1.8
2350
*/
2351
public static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s) {
2352
return new SynchronizedNavigableSet<>(s);
2353
}
2354
2355
/**
2356
* @serial include
2357
*/
2358
static class SynchronizedNavigableSet<E>
2359
extends SynchronizedSortedSet<E>
2360
implements NavigableSet<E>
2361
{
2362
@java.io.Serial
2363
private static final long serialVersionUID = -5505529816273629798L;
2364
2365
@SuppressWarnings("serial") // Conditionally serializable
2366
private final NavigableSet<E> ns;
2367
2368
SynchronizedNavigableSet(NavigableSet<E> s) {
2369
super(s);
2370
ns = s;
2371
}
2372
2373
SynchronizedNavigableSet(NavigableSet<E> s, Object mutex) {
2374
super(s, mutex);
2375
ns = s;
2376
}
2377
public E lower(E e) { synchronized (mutex) {return ns.lower(e);} }
2378
public E floor(E e) { synchronized (mutex) {return ns.floor(e);} }
2379
public E ceiling(E e) { synchronized (mutex) {return ns.ceiling(e);} }
2380
public E higher(E e) { synchronized (mutex) {return ns.higher(e);} }
2381
public E pollFirst() { synchronized (mutex) {return ns.pollFirst();} }
2382
public E pollLast() { synchronized (mutex) {return ns.pollLast();} }
2383
2384
public NavigableSet<E> descendingSet() {
2385
synchronized (mutex) {
2386
return new SynchronizedNavigableSet<>(ns.descendingSet(), mutex);
2387
}
2388
}
2389
2390
public Iterator<E> descendingIterator()
2391
{ synchronized (mutex) { return descendingSet().iterator(); } }
2392
2393
public NavigableSet<E> subSet(E fromElement, E toElement) {
2394
synchronized (mutex) {
2395
return new SynchronizedNavigableSet<>(ns.subSet(fromElement, true, toElement, false), mutex);
2396
}
2397
}
2398
public NavigableSet<E> headSet(E toElement) {
2399
synchronized (mutex) {
2400
return new SynchronizedNavigableSet<>(ns.headSet(toElement, false), mutex);
2401
}
2402
}
2403
public NavigableSet<E> tailSet(E fromElement) {
2404
synchronized (mutex) {
2405
return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, true), mutex);
2406
}
2407
}
2408
2409
public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
2410
synchronized (mutex) {
2411
return new SynchronizedNavigableSet<>(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), mutex);
2412
}
2413
}
2414
2415
public NavigableSet<E> headSet(E toElement, boolean inclusive) {
2416
synchronized (mutex) {
2417
return new SynchronizedNavigableSet<>(ns.headSet(toElement, inclusive), mutex);
2418
}
2419
}
2420
2421
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
2422
synchronized (mutex) {
2423
return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, inclusive), mutex);
2424
}
2425
}
2426
}
2427
2428
/**
2429
* Returns a synchronized (thread-safe) list backed by the specified
2430
* list. In order to guarantee serial access, it is critical that
2431
* <strong>all</strong> access to the backing list is accomplished
2432
* through the returned list.<p>
2433
*
2434
* It is imperative that the user manually synchronize on the returned
2435
* list when traversing it via {@link Iterator}, {@link Spliterator}
2436
* or {@link Stream}:
2437
* <pre>
2438
* List list = Collections.synchronizedList(new ArrayList());
2439
* ...
2440
* synchronized (list) {
2441
* Iterator i = list.iterator(); // Must be in synchronized block
2442
* while (i.hasNext())
2443
* foo(i.next());
2444
* }
2445
* </pre>
2446
* Failure to follow this advice may result in non-deterministic behavior.
2447
*
2448
* <p>The returned list will be serializable if the specified list is
2449
* serializable.
2450
*
2451
* @param <T> the class of the objects in the list
2452
* @param list the list to be "wrapped" in a synchronized list.
2453
* @return a synchronized view of the specified list.
2454
*/
2455
public static <T> List<T> synchronizedList(List<T> list) {
2456
return (list instanceof RandomAccess ?
2457
new SynchronizedRandomAccessList<>(list) :
2458
new SynchronizedList<>(list));
2459
}
2460
2461
static <T> List<T> synchronizedList(List<T> list, Object mutex) {
2462
return (list instanceof RandomAccess ?
2463
new SynchronizedRandomAccessList<>(list, mutex) :
2464
new SynchronizedList<>(list, mutex));
2465
}
2466
2467
/**
2468
* @serial include
2469
*/
2470
static class SynchronizedList<E>
2471
extends SynchronizedCollection<E>
2472
implements List<E> {
2473
@java.io.Serial
2474
private static final long serialVersionUID = -7754090372962971524L;
2475
2476
@SuppressWarnings("serial") // Conditionally serializable
2477
final List<E> list;
2478
2479
SynchronizedList(List<E> list) {
2480
super(list);
2481
this.list = list;
2482
}
2483
SynchronizedList(List<E> list, Object mutex) {
2484
super(list, mutex);
2485
this.list = list;
2486
}
2487
2488
public boolean equals(Object o) {
2489
if (this == o)
2490
return true;
2491
synchronized (mutex) {return list.equals(o);}
2492
}
2493
public int hashCode() {
2494
synchronized (mutex) {return list.hashCode();}
2495
}
2496
2497
public E get(int index) {
2498
synchronized (mutex) {return list.get(index);}
2499
}
2500
public E set(int index, E element) {
2501
synchronized (mutex) {return list.set(index, element);}
2502
}
2503
public void add(int index, E element) {
2504
synchronized (mutex) {list.add(index, element);}
2505
}
2506
public E remove(int index) {
2507
synchronized (mutex) {return list.remove(index);}
2508
}
2509
2510
public int indexOf(Object o) {
2511
synchronized (mutex) {return list.indexOf(o);}
2512
}
2513
public int lastIndexOf(Object o) {
2514
synchronized (mutex) {return list.lastIndexOf(o);}
2515
}
2516
2517
public boolean addAll(int index, Collection<? extends E> c) {
2518
synchronized (mutex) {return list.addAll(index, c);}
2519
}
2520
2521
public ListIterator<E> listIterator() {
2522
return list.listIterator(); // Must be manually synched by user
2523
}
2524
2525
public ListIterator<E> listIterator(int index) {
2526
return list.listIterator(index); // Must be manually synched by user
2527
}
2528
2529
public List<E> subList(int fromIndex, int toIndex) {
2530
synchronized (mutex) {
2531
return new SynchronizedList<>(list.subList(fromIndex, toIndex),
2532
mutex);
2533
}
2534
}
2535
2536
@Override
2537
public void replaceAll(UnaryOperator<E> operator) {
2538
synchronized (mutex) {list.replaceAll(operator);}
2539
}
2540
@Override
2541
public void sort(Comparator<? super E> c) {
2542
synchronized (mutex) {list.sort(c);}
2543
}
2544
2545
/**
2546
* SynchronizedRandomAccessList instances are serialized as
2547
* SynchronizedList instances to allow them to be deserialized
2548
* in pre-1.4 JREs (which do not have SynchronizedRandomAccessList).
2549
* This method inverts the transformation. As a beneficial
2550
* side-effect, it also grafts the RandomAccess marker onto
2551
* SynchronizedList instances that were serialized in pre-1.4 JREs.
2552
*
2553
* Note: Unfortunately, SynchronizedRandomAccessList instances
2554
* serialized in 1.4.1 and deserialized in 1.4 will become
2555
* SynchronizedList instances, as this method was missing in 1.4.
2556
*/
2557
@java.io.Serial
2558
private Object readResolve() {
2559
return (list instanceof RandomAccess
2560
? new SynchronizedRandomAccessList<>(list)
2561
: this);
2562
}
2563
}
2564
2565
/**
2566
* @serial include
2567
*/
2568
static class SynchronizedRandomAccessList<E>
2569
extends SynchronizedList<E>
2570
implements RandomAccess {
2571
2572
SynchronizedRandomAccessList(List<E> list) {
2573
super(list);
2574
}
2575
2576
SynchronizedRandomAccessList(List<E> list, Object mutex) {
2577
super(list, mutex);
2578
}
2579
2580
public List<E> subList(int fromIndex, int toIndex) {
2581
synchronized (mutex) {
2582
return new SynchronizedRandomAccessList<>(
2583
list.subList(fromIndex, toIndex), mutex);
2584
}
2585
}
2586
2587
@java.io.Serial
2588
private static final long serialVersionUID = 1530674583602358482L;
2589
2590
/**
2591
* Allows instances to be deserialized in pre-1.4 JREs (which do
2592
* not have SynchronizedRandomAccessList). SynchronizedList has
2593
* a readResolve method that inverts this transformation upon
2594
* deserialization.
2595
*/
2596
@java.io.Serial
2597
private Object writeReplace() {
2598
return new SynchronizedList<>(list);
2599
}
2600
}
2601
2602
/**
2603
* Returns a synchronized (thread-safe) map backed by the specified
2604
* map. In order to guarantee serial access, it is critical that
2605
* <strong>all</strong> access to the backing map is accomplished
2606
* through the returned map.<p>
2607
*
2608
* It is imperative that the user manually synchronize on the returned
2609
* map when traversing any of its collection views via {@link Iterator},
2610
* {@link Spliterator} or {@link Stream}:
2611
* <pre>
2612
* Map m = Collections.synchronizedMap(new HashMap());
2613
* ...
2614
* Set s = m.keySet(); // Needn't be in synchronized block
2615
* ...
2616
* synchronized (m) { // Synchronizing on m, not s!
2617
* Iterator i = s.iterator(); // Must be in synchronized block
2618
* while (i.hasNext())
2619
* foo(i.next());
2620
* }
2621
* </pre>
2622
* Failure to follow this advice may result in non-deterministic behavior.
2623
*
2624
* <p>The returned map will be serializable if the specified map is
2625
* serializable.
2626
*
2627
* @param <K> the class of the map keys
2628
* @param <V> the class of the map values
2629
* @param m the map to be "wrapped" in a synchronized map.
2630
* @return a synchronized view of the specified map.
2631
*/
2632
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
2633
return new SynchronizedMap<>(m);
2634
}
2635
2636
/**
2637
* @serial include
2638
*/
2639
private static class SynchronizedMap<K,V>
2640
implements Map<K,V>, Serializable {
2641
@java.io.Serial
2642
private static final long serialVersionUID = 1978198479659022715L;
2643
2644
@SuppressWarnings("serial") // Conditionally serializable
2645
private final Map<K,V> m; // Backing Map
2646
@SuppressWarnings("serial") // Conditionally serializable
2647
final Object mutex; // Object on which to synchronize
2648
2649
SynchronizedMap(Map<K,V> m) {
2650
this.m = Objects.requireNonNull(m);
2651
mutex = this;
2652
}
2653
2654
SynchronizedMap(Map<K,V> m, Object mutex) {
2655
this.m = m;
2656
this.mutex = mutex;
2657
}
2658
2659
public int size() {
2660
synchronized (mutex) {return m.size();}
2661
}
2662
public boolean isEmpty() {
2663
synchronized (mutex) {return m.isEmpty();}
2664
}
2665
public boolean containsKey(Object key) {
2666
synchronized (mutex) {return m.containsKey(key);}
2667
}
2668
public boolean containsValue(Object value) {
2669
synchronized (mutex) {return m.containsValue(value);}
2670
}
2671
public V get(Object key) {
2672
synchronized (mutex) {return m.get(key);}
2673
}
2674
2675
public V put(K key, V value) {
2676
synchronized (mutex) {return m.put(key, value);}
2677
}
2678
public V remove(Object key) {
2679
synchronized (mutex) {return m.remove(key);}
2680
}
2681
public void putAll(Map<? extends K, ? extends V> map) {
2682
synchronized (mutex) {m.putAll(map);}
2683
}
2684
public void clear() {
2685
synchronized (mutex) {m.clear();}
2686
}
2687
2688
private transient Set<K> keySet;
2689
private transient Set<Map.Entry<K,V>> entrySet;
2690
private transient Collection<V> values;
2691
2692
public Set<K> keySet() {
2693
synchronized (mutex) {
2694
if (keySet==null)
2695
keySet = new SynchronizedSet<>(m.keySet(), mutex);
2696
return keySet;
2697
}
2698
}
2699
2700
public Set<Map.Entry<K,V>> entrySet() {
2701
synchronized (mutex) {
2702
if (entrySet==null)
2703
entrySet = new SynchronizedSet<>(m.entrySet(), mutex);
2704
return entrySet;
2705
}
2706
}
2707
2708
public Collection<V> values() {
2709
synchronized (mutex) {
2710
if (values==null)
2711
values = new SynchronizedCollection<>(m.values(), mutex);
2712
return values;
2713
}
2714
}
2715
2716
public boolean equals(Object o) {
2717
if (this == o)
2718
return true;
2719
synchronized (mutex) {return m.equals(o);}
2720
}
2721
public int hashCode() {
2722
synchronized (mutex) {return m.hashCode();}
2723
}
2724
public String toString() {
2725
synchronized (mutex) {return m.toString();}
2726
}
2727
2728
// Override default methods in Map
2729
@Override
2730
public V getOrDefault(Object k, V defaultValue) {
2731
synchronized (mutex) {return m.getOrDefault(k, defaultValue);}
2732
}
2733
@Override
2734
public void forEach(BiConsumer<? super K, ? super V> action) {
2735
synchronized (mutex) {m.forEach(action);}
2736
}
2737
@Override
2738
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
2739
synchronized (mutex) {m.replaceAll(function);}
2740
}
2741
@Override
2742
public V putIfAbsent(K key, V value) {
2743
synchronized (mutex) {return m.putIfAbsent(key, value);}
2744
}
2745
@Override
2746
public boolean remove(Object key, Object value) {
2747
synchronized (mutex) {return m.remove(key, value);}
2748
}
2749
@Override
2750
public boolean replace(K key, V oldValue, V newValue) {
2751
synchronized (mutex) {return m.replace(key, oldValue, newValue);}
2752
}
2753
@Override
2754
public V replace(K key, V value) {
2755
synchronized (mutex) {return m.replace(key, value);}
2756
}
2757
@Override
2758
public V computeIfAbsent(K key,
2759
Function<? super K, ? extends V> mappingFunction) {
2760
synchronized (mutex) {return m.computeIfAbsent(key, mappingFunction);}
2761
}
2762
@Override
2763
public V computeIfPresent(K key,
2764
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2765
synchronized (mutex) {return m.computeIfPresent(key, remappingFunction);}
2766
}
2767
@Override
2768
public V compute(K key,
2769
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2770
synchronized (mutex) {return m.compute(key, remappingFunction);}
2771
}
2772
@Override
2773
public V merge(K key, V value,
2774
BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2775
synchronized (mutex) {return m.merge(key, value, remappingFunction);}
2776
}
2777
2778
@java.io.Serial
2779
private void writeObject(ObjectOutputStream s) throws IOException {
2780
synchronized (mutex) {s.defaultWriteObject();}
2781
}
2782
}
2783
2784
/**
2785
* Returns a synchronized (thread-safe) sorted map backed by the specified
2786
* sorted map. In order to guarantee serial access, it is critical that
2787
* <strong>all</strong> access to the backing sorted map is accomplished
2788
* through the returned sorted map (or its views).<p>
2789
*
2790
* It is imperative that the user manually synchronize on the returned
2791
* sorted map when traversing any of its collection views, or the
2792
* collections views of any of its {@code subMap}, {@code headMap} or
2793
* {@code tailMap} views, via {@link Iterator}, {@link Spliterator} or
2794
* {@link Stream}:
2795
* <pre>
2796
* SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2797
* ...
2798
* Set s = m.keySet(); // Needn't be in synchronized block
2799
* ...
2800
* synchronized (m) { // Synchronizing on m, not s!
2801
* Iterator i = s.iterator(); // Must be in synchronized block
2802
* while (i.hasNext())
2803
* foo(i.next());
2804
* }
2805
* </pre>
2806
* or:
2807
* <pre>
2808
* SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2809
* SortedMap m2 = m.subMap(foo, bar);
2810
* ...
2811
* Set s2 = m2.keySet(); // Needn't be in synchronized block
2812
* ...
2813
* synchronized (m) { // Synchronizing on m, not m2 or s2!
2814
* Iterator i = s2.iterator(); // Must be in synchronized block
2815
* while (i.hasNext())
2816
* foo(i.next());
2817
* }
2818
* </pre>
2819
* Failure to follow this advice may result in non-deterministic behavior.
2820
*
2821
* <p>The returned sorted map will be serializable if the specified
2822
* sorted map is serializable.
2823
*
2824
* @param <K> the class of the map keys
2825
* @param <V> the class of the map values
2826
* @param m the sorted map to be "wrapped" in a synchronized sorted map.
2827
* @return a synchronized view of the specified sorted map.
2828
*/
2829
public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {
2830
return new SynchronizedSortedMap<>(m);
2831
}
2832
2833
/**
2834
* @serial include
2835
*/
2836
static class SynchronizedSortedMap<K,V>
2837
extends SynchronizedMap<K,V>
2838
implements SortedMap<K,V>
2839
{
2840
@java.io.Serial
2841
private static final long serialVersionUID = -8798146769416483793L;
2842
2843
@SuppressWarnings("serial") // Conditionally serializable
2844
private final SortedMap<K,V> sm;
2845
2846
SynchronizedSortedMap(SortedMap<K,V> m) {
2847
super(m);
2848
sm = m;
2849
}
2850
SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) {
2851
super(m, mutex);
2852
sm = m;
2853
}
2854
2855
public Comparator<? super K> comparator() {
2856
synchronized (mutex) {return sm.comparator();}
2857
}
2858
2859
public SortedMap<K,V> subMap(K fromKey, K toKey) {
2860
synchronized (mutex) {
2861
return new SynchronizedSortedMap<>(
2862
sm.subMap(fromKey, toKey), mutex);
2863
}
2864
}
2865
public SortedMap<K,V> headMap(K toKey) {
2866
synchronized (mutex) {
2867
return new SynchronizedSortedMap<>(sm.headMap(toKey), mutex);
2868
}
2869
}
2870
public SortedMap<K,V> tailMap(K fromKey) {
2871
synchronized (mutex) {
2872
return new SynchronizedSortedMap<>(sm.tailMap(fromKey),mutex);
2873
}
2874
}
2875
2876
public K firstKey() {
2877
synchronized (mutex) {return sm.firstKey();}
2878
}
2879
public K lastKey() {
2880
synchronized (mutex) {return sm.lastKey();}
2881
}
2882
}
2883
2884
/**
2885
* Returns a synchronized (thread-safe) navigable map backed by the
2886
* specified navigable map. In order to guarantee serial access, it is
2887
* critical that <strong>all</strong> access to the backing navigable map is
2888
* accomplished through the returned navigable map (or its views).<p>
2889
*
2890
* It is imperative that the user manually synchronize on the returned
2891
* navigable map when traversing any of its collection views, or the
2892
* collections views of any of its {@code subMap}, {@code headMap} or
2893
* {@code tailMap} views, via {@link Iterator}, {@link Spliterator} or
2894
* {@link Stream}:
2895
* <pre>
2896
* NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap());
2897
* ...
2898
* Set s = m.keySet(); // Needn't be in synchronized block
2899
* ...
2900
* synchronized (m) { // Synchronizing on m, not s!
2901
* Iterator i = s.iterator(); // Must be in synchronized block
2902
* while (i.hasNext())
2903
* foo(i.next());
2904
* }
2905
* </pre>
2906
* or:
2907
* <pre>
2908
* NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap());
2909
* NavigableMap m2 = m.subMap(foo, true, bar, false);
2910
* ...
2911
* Set s2 = m2.keySet(); // Needn't be in synchronized block
2912
* ...
2913
* synchronized (m) { // Synchronizing on m, not m2 or s2!
2914
* Iterator i = s.iterator(); // Must be in synchronized block
2915
* while (i.hasNext())
2916
* foo(i.next());
2917
* }
2918
* </pre>
2919
* Failure to follow this advice may result in non-deterministic behavior.
2920
*
2921
* <p>The returned navigable map will be serializable if the specified
2922
* navigable map is serializable.
2923
*
2924
* @param <K> the class of the map keys
2925
* @param <V> the class of the map values
2926
* @param m the navigable map to be "wrapped" in a synchronized navigable
2927
* map
2928
* @return a synchronized view of the specified navigable map.
2929
* @since 1.8
2930
*/
2931
public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m) {
2932
return new SynchronizedNavigableMap<>(m);
2933
}
2934
2935
/**
2936
* A synchronized NavigableMap.
2937
*
2938
* @serial include
2939
*/
2940
static class SynchronizedNavigableMap<K,V>
2941
extends SynchronizedSortedMap<K,V>
2942
implements NavigableMap<K,V>
2943
{
2944
@java.io.Serial
2945
private static final long serialVersionUID = 699392247599746807L;
2946
2947
@SuppressWarnings("serial") // Conditionally serializable
2948
private final NavigableMap<K,V> nm;
2949
2950
SynchronizedNavigableMap(NavigableMap<K,V> m) {
2951
super(m);
2952
nm = m;
2953
}
2954
SynchronizedNavigableMap(NavigableMap<K,V> m, Object mutex) {
2955
super(m, mutex);
2956
nm = m;
2957
}
2958
2959
public Entry<K, V> lowerEntry(K key)
2960
{ synchronized (mutex) { return nm.lowerEntry(key); } }
2961
public K lowerKey(K key)
2962
{ synchronized (mutex) { return nm.lowerKey(key); } }
2963
public Entry<K, V> floorEntry(K key)
2964
{ synchronized (mutex) { return nm.floorEntry(key); } }
2965
public K floorKey(K key)
2966
{ synchronized (mutex) { return nm.floorKey(key); } }
2967
public Entry<K, V> ceilingEntry(K key)
2968
{ synchronized (mutex) { return nm.ceilingEntry(key); } }
2969
public K ceilingKey(K key)
2970
{ synchronized (mutex) { return nm.ceilingKey(key); } }
2971
public Entry<K, V> higherEntry(K key)
2972
{ synchronized (mutex) { return nm.higherEntry(key); } }
2973
public K higherKey(K key)
2974
{ synchronized (mutex) { return nm.higherKey(key); } }
2975
public Entry<K, V> firstEntry()
2976
{ synchronized (mutex) { return nm.firstEntry(); } }
2977
public Entry<K, V> lastEntry()
2978
{ synchronized (mutex) { return nm.lastEntry(); } }
2979
public Entry<K, V> pollFirstEntry()
2980
{ synchronized (mutex) { return nm.pollFirstEntry(); } }
2981
public Entry<K, V> pollLastEntry()
2982
{ synchronized (mutex) { return nm.pollLastEntry(); } }
2983
2984
public NavigableMap<K, V> descendingMap() {
2985
synchronized (mutex) {
2986
return
2987
new SynchronizedNavigableMap<>(nm.descendingMap(), mutex);
2988
}
2989
}
2990
2991
public NavigableSet<K> keySet() {
2992
return navigableKeySet();
2993
}
2994
2995
public NavigableSet<K> navigableKeySet() {
2996
synchronized (mutex) {
2997
return new SynchronizedNavigableSet<>(nm.navigableKeySet(), mutex);
2998
}
2999
}
3000
3001
public NavigableSet<K> descendingKeySet() {
3002
synchronized (mutex) {
3003
return new SynchronizedNavigableSet<>(nm.descendingKeySet(), mutex);
3004
}
3005
}
3006
3007
3008
public SortedMap<K,V> subMap(K fromKey, K toKey) {
3009
synchronized (mutex) {
3010
return new SynchronizedNavigableMap<>(
3011
nm.subMap(fromKey, true, toKey, false), mutex);
3012
}
3013
}
3014
public SortedMap<K,V> headMap(K toKey) {
3015
synchronized (mutex) {
3016
return new SynchronizedNavigableMap<>(nm.headMap(toKey, false), mutex);
3017
}
3018
}
3019
public SortedMap<K,V> tailMap(K fromKey) {
3020
synchronized (mutex) {
3021
return new SynchronizedNavigableMap<>(nm.tailMap(fromKey, true),mutex);
3022
}
3023
}
3024
3025
public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
3026
synchronized (mutex) {
3027
return new SynchronizedNavigableMap<>(
3028
nm.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex);
3029
}
3030
}
3031
3032
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
3033
synchronized (mutex) {
3034
return new SynchronizedNavigableMap<>(
3035
nm.headMap(toKey, inclusive), mutex);
3036
}
3037
}
3038
3039
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
3040
synchronized (mutex) {
3041
return new SynchronizedNavigableMap<>(
3042
nm.tailMap(fromKey, inclusive), mutex);
3043
}
3044
}
3045
}
3046
3047
// Dynamically typesafe collection wrappers
3048
3049
/**
3050
* Returns a dynamically typesafe view of the specified collection.
3051
* Any attempt to insert an element of the wrong type will result in an
3052
* immediate {@link ClassCastException}. Assuming a collection
3053
* contains no incorrectly typed elements prior to the time a
3054
* dynamically typesafe view is generated, and that all subsequent
3055
* access to the collection takes place through the view, it is
3056
* <i>guaranteed</i> that the collection cannot contain an incorrectly
3057
* typed element.
3058
*
3059
* <p>The generics mechanism in the language provides compile-time
3060
* (static) type checking, but it is possible to defeat this mechanism
3061
* with unchecked casts. Usually this is not a problem, as the compiler
3062
* issues warnings on all such unchecked operations. There are, however,
3063
* times when static type checking alone is not sufficient. For example,
3064
* suppose a collection is passed to a third-party library and it is
3065
* imperative that the library code not corrupt the collection by
3066
* inserting an element of the wrong type.
3067
*
3068
* <p>Another use of dynamically typesafe views is debugging. Suppose a
3069
* program fails with a {@code ClassCastException}, indicating that an
3070
* incorrectly typed element was put into a parameterized collection.
3071
* Unfortunately, the exception can occur at any time after the erroneous
3072
* element is inserted, so it typically provides little or no information
3073
* as to the real source of the problem. If the problem is reproducible,
3074
* one can quickly determine its source by temporarily modifying the
3075
* program to wrap the collection with a dynamically typesafe view.
3076
* For example, this declaration:
3077
* <pre> {@code
3078
* Collection<String> c = new HashSet<>();
3079
* }</pre>
3080
* may be replaced temporarily by this one:
3081
* <pre> {@code
3082
* Collection<String> c = Collections.checkedCollection(
3083
* new HashSet<>(), String.class);
3084
* }</pre>
3085
* Running the program again will cause it to fail at the point where
3086
* an incorrectly typed element is inserted into the collection, clearly
3087
* identifying the source of the problem. Once the problem is fixed, the
3088
* modified declaration may be reverted back to the original.
3089
*
3090
* <p>The returned collection does <i>not</i> pass the hashCode and equals
3091
* operations through to the backing collection, but relies on
3092
* {@code Object}'s {@code equals} and {@code hashCode} methods. This
3093
* is necessary to preserve the contracts of these operations in the case
3094
* that the backing collection is a set or a list.
3095
*
3096
* <p>The returned collection will be serializable if the specified
3097
* collection is serializable.
3098
*
3099
* <p>Since {@code null} is considered to be a value of any reference
3100
* type, the returned collection permits insertion of null elements
3101
* whenever the backing collection does.
3102
*
3103
* @param <E> the class of the objects in the collection
3104
* @param c the collection for which a dynamically typesafe view is to be
3105
* returned
3106
* @param type the type of element that {@code c} is permitted to hold
3107
* @return a dynamically typesafe view of the specified collection
3108
* @since 1.5
3109
*/
3110
public static <E> Collection<E> checkedCollection(Collection<E> c,
3111
Class<E> type) {
3112
return new CheckedCollection<>(c, type);
3113
}
3114
3115
@SuppressWarnings("unchecked")
3116
static <T> T[] zeroLengthArray(Class<T> type) {
3117
return (T[]) Array.newInstance(type, 0);
3118
}
3119
3120
/**
3121
* @serial include
3122
*/
3123
static class CheckedCollection<E> implements Collection<E>, Serializable {
3124
@java.io.Serial
3125
private static final long serialVersionUID = 1578914078182001775L;
3126
3127
@SuppressWarnings("serial") // Conditionally serializable
3128
final Collection<E> c;
3129
@SuppressWarnings("serial") // Conditionally serializable
3130
final Class<E> type;
3131
3132
@SuppressWarnings("unchecked")
3133
E typeCheck(Object o) {
3134
if (o != null && !type.isInstance(o))
3135
throw new ClassCastException(badElementMsg(o));
3136
return (E) o;
3137
}
3138
3139
private String badElementMsg(Object o) {
3140
return "Attempt to insert " + o.getClass() +
3141
" element into collection with element type " + type;
3142
}
3143
3144
CheckedCollection(Collection<E> c, Class<E> type) {
3145
this.c = Objects.requireNonNull(c, "c");
3146
this.type = Objects.requireNonNull(type, "type");
3147
}
3148
3149
public int size() { return c.size(); }
3150
public boolean isEmpty() { return c.isEmpty(); }
3151
public boolean contains(Object o) { return c.contains(o); }
3152
public Object[] toArray() { return c.toArray(); }
3153
public <T> T[] toArray(T[] a) { return c.toArray(a); }
3154
public <T> T[] toArray(IntFunction<T[]> f) { return c.toArray(f); }
3155
public String toString() { return c.toString(); }
3156
public boolean remove(Object o) { return c.remove(o); }
3157
public void clear() { c.clear(); }
3158
3159
public boolean containsAll(Collection<?> coll) {
3160
return c.containsAll(coll);
3161
}
3162
public boolean removeAll(Collection<?> coll) {
3163
return c.removeAll(coll);
3164
}
3165
public boolean retainAll(Collection<?> coll) {
3166
return c.retainAll(coll);
3167
}
3168
3169
public Iterator<E> iterator() {
3170
// JDK-6363904 - unwrapped iterator could be typecast to
3171
// ListIterator with unsafe set()
3172
final Iterator<E> it = c.iterator();
3173
return new Iterator<E>() {
3174
public boolean hasNext() { return it.hasNext(); }
3175
public E next() { return it.next(); }
3176
public void remove() { it.remove(); }
3177
public void forEachRemaining(Consumer<? super E> action) {
3178
it.forEachRemaining(action);
3179
}
3180
};
3181
}
3182
3183
public boolean add(E e) { return c.add(typeCheck(e)); }
3184
3185
@SuppressWarnings("serial") // Conditionally serializable
3186
private E[] zeroLengthElementArray; // Lazily initialized
3187
3188
private E[] zeroLengthElementArray() {
3189
return zeroLengthElementArray != null ? zeroLengthElementArray :
3190
(zeroLengthElementArray = zeroLengthArray(type));
3191
}
3192
3193
@SuppressWarnings("unchecked")
3194
Collection<E> checkedCopyOf(Collection<? extends E> coll) {
3195
Object[] a;
3196
try {
3197
E[] z = zeroLengthElementArray();
3198
a = coll.toArray(z);
3199
// Defend against coll violating the toArray contract
3200
if (a.getClass() != z.getClass())
3201
a = Arrays.copyOf(a, a.length, z.getClass());
3202
} catch (ArrayStoreException ignore) {
3203
// To get better and consistent diagnostics,
3204
// we call typeCheck explicitly on each element.
3205
// We call clone() to defend against coll retaining a
3206
// reference to the returned array and storing a bad
3207
// element into it after it has been type checked.
3208
a = coll.toArray().clone();
3209
for (Object o : a)
3210
typeCheck(o);
3211
}
3212
// A slight abuse of the type system, but safe here.
3213
return (Collection<E>) Arrays.asList(a);
3214
}
3215
3216
public boolean addAll(Collection<? extends E> coll) {
3217
// Doing things this way insulates us from concurrent changes
3218
// in the contents of coll and provides all-or-nothing
3219
// semantics (which we wouldn't get if we type-checked each
3220
// element as we added it)
3221
return c.addAll(checkedCopyOf(coll));
3222
}
3223
3224
// Override default methods in Collection
3225
@Override
3226
public void forEach(Consumer<? super E> action) {c.forEach(action);}
3227
@Override
3228
public boolean removeIf(Predicate<? super E> filter) {
3229
return c.removeIf(filter);
3230
}
3231
@Override
3232
public Spliterator<E> spliterator() {return c.spliterator();}
3233
@Override
3234
public Stream<E> stream() {return c.stream();}
3235
@Override
3236
public Stream<E> parallelStream() {return c.parallelStream();}
3237
}
3238
3239
/**
3240
* Returns a dynamically typesafe view of the specified queue.
3241
* Any attempt to insert an element of the wrong type will result in
3242
* an immediate {@link ClassCastException}. Assuming a queue contains
3243
* no incorrectly typed elements prior to the time a dynamically typesafe
3244
* view is generated, and that all subsequent access to the queue
3245
* takes place through the view, it is <i>guaranteed</i> that the
3246
* queue cannot contain an incorrectly typed element.
3247
*
3248
* <p>A discussion of the use of dynamically typesafe views may be
3249
* found in the documentation for the {@link #checkedCollection
3250
* checkedCollection} method.
3251
*
3252
* <p>The returned queue will be serializable if the specified queue
3253
* is serializable.
3254
*
3255
* <p>Since {@code null} is considered to be a value of any reference
3256
* type, the returned queue permits insertion of {@code null} elements
3257
* whenever the backing queue does.
3258
*
3259
* @param <E> the class of the objects in the queue
3260
* @param queue the queue for which a dynamically typesafe view is to be
3261
* returned
3262
* @param type the type of element that {@code queue} is permitted to hold
3263
* @return a dynamically typesafe view of the specified queue
3264
* @since 1.8
3265
*/
3266
public static <E> Queue<E> checkedQueue(Queue<E> queue, Class<E> type) {
3267
return new CheckedQueue<>(queue, type);
3268
}
3269
3270
/**
3271
* @serial include
3272
*/
3273
static class CheckedQueue<E>
3274
extends CheckedCollection<E>
3275
implements Queue<E>, Serializable
3276
{
3277
@java.io.Serial
3278
private static final long serialVersionUID = 1433151992604707767L;
3279
@SuppressWarnings("serial") // Conditionally serializable
3280
final Queue<E> queue;
3281
3282
CheckedQueue(Queue<E> queue, Class<E> elementType) {
3283
super(queue, elementType);
3284
this.queue = queue;
3285
}
3286
3287
public E element() {return queue.element();}
3288
public boolean equals(Object o) {return o == this || c.equals(o);}
3289
public int hashCode() {return c.hashCode();}
3290
public E peek() {return queue.peek();}
3291
public E poll() {return queue.poll();}
3292
public E remove() {return queue.remove();}
3293
public boolean offer(E e) {return queue.offer(typeCheck(e));}
3294
}
3295
3296
/**
3297
* Returns a dynamically typesafe view of the specified set.
3298
* Any attempt to insert an element of the wrong type will result in
3299
* an immediate {@link ClassCastException}. Assuming a set contains
3300
* no incorrectly typed elements prior to the time a dynamically typesafe
3301
* view is generated, and that all subsequent access to the set
3302
* takes place through the view, it is <i>guaranteed</i> that the
3303
* set cannot contain an incorrectly typed element.
3304
*
3305
* <p>A discussion of the use of dynamically typesafe views may be
3306
* found in the documentation for the {@link #checkedCollection
3307
* checkedCollection} method.
3308
*
3309
* <p>The returned set will be serializable if the specified set is
3310
* serializable.
3311
*
3312
* <p>Since {@code null} is considered to be a value of any reference
3313
* type, the returned set permits insertion of null elements whenever
3314
* the backing set does.
3315
*
3316
* @param <E> the class of the objects in the set
3317
* @param s the set for which a dynamically typesafe view is to be
3318
* returned
3319
* @param type the type of element that {@code s} is permitted to hold
3320
* @return a dynamically typesafe view of the specified set
3321
* @since 1.5
3322
*/
3323
public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {
3324
return new CheckedSet<>(s, type);
3325
}
3326
3327
/**
3328
* @serial include
3329
*/
3330
static class CheckedSet<E> extends CheckedCollection<E>
3331
implements Set<E>, Serializable
3332
{
3333
@java.io.Serial
3334
private static final long serialVersionUID = 4694047833775013803L;
3335
3336
CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); }
3337
3338
public boolean equals(Object o) { return o == this || c.equals(o); }
3339
public int hashCode() { return c.hashCode(); }
3340
}
3341
3342
/**
3343
* Returns a dynamically typesafe view of the specified sorted set.
3344
* Any attempt to insert an element of the wrong type will result in an
3345
* immediate {@link ClassCastException}. Assuming a sorted set
3346
* contains no incorrectly typed elements prior to the time a
3347
* dynamically typesafe view is generated, and that all subsequent
3348
* access to the sorted set takes place through the view, it is
3349
* <i>guaranteed</i> that the sorted set cannot contain an incorrectly
3350
* typed element.
3351
*
3352
* <p>A discussion of the use of dynamically typesafe views may be
3353
* found in the documentation for the {@link #checkedCollection
3354
* checkedCollection} method.
3355
*
3356
* <p>The returned sorted set will be serializable if the specified sorted
3357
* set is serializable.
3358
*
3359
* <p>Since {@code null} is considered to be a value of any reference
3360
* type, the returned sorted set permits insertion of null elements
3361
* whenever the backing sorted set does.
3362
*
3363
* @param <E> the class of the objects in the set
3364
* @param s the sorted set for which a dynamically typesafe view is to be
3365
* returned
3366
* @param type the type of element that {@code s} is permitted to hold
3367
* @return a dynamically typesafe view of the specified sorted set
3368
* @since 1.5
3369
*/
3370
public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
3371
Class<E> type) {
3372
return new CheckedSortedSet<>(s, type);
3373
}
3374
3375
/**
3376
* @serial include
3377
*/
3378
static class CheckedSortedSet<E> extends CheckedSet<E>
3379
implements SortedSet<E>, Serializable
3380
{
3381
@java.io.Serial
3382
private static final long serialVersionUID = 1599911165492914959L;
3383
3384
@SuppressWarnings("serial") // Conditionally serializable
3385
private final SortedSet<E> ss;
3386
3387
CheckedSortedSet(SortedSet<E> s, Class<E> type) {
3388
super(s, type);
3389
ss = s;
3390
}
3391
3392
public Comparator<? super E> comparator() { return ss.comparator(); }
3393
public E first() { return ss.first(); }
3394
public E last() { return ss.last(); }
3395
3396
public SortedSet<E> subSet(E fromElement, E toElement) {
3397
return checkedSortedSet(ss.subSet(fromElement,toElement), type);
3398
}
3399
public SortedSet<E> headSet(E toElement) {
3400
return checkedSortedSet(ss.headSet(toElement), type);
3401
}
3402
public SortedSet<E> tailSet(E fromElement) {
3403
return checkedSortedSet(ss.tailSet(fromElement), type);
3404
}
3405
}
3406
3407
/**
3408
* Returns a dynamically typesafe view of the specified navigable set.
3409
* Any attempt to insert an element of the wrong type will result in an
3410
* immediate {@link ClassCastException}. Assuming a navigable set
3411
* contains no incorrectly typed elements prior to the time a
3412
* dynamically typesafe view is generated, and that all subsequent
3413
* access to the navigable set takes place through the view, it is
3414
* <em>guaranteed</em> that the navigable set cannot contain an incorrectly
3415
* typed element.
3416
*
3417
* <p>A discussion of the use of dynamically typesafe views may be
3418
* found in the documentation for the {@link #checkedCollection
3419
* checkedCollection} method.
3420
*
3421
* <p>The returned navigable set will be serializable if the specified
3422
* navigable set is serializable.
3423
*
3424
* <p>Since {@code null} is considered to be a value of any reference
3425
* type, the returned navigable set permits insertion of null elements
3426
* whenever the backing sorted set does.
3427
*
3428
* @param <E> the class of the objects in the set
3429
* @param s the navigable set for which a dynamically typesafe view is to be
3430
* returned
3431
* @param type the type of element that {@code s} is permitted to hold
3432
* @return a dynamically typesafe view of the specified navigable set
3433
* @since 1.8
3434
*/
3435
public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s,
3436
Class<E> type) {
3437
return new CheckedNavigableSet<>(s, type);
3438
}
3439
3440
/**
3441
* @serial include
3442
*/
3443
static class CheckedNavigableSet<E> extends CheckedSortedSet<E>
3444
implements NavigableSet<E>, Serializable
3445
{
3446
@java.io.Serial
3447
private static final long serialVersionUID = -5429120189805438922L;
3448
3449
@SuppressWarnings("serial") // Conditionally serializable
3450
private final NavigableSet<E> ns;
3451
3452
CheckedNavigableSet(NavigableSet<E> s, Class<E> type) {
3453
super(s, type);
3454
ns = s;
3455
}
3456
3457
public E lower(E e) { return ns.lower(e); }
3458
public E floor(E e) { return ns.floor(e); }
3459
public E ceiling(E e) { return ns.ceiling(e); }
3460
public E higher(E e) { return ns.higher(e); }
3461
public E pollFirst() { return ns.pollFirst(); }
3462
public E pollLast() {return ns.pollLast(); }
3463
public NavigableSet<E> descendingSet()
3464
{ return checkedNavigableSet(ns.descendingSet(), type); }
3465
public Iterator<E> descendingIterator()
3466
{return checkedNavigableSet(ns.descendingSet(), type).iterator(); }
3467
3468
public NavigableSet<E> subSet(E fromElement, E toElement) {
3469
return checkedNavigableSet(ns.subSet(fromElement, true, toElement, false), type);
3470
}
3471
public NavigableSet<E> headSet(E toElement) {
3472
return checkedNavigableSet(ns.headSet(toElement, false), type);
3473
}
3474
public NavigableSet<E> tailSet(E fromElement) {
3475
return checkedNavigableSet(ns.tailSet(fromElement, true), type);
3476
}
3477
3478
public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
3479
return checkedNavigableSet(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), type);
3480
}
3481
3482
public NavigableSet<E> headSet(E toElement, boolean inclusive) {
3483
return checkedNavigableSet(ns.headSet(toElement, inclusive), type);
3484
}
3485
3486
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
3487
return checkedNavigableSet(ns.tailSet(fromElement, inclusive), type);
3488
}
3489
}
3490
3491
/**
3492
* Returns a dynamically typesafe view of the specified list.
3493
* Any attempt to insert an element of the wrong type will result in
3494
* an immediate {@link ClassCastException}. Assuming a list contains
3495
* no incorrectly typed elements prior to the time a dynamically typesafe
3496
* view is generated, and that all subsequent access to the list
3497
* takes place through the view, it is <i>guaranteed</i> that the
3498
* list cannot contain an incorrectly typed element.
3499
*
3500
* <p>A discussion of the use of dynamically typesafe views may be
3501
* found in the documentation for the {@link #checkedCollection
3502
* checkedCollection} method.
3503
*
3504
* <p>The returned list will be serializable if the specified list
3505
* is serializable.
3506
*
3507
* <p>Since {@code null} is considered to be a value of any reference
3508
* type, the returned list permits insertion of null elements whenever
3509
* the backing list does.
3510
*
3511
* @param <E> the class of the objects in the list
3512
* @param list the list for which a dynamically typesafe view is to be
3513
* returned
3514
* @param type the type of element that {@code list} is permitted to hold
3515
* @return a dynamically typesafe view of the specified list
3516
* @since 1.5
3517
*/
3518
public static <E> List<E> checkedList(List<E> list, Class<E> type) {
3519
return (list instanceof RandomAccess ?
3520
new CheckedRandomAccessList<>(list, type) :
3521
new CheckedList<>(list, type));
3522
}
3523
3524
/**
3525
* @serial include
3526
*/
3527
static class CheckedList<E>
3528
extends CheckedCollection<E>
3529
implements List<E>
3530
{
3531
@java.io.Serial
3532
private static final long serialVersionUID = 65247728283967356L;
3533
@SuppressWarnings("serial") // Conditionally serializable
3534
final List<E> list;
3535
3536
CheckedList(List<E> list, Class<E> type) {
3537
super(list, type);
3538
this.list = list;
3539
}
3540
3541
public boolean equals(Object o) { return o == this || list.equals(o); }
3542
public int hashCode() { return list.hashCode(); }
3543
public E get(int index) { return list.get(index); }
3544
public E remove(int index) { return list.remove(index); }
3545
public int indexOf(Object o) { return list.indexOf(o); }
3546
public int lastIndexOf(Object o) { return list.lastIndexOf(o); }
3547
3548
public E set(int index, E element) {
3549
return list.set(index, typeCheck(element));
3550
}
3551
3552
public void add(int index, E element) {
3553
list.add(index, typeCheck(element));
3554
}
3555
3556
public boolean addAll(int index, Collection<? extends E> c) {
3557
return list.addAll(index, checkedCopyOf(c));
3558
}
3559
public ListIterator<E> listIterator() { return listIterator(0); }
3560
3561
public ListIterator<E> listIterator(final int index) {
3562
final ListIterator<E> i = list.listIterator(index);
3563
3564
return new ListIterator<E>() {
3565
public boolean hasNext() { return i.hasNext(); }
3566
public E next() { return i.next(); }
3567
public boolean hasPrevious() { return i.hasPrevious(); }
3568
public E previous() { return i.previous(); }
3569
public int nextIndex() { return i.nextIndex(); }
3570
public int previousIndex() { return i.previousIndex(); }
3571
public void remove() { i.remove(); }
3572
3573
public void set(E e) {
3574
i.set(typeCheck(e));
3575
}
3576
3577
public void add(E e) {
3578
i.add(typeCheck(e));
3579
}
3580
3581
@Override
3582
public void forEachRemaining(Consumer<? super E> action) {
3583
i.forEachRemaining(action);
3584
}
3585
};
3586
}
3587
3588
public List<E> subList(int fromIndex, int toIndex) {
3589
return new CheckedList<>(list.subList(fromIndex, toIndex), type);
3590
}
3591
3592
/**
3593
* {@inheritDoc}
3594
*
3595
* @throws ClassCastException if the class of an element returned by the
3596
* operator prevents it from being added to this collection. The
3597
* exception may be thrown after some elements of the list have
3598
* already been replaced.
3599
*/
3600
@Override
3601
public void replaceAll(UnaryOperator<E> operator) {
3602
Objects.requireNonNull(operator);
3603
list.replaceAll(e -> typeCheck(operator.apply(e)));
3604
}
3605
3606
@Override
3607
public void sort(Comparator<? super E> c) {
3608
list.sort(c);
3609
}
3610
}
3611
3612
/**
3613
* @serial include
3614
*/
3615
static class CheckedRandomAccessList<E> extends CheckedList<E>
3616
implements RandomAccess
3617
{
3618
@java.io.Serial
3619
private static final long serialVersionUID = 1638200125423088369L;
3620
3621
CheckedRandomAccessList(List<E> list, Class<E> type) {
3622
super(list, type);
3623
}
3624
3625
public List<E> subList(int fromIndex, int toIndex) {
3626
return new CheckedRandomAccessList<>(
3627
list.subList(fromIndex, toIndex), type);
3628
}
3629
}
3630
3631
/**
3632
* Returns a dynamically typesafe view of the specified map.
3633
* Any attempt to insert a mapping whose key or value have the wrong
3634
* type will result in an immediate {@link ClassCastException}.
3635
* Similarly, any attempt to modify the value currently associated with
3636
* a key will result in an immediate {@link ClassCastException},
3637
* whether the modification is attempted directly through the map
3638
* itself, or through a {@link Map.Entry} instance obtained from the
3639
* map's {@link Map#entrySet() entry set} view.
3640
*
3641
* <p>Assuming a map contains no incorrectly typed keys or values
3642
* prior to the time a dynamically typesafe view is generated, and
3643
* that all subsequent access to the map takes place through the view
3644
* (or one of its collection views), it is <i>guaranteed</i> that the
3645
* map cannot contain an incorrectly typed key or value.
3646
*
3647
* <p>A discussion of the use of dynamically typesafe views may be
3648
* found in the documentation for the {@link #checkedCollection
3649
* checkedCollection} method.
3650
*
3651
* <p>The returned map will be serializable if the specified map is
3652
* serializable.
3653
*
3654
* <p>Since {@code null} is considered to be a value of any reference
3655
* type, the returned map permits insertion of null keys or values
3656
* whenever the backing map does.
3657
*
3658
* @param <K> the class of the map keys
3659
* @param <V> the class of the map values
3660
* @param m the map for which a dynamically typesafe view is to be
3661
* returned
3662
* @param keyType the type of key that {@code m} is permitted to hold
3663
* @param valueType the type of value that {@code m} is permitted to hold
3664
* @return a dynamically typesafe view of the specified map
3665
* @since 1.5
3666
*/
3667
public static <K, V> Map<K, V> checkedMap(Map<K, V> m,
3668
Class<K> keyType,
3669
Class<V> valueType) {
3670
return new CheckedMap<>(m, keyType, valueType);
3671
}
3672
3673
3674
/**
3675
* @serial include
3676
*/
3677
private static class CheckedMap<K,V>
3678
implements Map<K,V>, Serializable
3679
{
3680
@java.io.Serial
3681
private static final long serialVersionUID = 5742860141034234728L;
3682
3683
@SuppressWarnings("serial") // Conditionally serializable
3684
private final Map<K, V> m;
3685
@SuppressWarnings("serial") // Conditionally serializable
3686
final Class<K> keyType;
3687
@SuppressWarnings("serial") // Conditionally serializable
3688
final Class<V> valueType;
3689
3690
private void typeCheck(Object key, Object value) {
3691
if (key != null && !keyType.isInstance(key))
3692
throw new ClassCastException(badKeyMsg(key));
3693
3694
if (value != null && !valueType.isInstance(value))
3695
throw new ClassCastException(badValueMsg(value));
3696
}
3697
3698
private BiFunction<? super K, ? super V, ? extends V> typeCheck(
3699
BiFunction<? super K, ? super V, ? extends V> func) {
3700
Objects.requireNonNull(func);
3701
return (k, v) -> {
3702
V newValue = func.apply(k, v);
3703
typeCheck(k, newValue);
3704
return newValue;
3705
};
3706
}
3707
3708
private String badKeyMsg(Object key) {
3709
return "Attempt to insert " + key.getClass() +
3710
" key into map with key type " + keyType;
3711
}
3712
3713
private String badValueMsg(Object value) {
3714
return "Attempt to insert " + value.getClass() +
3715
" value into map with value type " + valueType;
3716
}
3717
3718
CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) {
3719
this.m = Objects.requireNonNull(m);
3720
this.keyType = Objects.requireNonNull(keyType);
3721
this.valueType = Objects.requireNonNull(valueType);
3722
}
3723
3724
public int size() { return m.size(); }
3725
public boolean isEmpty() { return m.isEmpty(); }
3726
public boolean containsKey(Object key) { return m.containsKey(key); }
3727
public boolean containsValue(Object v) { return m.containsValue(v); }
3728
public V get(Object key) { return m.get(key); }
3729
public V remove(Object key) { return m.remove(key); }
3730
public void clear() { m.clear(); }
3731
public Set<K> keySet() { return m.keySet(); }
3732
public Collection<V> values() { return m.values(); }
3733
public boolean equals(Object o) { return o == this || m.equals(o); }
3734
public int hashCode() { return m.hashCode(); }
3735
public String toString() { return m.toString(); }
3736
3737
public V put(K key, V value) {
3738
typeCheck(key, value);
3739
return m.put(key, value);
3740
}
3741
3742
@SuppressWarnings("unchecked")
3743
public void putAll(Map<? extends K, ? extends V> t) {
3744
// Satisfy the following goals:
3745
// - good diagnostics in case of type mismatch
3746
// - all-or-nothing semantics
3747
// - protection from malicious t
3748
// - correct behavior if t is a concurrent map
3749
Object[] entries = t.entrySet().toArray();
3750
List<Map.Entry<K,V>> checked = new ArrayList<>(entries.length);
3751
for (Object o : entries) {
3752
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
3753
Object k = e.getKey();
3754
Object v = e.getValue();
3755
typeCheck(k, v);
3756
checked.add(
3757
new AbstractMap.SimpleImmutableEntry<>((K)k, (V)v));
3758
}
3759
for (Map.Entry<K,V> e : checked)
3760
m.put(e.getKey(), e.getValue());
3761
}
3762
3763
private transient Set<Map.Entry<K,V>> entrySet;
3764
3765
public Set<Map.Entry<K,V>> entrySet() {
3766
if (entrySet==null)
3767
entrySet = new CheckedEntrySet<>(m.entrySet(), valueType);
3768
return entrySet;
3769
}
3770
3771
// Override default methods in Map
3772
@Override
3773
public void forEach(BiConsumer<? super K, ? super V> action) {
3774
m.forEach(action);
3775
}
3776
3777
@Override
3778
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
3779
m.replaceAll(typeCheck(function));
3780
}
3781
3782
@Override
3783
public V putIfAbsent(K key, V value) {
3784
typeCheck(key, value);
3785
return m.putIfAbsent(key, value);
3786
}
3787
3788
@Override
3789
public boolean remove(Object key, Object value) {
3790
return m.remove(key, value);
3791
}
3792
3793
@Override
3794
public boolean replace(K key, V oldValue, V newValue) {
3795
typeCheck(key, newValue);
3796
return m.replace(key, oldValue, newValue);
3797
}
3798
3799
@Override
3800
public V replace(K key, V value) {
3801
typeCheck(key, value);
3802
return m.replace(key, value);
3803
}
3804
3805
@Override
3806
public V computeIfAbsent(K key,
3807
Function<? super K, ? extends V> mappingFunction) {
3808
Objects.requireNonNull(mappingFunction);
3809
return m.computeIfAbsent(key, k -> {
3810
V value = mappingFunction.apply(k);
3811
typeCheck(k, value);
3812
return value;
3813
});
3814
}
3815
3816
@Override
3817
public V computeIfPresent(K key,
3818
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
3819
return m.computeIfPresent(key, typeCheck(remappingFunction));
3820
}
3821
3822
@Override
3823
public V compute(K key,
3824
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
3825
return m.compute(key, typeCheck(remappingFunction));
3826
}
3827
3828
@Override
3829
public V merge(K key, V value,
3830
BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
3831
Objects.requireNonNull(remappingFunction);
3832
return m.merge(key, value, (v1, v2) -> {
3833
V newValue = remappingFunction.apply(v1, v2);
3834
typeCheck(null, newValue);
3835
return newValue;
3836
});
3837
}
3838
3839
/**
3840
* We need this class in addition to CheckedSet as Map.Entry permits
3841
* modification of the backing Map via the setValue operation. This
3842
* class is subtle: there are many possible attacks that must be
3843
* thwarted.
3844
*
3845
* @serial exclude
3846
*/
3847
static class CheckedEntrySet<K,V> implements Set<Map.Entry<K,V>> {
3848
private final Set<Map.Entry<K,V>> s;
3849
private final Class<V> valueType;
3850
3851
CheckedEntrySet(Set<Map.Entry<K, V>> s, Class<V> valueType) {
3852
this.s = s;
3853
this.valueType = valueType;
3854
}
3855
3856
public int size() { return s.size(); }
3857
public boolean isEmpty() { return s.isEmpty(); }
3858
public String toString() { return s.toString(); }
3859
public int hashCode() { return s.hashCode(); }
3860
public void clear() { s.clear(); }
3861
3862
public boolean add(Map.Entry<K, V> e) {
3863
throw new UnsupportedOperationException();
3864
}
3865
public boolean addAll(Collection<? extends Map.Entry<K, V>> coll) {
3866
throw new UnsupportedOperationException();
3867
}
3868
3869
public Iterator<Map.Entry<K,V>> iterator() {
3870
final Iterator<Map.Entry<K, V>> i = s.iterator();
3871
3872
return new Iterator<Map.Entry<K,V>>() {
3873
public boolean hasNext() { return i.hasNext(); }
3874
public void remove() { i.remove(); }
3875
3876
public Map.Entry<K,V> next() {
3877
return checkedEntry(i.next(), valueType);
3878
}
3879
3880
public void forEachRemaining(Consumer<? super Entry<K, V>> action) {
3881
i.forEachRemaining(
3882
e -> action.accept(checkedEntry(e, valueType)));
3883
}
3884
};
3885
}
3886
3887
@SuppressWarnings("unchecked")
3888
public Object[] toArray() {
3889
Object[] source = s.toArray();
3890
3891
/*
3892
* Ensure that we don't get an ArrayStoreException even if
3893
* s.toArray returns an array of something other than Object
3894
*/
3895
Object[] dest = (source.getClass() == Object[].class)
3896
? source
3897
: new Object[source.length];
3898
3899
for (int i = 0; i < source.length; i++)
3900
dest[i] = checkedEntry((Map.Entry<K,V>)source[i],
3901
valueType);
3902
return dest;
3903
}
3904
3905
@SuppressWarnings("unchecked")
3906
public <T> T[] toArray(T[] a) {
3907
// We don't pass a to s.toArray, to avoid window of
3908
// vulnerability wherein an unscrupulous multithreaded client
3909
// could get his hands on raw (unwrapped) Entries from s.
3910
T[] arr = s.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
3911
3912
for (int i=0; i<arr.length; i++)
3913
arr[i] = (T) checkedEntry((Map.Entry<K,V>)arr[i],
3914
valueType);
3915
if (arr.length > a.length)
3916
return arr;
3917
3918
System.arraycopy(arr, 0, a, 0, arr.length);
3919
if (a.length > arr.length)
3920
a[arr.length] = null;
3921
return a;
3922
}
3923
3924
/**
3925
* This method is overridden to protect the backing set against
3926
* an object with a nefarious equals function that senses
3927
* that the equality-candidate is Map.Entry and calls its
3928
* setValue method.
3929
*/
3930
public boolean contains(Object o) {
3931
return o instanceof Map.Entry<?, ?> e
3932
&& s.contains((e instanceof CheckedEntry) ? e : checkedEntry(e, valueType));
3933
}
3934
3935
/**
3936
* The bulk collection methods are overridden to protect
3937
* against an unscrupulous collection whose contains(Object o)
3938
* method senses when o is a Map.Entry, and calls o.setValue.
3939
*/
3940
public boolean containsAll(Collection<?> c) {
3941
for (Object o : c)
3942
if (!contains(o)) // Invokes safe contains() above
3943
return false;
3944
return true;
3945
}
3946
3947
public boolean remove(Object o) {
3948
if (!(o instanceof Map.Entry))
3949
return false;
3950
return s.remove(new AbstractMap.SimpleImmutableEntry
3951
<>((Map.Entry<?,?>)o));
3952
}
3953
3954
public boolean removeAll(Collection<?> c) {
3955
return batchRemove(c, false);
3956
}
3957
public boolean retainAll(Collection<?> c) {
3958
return batchRemove(c, true);
3959
}
3960
private boolean batchRemove(Collection<?> c, boolean complement) {
3961
Objects.requireNonNull(c);
3962
boolean modified = false;
3963
Iterator<Map.Entry<K,V>> it = iterator();
3964
while (it.hasNext()) {
3965
if (c.contains(it.next()) != complement) {
3966
it.remove();
3967
modified = true;
3968
}
3969
}
3970
return modified;
3971
}
3972
3973
public boolean equals(Object o) {
3974
if (o == this)
3975
return true;
3976
return o instanceof Set<?> that
3977
&& that.size() == s.size()
3978
&& containsAll(that); // Invokes safe containsAll() above
3979
}
3980
3981
static <K,V,T> CheckedEntry<K,V,T> checkedEntry(Map.Entry<K,V> e,
3982
Class<T> valueType) {
3983
return new CheckedEntry<>(e, valueType);
3984
}
3985
3986
/**
3987
* This "wrapper class" serves two purposes: it prevents
3988
* the client from modifying the backing Map, by short-circuiting
3989
* the setValue method, and it protects the backing Map against
3990
* an ill-behaved Map.Entry that attempts to modify another
3991
* Map.Entry when asked to perform an equality check.
3992
*/
3993
private static class CheckedEntry<K,V,T> implements Map.Entry<K,V> {
3994
private final Map.Entry<K, V> e;
3995
private final Class<T> valueType;
3996
3997
CheckedEntry(Map.Entry<K, V> e, Class<T> valueType) {
3998
this.e = Objects.requireNonNull(e);
3999
this.valueType = Objects.requireNonNull(valueType);
4000
}
4001
4002
public K getKey() { return e.getKey(); }
4003
public V getValue() { return e.getValue(); }
4004
public int hashCode() { return e.hashCode(); }
4005
public String toString() { return e.toString(); }
4006
4007
public V setValue(V value) {
4008
if (value != null && !valueType.isInstance(value))
4009
throw new ClassCastException(badValueMsg(value));
4010
return e.setValue(value);
4011
}
4012
4013
private String badValueMsg(Object value) {
4014
return "Attempt to insert " + value.getClass() +
4015
" value into map with value type " + valueType;
4016
}
4017
4018
public boolean equals(Object o) {
4019
if (o == this)
4020
return true;
4021
if (!(o instanceof Map.Entry))
4022
return false;
4023
return e.equals(new AbstractMap.SimpleImmutableEntry
4024
<>((Map.Entry<?,?>)o));
4025
}
4026
}
4027
}
4028
}
4029
4030
/**
4031
* Returns a dynamically typesafe view of the specified sorted map.
4032
* Any attempt to insert a mapping whose key or value have the wrong
4033
* type will result in an immediate {@link ClassCastException}.
4034
* Similarly, any attempt to modify the value currently associated with
4035
* a key will result in an immediate {@link ClassCastException},
4036
* whether the modification is attempted directly through the map
4037
* itself, or through a {@link Map.Entry} instance obtained from the
4038
* map's {@link Map#entrySet() entry set} view.
4039
*
4040
* <p>Assuming a map contains no incorrectly typed keys or values
4041
* prior to the time a dynamically typesafe view is generated, and
4042
* that all subsequent access to the map takes place through the view
4043
* (or one of its collection views), it is <i>guaranteed</i> that the
4044
* map cannot contain an incorrectly typed key or value.
4045
*
4046
* <p>A discussion of the use of dynamically typesafe views may be
4047
* found in the documentation for the {@link #checkedCollection
4048
* checkedCollection} method.
4049
*
4050
* <p>The returned map will be serializable if the specified map is
4051
* serializable.
4052
*
4053
* <p>Since {@code null} is considered to be a value of any reference
4054
* type, the returned map permits insertion of null keys or values
4055
* whenever the backing map does.
4056
*
4057
* @param <K> the class of the map keys
4058
* @param <V> the class of the map values
4059
* @param m the map for which a dynamically typesafe view is to be
4060
* returned
4061
* @param keyType the type of key that {@code m} is permitted to hold
4062
* @param valueType the type of value that {@code m} is permitted to hold
4063
* @return a dynamically typesafe view of the specified map
4064
* @since 1.5
4065
*/
4066
public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,
4067
Class<K> keyType,
4068
Class<V> valueType) {
4069
return new CheckedSortedMap<>(m, keyType, valueType);
4070
}
4071
4072
/**
4073
* @serial include
4074
*/
4075
static class CheckedSortedMap<K,V> extends CheckedMap<K,V>
4076
implements SortedMap<K,V>, Serializable
4077
{
4078
@java.io.Serial
4079
private static final long serialVersionUID = 1599671320688067438L;
4080
4081
@SuppressWarnings("serial") // Conditionally serializable
4082
private final SortedMap<K, V> sm;
4083
4084
CheckedSortedMap(SortedMap<K, V> m,
4085
Class<K> keyType, Class<V> valueType) {
4086
super(m, keyType, valueType);
4087
sm = m;
4088
}
4089
4090
public Comparator<? super K> comparator() { return sm.comparator(); }
4091
public K firstKey() { return sm.firstKey(); }
4092
public K lastKey() { return sm.lastKey(); }
4093
4094
public SortedMap<K,V> subMap(K fromKey, K toKey) {
4095
return checkedSortedMap(sm.subMap(fromKey, toKey),
4096
keyType, valueType);
4097
}
4098
public SortedMap<K,V> headMap(K toKey) {
4099
return checkedSortedMap(sm.headMap(toKey), keyType, valueType);
4100
}
4101
public SortedMap<K,V> tailMap(K fromKey) {
4102
return checkedSortedMap(sm.tailMap(fromKey), keyType, valueType);
4103
}
4104
}
4105
4106
/**
4107
* Returns a dynamically typesafe view of the specified navigable map.
4108
* Any attempt to insert a mapping whose key or value have the wrong
4109
* type will result in an immediate {@link ClassCastException}.
4110
* Similarly, any attempt to modify the value currently associated with
4111
* a key will result in an immediate {@link ClassCastException},
4112
* whether the modification is attempted directly through the map
4113
* itself, or through a {@link Map.Entry} instance obtained from the
4114
* map's {@link Map#entrySet() entry set} view.
4115
*
4116
* <p>Assuming a map contains no incorrectly typed keys or values
4117
* prior to the time a dynamically typesafe view is generated, and
4118
* that all subsequent access to the map takes place through the view
4119
* (or one of its collection views), it is <em>guaranteed</em> that the
4120
* map cannot contain an incorrectly typed key or value.
4121
*
4122
* <p>A discussion of the use of dynamically typesafe views may be
4123
* found in the documentation for the {@link #checkedCollection
4124
* checkedCollection} method.
4125
*
4126
* <p>The returned map will be serializable if the specified map is
4127
* serializable.
4128
*
4129
* <p>Since {@code null} is considered to be a value of any reference
4130
* type, the returned map permits insertion of null keys or values
4131
* whenever the backing map does.
4132
*
4133
* @param <K> type of map keys
4134
* @param <V> type of map values
4135
* @param m the map for which a dynamically typesafe view is to be
4136
* returned
4137
* @param keyType the type of key that {@code m} is permitted to hold
4138
* @param valueType the type of value that {@code m} is permitted to hold
4139
* @return a dynamically typesafe view of the specified map
4140
* @since 1.8
4141
*/
4142
public static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K, V> m,
4143
Class<K> keyType,
4144
Class<V> valueType) {
4145
return new CheckedNavigableMap<>(m, keyType, valueType);
4146
}
4147
4148
/**
4149
* @serial include
4150
*/
4151
static class CheckedNavigableMap<K,V> extends CheckedSortedMap<K,V>
4152
implements NavigableMap<K,V>, Serializable
4153
{
4154
@java.io.Serial
4155
private static final long serialVersionUID = -4852462692372534096L;
4156
4157
@SuppressWarnings("serial") // Conditionally serializable
4158
private final NavigableMap<K, V> nm;
4159
4160
CheckedNavigableMap(NavigableMap<K, V> m,
4161
Class<K> keyType, Class<V> valueType) {
4162
super(m, keyType, valueType);
4163
nm = m;
4164
}
4165
4166
public Comparator<? super K> comparator() { return nm.comparator(); }
4167
public K firstKey() { return nm.firstKey(); }
4168
public K lastKey() { return nm.lastKey(); }
4169
4170
public Entry<K, V> lowerEntry(K key) {
4171
Entry<K,V> lower = nm.lowerEntry(key);
4172
return (null != lower)
4173
? new CheckedMap.CheckedEntrySet.CheckedEntry<>(lower, valueType)
4174
: null;
4175
}
4176
4177
public K lowerKey(K key) { return nm.lowerKey(key); }
4178
4179
public Entry<K, V> floorEntry(K key) {
4180
Entry<K,V> floor = nm.floorEntry(key);
4181
return (null != floor)
4182
? new CheckedMap.CheckedEntrySet.CheckedEntry<>(floor, valueType)
4183
: null;
4184
}
4185
4186
public K floorKey(K key) { return nm.floorKey(key); }
4187
4188
public Entry<K, V> ceilingEntry(K key) {
4189
Entry<K,V> ceiling = nm.ceilingEntry(key);
4190
return (null != ceiling)
4191
? new CheckedMap.CheckedEntrySet.CheckedEntry<>(ceiling, valueType)
4192
: null;
4193
}
4194
4195
public K ceilingKey(K key) { return nm.ceilingKey(key); }
4196
4197
public Entry<K, V> higherEntry(K key) {
4198
Entry<K,V> higher = nm.higherEntry(key);
4199
return (null != higher)
4200
? new CheckedMap.CheckedEntrySet.CheckedEntry<>(higher, valueType)
4201
: null;
4202
}
4203
4204
public K higherKey(K key) { return nm.higherKey(key); }
4205
4206
public Entry<K, V> firstEntry() {
4207
Entry<K,V> first = nm.firstEntry();
4208
return (null != first)
4209
? new CheckedMap.CheckedEntrySet.CheckedEntry<>(first, valueType)
4210
: null;
4211
}
4212
4213
public Entry<K, V> lastEntry() {
4214
Entry<K,V> last = nm.lastEntry();
4215
return (null != last)
4216
? new CheckedMap.CheckedEntrySet.CheckedEntry<>(last, valueType)
4217
: null;
4218
}
4219
4220
public Entry<K, V> pollFirstEntry() {
4221
Entry<K,V> entry = nm.pollFirstEntry();
4222
return (null == entry)
4223
? null
4224
: new CheckedMap.CheckedEntrySet.CheckedEntry<>(entry, valueType);
4225
}
4226
4227
public Entry<K, V> pollLastEntry() {
4228
Entry<K,V> entry = nm.pollLastEntry();
4229
return (null == entry)
4230
? null
4231
: new CheckedMap.CheckedEntrySet.CheckedEntry<>(entry, valueType);
4232
}
4233
4234
public NavigableMap<K, V> descendingMap() {
4235
return checkedNavigableMap(nm.descendingMap(), keyType, valueType);
4236
}
4237
4238
public NavigableSet<K> keySet() {
4239
return navigableKeySet();
4240
}
4241
4242
public NavigableSet<K> navigableKeySet() {
4243
return checkedNavigableSet(nm.navigableKeySet(), keyType);
4244
}
4245
4246
public NavigableSet<K> descendingKeySet() {
4247
return checkedNavigableSet(nm.descendingKeySet(), keyType);
4248
}
4249
4250
@Override
4251
public NavigableMap<K,V> subMap(K fromKey, K toKey) {
4252
return checkedNavigableMap(nm.subMap(fromKey, true, toKey, false),
4253
keyType, valueType);
4254
}
4255
4256
@Override
4257
public NavigableMap<K,V> headMap(K toKey) {
4258
return checkedNavigableMap(nm.headMap(toKey, false), keyType, valueType);
4259
}
4260
4261
@Override
4262
public NavigableMap<K,V> tailMap(K fromKey) {
4263
return checkedNavigableMap(nm.tailMap(fromKey, true), keyType, valueType);
4264
}
4265
4266
public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
4267
return checkedNavigableMap(nm.subMap(fromKey, fromInclusive, toKey, toInclusive), keyType, valueType);
4268
}
4269
4270
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
4271
return checkedNavigableMap(nm.headMap(toKey, inclusive), keyType, valueType);
4272
}
4273
4274
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
4275
return checkedNavigableMap(nm.tailMap(fromKey, inclusive), keyType, valueType);
4276
}
4277
}
4278
4279
// Empty collections
4280
4281
/**
4282
* Returns an iterator that has no elements. More precisely,
4283
*
4284
* <ul>
4285
* <li>{@link Iterator#hasNext hasNext} always returns {@code
4286
* false}.</li>
4287
* <li>{@link Iterator#next next} always throws {@link
4288
* NoSuchElementException}.</li>
4289
* <li>{@link Iterator#remove remove} always throws {@link
4290
* IllegalStateException}.</li>
4291
* </ul>
4292
*
4293
* <p>Implementations of this method are permitted, but not
4294
* required, to return the same object from multiple invocations.
4295
*
4296
* @param <T> type of elements, if there were any, in the iterator
4297
* @return an empty iterator
4298
* @since 1.7
4299
*/
4300
@SuppressWarnings("unchecked")
4301
public static <T> Iterator<T> emptyIterator() {
4302
return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR;
4303
}
4304
4305
private static class EmptyIterator<E> implements Iterator<E> {
4306
static final EmptyIterator<Object> EMPTY_ITERATOR
4307
= new EmptyIterator<>();
4308
4309
public boolean hasNext() { return false; }
4310
public E next() { throw new NoSuchElementException(); }
4311
public void remove() { throw new IllegalStateException(); }
4312
@Override
4313
public void forEachRemaining(Consumer<? super E> action) {
4314
Objects.requireNonNull(action);
4315
}
4316
}
4317
4318
/**
4319
* Returns a list iterator that has no elements. More precisely,
4320
*
4321
* <ul>
4322
* <li>{@link Iterator#hasNext hasNext} and {@link
4323
* ListIterator#hasPrevious hasPrevious} always return {@code
4324
* false}.</li>
4325
* <li>{@link Iterator#next next} and {@link ListIterator#previous
4326
* previous} always throw {@link NoSuchElementException}.</li>
4327
* <li>{@link Iterator#remove remove} and {@link ListIterator#set
4328
* set} always throw {@link IllegalStateException}.</li>
4329
* <li>{@link ListIterator#add add} always throws {@link
4330
* UnsupportedOperationException}.</li>
4331
* <li>{@link ListIterator#nextIndex nextIndex} always returns
4332
* {@code 0}.</li>
4333
* <li>{@link ListIterator#previousIndex previousIndex} always
4334
* returns {@code -1}.</li>
4335
* </ul>
4336
*
4337
* <p>Implementations of this method are permitted, but not
4338
* required, to return the same object from multiple invocations.
4339
*
4340
* @param <T> type of elements, if there were any, in the iterator
4341
* @return an empty list iterator
4342
* @since 1.7
4343
*/
4344
@SuppressWarnings("unchecked")
4345
public static <T> ListIterator<T> emptyListIterator() {
4346
return (ListIterator<T>) EmptyListIterator.EMPTY_ITERATOR;
4347
}
4348
4349
private static class EmptyListIterator<E>
4350
extends EmptyIterator<E>
4351
implements ListIterator<E>
4352
{
4353
static final EmptyListIterator<Object> EMPTY_ITERATOR
4354
= new EmptyListIterator<>();
4355
4356
public boolean hasPrevious() { return false; }
4357
public E previous() { throw new NoSuchElementException(); }
4358
public int nextIndex() { return 0; }
4359
public int previousIndex() { return -1; }
4360
public void set(E e) { throw new IllegalStateException(); }
4361
public void add(E e) { throw new UnsupportedOperationException(); }
4362
}
4363
4364
/**
4365
* Returns an enumeration that has no elements. More precisely,
4366
*
4367
* <ul>
4368
* <li>{@link Enumeration#hasMoreElements hasMoreElements} always
4369
* returns {@code false}.</li>
4370
* <li> {@link Enumeration#nextElement nextElement} always throws
4371
* {@link NoSuchElementException}.</li>
4372
* </ul>
4373
*
4374
* <p>Implementations of this method are permitted, but not
4375
* required, to return the same object from multiple invocations.
4376
*
4377
* @param <T> the class of the objects in the enumeration
4378
* @return an empty enumeration
4379
* @since 1.7
4380
*/
4381
@SuppressWarnings("unchecked")
4382
public static <T> Enumeration<T> emptyEnumeration() {
4383
return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION;
4384
}
4385
4386
private static class EmptyEnumeration<E> implements Enumeration<E> {
4387
static final EmptyEnumeration<Object> EMPTY_ENUMERATION
4388
= new EmptyEnumeration<>();
4389
4390
public boolean hasMoreElements() { return false; }
4391
public E nextElement() { throw new NoSuchElementException(); }
4392
public Iterator<E> asIterator() { return emptyIterator(); }
4393
}
4394
4395
/**
4396
* The empty set (immutable). This set is serializable.
4397
*
4398
* @see #emptySet()
4399
*/
4400
@SuppressWarnings("rawtypes")
4401
public static final Set EMPTY_SET = new EmptySet<>();
4402
4403
/**
4404
* Returns an empty set (immutable). This set is serializable.
4405
* Unlike the like-named field, this method is parameterized.
4406
*
4407
* <p>This example illustrates the type-safe way to obtain an empty set:
4408
* <pre>
4409
* Set&lt;String&gt; s = Collections.emptySet();
4410
* </pre>
4411
* @implNote Implementations of this method need not create a separate
4412
* {@code Set} object for each call. Using this method is likely to have
4413
* comparable cost to using the like-named field. (Unlike this method, the
4414
* field does not provide type safety.)
4415
*
4416
* @param <T> the class of the objects in the set
4417
* @return the empty set
4418
*
4419
* @see #EMPTY_SET
4420
* @since 1.5
4421
*/
4422
@SuppressWarnings("unchecked")
4423
public static final <T> Set<T> emptySet() {
4424
return (Set<T>) EMPTY_SET;
4425
}
4426
4427
/**
4428
* @serial include
4429
*/
4430
private static class EmptySet<E>
4431
extends AbstractSet<E>
4432
implements Serializable
4433
{
4434
@java.io.Serial
4435
private static final long serialVersionUID = 1582296315990362920L;
4436
4437
public Iterator<E> iterator() { return emptyIterator(); }
4438
4439
public int size() {return 0;}
4440
public boolean isEmpty() {return true;}
4441
public void clear() {}
4442
4443
public boolean contains(Object obj) {return false;}
4444
public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
4445
4446
public Object[] toArray() { return new Object[0]; }
4447
4448
public <T> T[] toArray(T[] a) {
4449
if (a.length > 0)
4450
a[0] = null;
4451
return a;
4452
}
4453
4454
// Override default methods in Collection
4455
@Override
4456
public void forEach(Consumer<? super E> action) {
4457
Objects.requireNonNull(action);
4458
}
4459
@Override
4460
public boolean removeIf(Predicate<? super E> filter) {
4461
Objects.requireNonNull(filter);
4462
return false;
4463
}
4464
@Override
4465
public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
4466
4467
// Preserves singleton property
4468
@java.io.Serial
4469
private Object readResolve() {
4470
return EMPTY_SET;
4471
}
4472
4473
@Override
4474
public int hashCode() {
4475
return 0;
4476
}
4477
}
4478
4479
/**
4480
* Returns an empty sorted set (immutable). This set is serializable.
4481
*
4482
* <p>This example illustrates the type-safe way to obtain an empty
4483
* sorted set:
4484
* <pre> {@code
4485
* SortedSet<String> s = Collections.emptySortedSet();
4486
* }</pre>
4487
*
4488
* @implNote Implementations of this method need not create a separate
4489
* {@code SortedSet} object for each call.
4490
*
4491
* @param <E> type of elements, if there were any, in the set
4492
* @return the empty sorted set
4493
* @since 1.8
4494
*/
4495
@SuppressWarnings("unchecked")
4496
public static <E> SortedSet<E> emptySortedSet() {
4497
return (SortedSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET;
4498
}
4499
4500
/**
4501
* Returns an empty navigable set (immutable). This set is serializable.
4502
*
4503
* <p>This example illustrates the type-safe way to obtain an empty
4504
* navigable set:
4505
* <pre> {@code
4506
* NavigableSet<String> s = Collections.emptyNavigableSet();
4507
* }</pre>
4508
*
4509
* @implNote Implementations of this method need not
4510
* create a separate {@code NavigableSet} object for each call.
4511
*
4512
* @param <E> type of elements, if there were any, in the set
4513
* @return the empty navigable set
4514
* @since 1.8
4515
*/
4516
@SuppressWarnings("unchecked")
4517
public static <E> NavigableSet<E> emptyNavigableSet() {
4518
return (NavigableSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET;
4519
}
4520
4521
/**
4522
* The empty list (immutable). This list is serializable.
4523
*
4524
* @see #emptyList()
4525
*/
4526
@SuppressWarnings("rawtypes")
4527
public static final List EMPTY_LIST = new EmptyList<>();
4528
4529
/**
4530
* Returns an empty list (immutable). This list is serializable.
4531
*
4532
* <p>This example illustrates the type-safe way to obtain an empty list:
4533
* <pre>
4534
* List&lt;String&gt; s = Collections.emptyList();
4535
* </pre>
4536
*
4537
* @implNote
4538
* Implementations of this method need not create a separate {@code List}
4539
* object for each call. Using this method is likely to have comparable
4540
* cost to using the like-named field. (Unlike this method, the field does
4541
* not provide type safety.)
4542
*
4543
* @param <T> type of elements, if there were any, in the list
4544
* @return an empty immutable list
4545
*
4546
* @see #EMPTY_LIST
4547
* @since 1.5
4548
*/
4549
@SuppressWarnings("unchecked")
4550
public static final <T> List<T> emptyList() {
4551
return (List<T>) EMPTY_LIST;
4552
}
4553
4554
/**
4555
* @serial include
4556
*/
4557
private static class EmptyList<E>
4558
extends AbstractList<E>
4559
implements RandomAccess, Serializable {
4560
@java.io.Serial
4561
private static final long serialVersionUID = 8842843931221139166L;
4562
4563
public Iterator<E> iterator() {
4564
return emptyIterator();
4565
}
4566
public ListIterator<E> listIterator() {
4567
return emptyListIterator();
4568
}
4569
4570
public int size() {return 0;}
4571
public boolean isEmpty() {return true;}
4572
public void clear() {}
4573
4574
public boolean contains(Object obj) {return false;}
4575
public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
4576
4577
public Object[] toArray() { return new Object[0]; }
4578
4579
public <T> T[] toArray(T[] a) {
4580
if (a.length > 0)
4581
a[0] = null;
4582
return a;
4583
}
4584
4585
public E get(int index) {
4586
throw new IndexOutOfBoundsException("Index: "+index);
4587
}
4588
4589
public boolean equals(Object o) {
4590
return (o instanceof List) && ((List<?>)o).isEmpty();
4591
}
4592
4593
public int hashCode() { return 1; }
4594
4595
@Override
4596
public boolean removeIf(Predicate<? super E> filter) {
4597
Objects.requireNonNull(filter);
4598
return false;
4599
}
4600
@Override
4601
public void replaceAll(UnaryOperator<E> operator) {
4602
Objects.requireNonNull(operator);
4603
}
4604
@Override
4605
public void sort(Comparator<? super E> c) {
4606
}
4607
4608
// Override default methods in Collection
4609
@Override
4610
public void forEach(Consumer<? super E> action) {
4611
Objects.requireNonNull(action);
4612
}
4613
4614
@Override
4615
public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
4616
4617
// Preserves singleton property
4618
@java.io.Serial
4619
private Object readResolve() {
4620
return EMPTY_LIST;
4621
}
4622
}
4623
4624
/**
4625
* The empty map (immutable). This map is serializable.
4626
*
4627
* @see #emptyMap()
4628
* @since 1.3
4629
*/
4630
@SuppressWarnings("rawtypes")
4631
public static final Map EMPTY_MAP = new EmptyMap<>();
4632
4633
/**
4634
* Returns an empty map (immutable). This map is serializable.
4635
*
4636
* <p>This example illustrates the type-safe way to obtain an empty map:
4637
* <pre>
4638
* Map&lt;String, Date&gt; s = Collections.emptyMap();
4639
* </pre>
4640
* @implNote Implementations of this method need not create a separate
4641
* {@code Map} object for each call. Using this method is likely to have
4642
* comparable cost to using the like-named field. (Unlike this method, the
4643
* field does not provide type safety.)
4644
*
4645
* @param <K> the class of the map keys
4646
* @param <V> the class of the map values
4647
* @return an empty map
4648
* @see #EMPTY_MAP
4649
* @since 1.5
4650
*/
4651
@SuppressWarnings("unchecked")
4652
public static final <K,V> Map<K,V> emptyMap() {
4653
return (Map<K,V>) EMPTY_MAP;
4654
}
4655
4656
/**
4657
* Returns an empty sorted map (immutable). This map is serializable.
4658
*
4659
* <p>This example illustrates the type-safe way to obtain an empty map:
4660
* <pre> {@code
4661
* SortedMap<String, Date> s = Collections.emptySortedMap();
4662
* }</pre>
4663
*
4664
* @implNote Implementations of this method need not create a separate
4665
* {@code SortedMap} object for each call.
4666
*
4667
* @param <K> the class of the map keys
4668
* @param <V> the class of the map values
4669
* @return an empty sorted map
4670
* @since 1.8
4671
*/
4672
@SuppressWarnings("unchecked")
4673
public static final <K,V> SortedMap<K,V> emptySortedMap() {
4674
return (SortedMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP;
4675
}
4676
4677
/**
4678
* Returns an empty navigable map (immutable). This map is serializable.
4679
*
4680
* <p>This example illustrates the type-safe way to obtain an empty map:
4681
* <pre> {@code
4682
* NavigableMap<String, Date> s = Collections.emptyNavigableMap();
4683
* }</pre>
4684
*
4685
* @implNote Implementations of this method need not create a separate
4686
* {@code NavigableMap} object for each call.
4687
*
4688
* @param <K> the class of the map keys
4689
* @param <V> the class of the map values
4690
* @return an empty navigable map
4691
* @since 1.8
4692
*/
4693
@SuppressWarnings("unchecked")
4694
public static final <K,V> NavigableMap<K,V> emptyNavigableMap() {
4695
return (NavigableMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP;
4696
}
4697
4698
/**
4699
* @serial include
4700
*/
4701
private static class EmptyMap<K,V>
4702
extends AbstractMap<K,V>
4703
implements Serializable
4704
{
4705
@java.io.Serial
4706
private static final long serialVersionUID = 6428348081105594320L;
4707
4708
public int size() {return 0;}
4709
public boolean isEmpty() {return true;}
4710
public void clear() {}
4711
public boolean containsKey(Object key) {return false;}
4712
public boolean containsValue(Object value) {return false;}
4713
public V get(Object key) {return null;}
4714
public Set<K> keySet() {return emptySet();}
4715
public Collection<V> values() {return emptySet();}
4716
public Set<Map.Entry<K,V>> entrySet() {return emptySet();}
4717
4718
public boolean equals(Object o) {
4719
return (o instanceof Map) && ((Map<?,?>)o).isEmpty();
4720
}
4721
4722
public int hashCode() {return 0;}
4723
4724
// Override default methods in Map
4725
@Override
4726
@SuppressWarnings("unchecked")
4727
public V getOrDefault(Object k, V defaultValue) {
4728
return defaultValue;
4729
}
4730
4731
@Override
4732
public void forEach(BiConsumer<? super K, ? super V> action) {
4733
Objects.requireNonNull(action);
4734
}
4735
4736
@Override
4737
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
4738
Objects.requireNonNull(function);
4739
}
4740
4741
@Override
4742
public V putIfAbsent(K key, V value) {
4743
throw new UnsupportedOperationException();
4744
}
4745
4746
@Override
4747
public boolean remove(Object key, Object value) {
4748
throw new UnsupportedOperationException();
4749
}
4750
4751
@Override
4752
public boolean replace(K key, V oldValue, V newValue) {
4753
throw new UnsupportedOperationException();
4754
}
4755
4756
@Override
4757
public V replace(K key, V value) {
4758
throw new UnsupportedOperationException();
4759
}
4760
4761
@Override
4762
public V computeIfAbsent(K key,
4763
Function<? super K, ? extends V> mappingFunction) {
4764
throw new UnsupportedOperationException();
4765
}
4766
4767
@Override
4768
public V computeIfPresent(K key,
4769
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
4770
throw new UnsupportedOperationException();
4771
}
4772
4773
@Override
4774
public V compute(K key,
4775
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
4776
throw new UnsupportedOperationException();
4777
}
4778
4779
@Override
4780
public V merge(K key, V value,
4781
BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
4782
throw new UnsupportedOperationException();
4783
}
4784
4785
// Preserves singleton property
4786
@java.io.Serial
4787
private Object readResolve() {
4788
return EMPTY_MAP;
4789
}
4790
}
4791
4792
// Singleton collections
4793
4794
/**
4795
* Returns an immutable set containing only the specified object.
4796
* The returned set is serializable.
4797
*
4798
* @param <T> the class of the objects in the set
4799
* @param o the sole object to be stored in the returned set.
4800
* @return an immutable set containing only the specified object.
4801
*/
4802
public static <T> Set<T> singleton(T o) {
4803
return new SingletonSet<>(o);
4804
}
4805
4806
static <E> Iterator<E> singletonIterator(final E e) {
4807
return new Iterator<E>() {
4808
private boolean hasNext = true;
4809
public boolean hasNext() {
4810
return hasNext;
4811
}
4812
public E next() {
4813
if (hasNext) {
4814
hasNext = false;
4815
return e;
4816
}
4817
throw new NoSuchElementException();
4818
}
4819
public void remove() {
4820
throw new UnsupportedOperationException();
4821
}
4822
@Override
4823
public void forEachRemaining(Consumer<? super E> action) {
4824
Objects.requireNonNull(action);
4825
if (hasNext) {
4826
hasNext = false;
4827
action.accept(e);
4828
}
4829
}
4830
};
4831
}
4832
4833
/**
4834
* Creates a {@code Spliterator} with only the specified element
4835
*
4836
* @param <T> Type of elements
4837
* @return A singleton {@code Spliterator}
4838
*/
4839
static <T> Spliterator<T> singletonSpliterator(final T element) {
4840
return new Spliterator<T>() {
4841
long est = 1;
4842
4843
@Override
4844
public Spliterator<T> trySplit() {
4845
return null;
4846
}
4847
4848
@Override
4849
public boolean tryAdvance(Consumer<? super T> consumer) {
4850
Objects.requireNonNull(consumer);
4851
if (est > 0) {
4852
est--;
4853
consumer.accept(element);
4854
return true;
4855
}
4856
return false;
4857
}
4858
4859
@Override
4860
public void forEachRemaining(Consumer<? super T> consumer) {
4861
tryAdvance(consumer);
4862
}
4863
4864
@Override
4865
public long estimateSize() {
4866
return est;
4867
}
4868
4869
@Override
4870
public int characteristics() {
4871
int value = (element != null) ? Spliterator.NONNULL : 0;
4872
4873
return value | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.IMMUTABLE |
4874
Spliterator.DISTINCT | Spliterator.ORDERED;
4875
}
4876
};
4877
}
4878
4879
/**
4880
* @serial include
4881
*/
4882
private static class SingletonSet<E>
4883
extends AbstractSet<E>
4884
implements Serializable
4885
{
4886
@java.io.Serial
4887
private static final long serialVersionUID = 3193687207550431679L;
4888
4889
@SuppressWarnings("serial") // Conditionally serializable
4890
private final E element;
4891
4892
SingletonSet(E e) {element = e;}
4893
4894
public Iterator<E> iterator() {
4895
return singletonIterator(element);
4896
}
4897
4898
public int size() {return 1;}
4899
4900
public boolean contains(Object o) {return eq(o, element);}
4901
4902
// Override default methods for Collection
4903
@Override
4904
public void forEach(Consumer<? super E> action) {
4905
action.accept(element);
4906
}
4907
@Override
4908
public Spliterator<E> spliterator() {
4909
return singletonSpliterator(element);
4910
}
4911
@Override
4912
public boolean removeIf(Predicate<? super E> filter) {
4913
throw new UnsupportedOperationException();
4914
}
4915
@Override
4916
public int hashCode() {
4917
return Objects.hashCode(element);
4918
}
4919
}
4920
4921
/**
4922
* Returns an immutable list containing only the specified object.
4923
* The returned list is serializable.
4924
*
4925
* @param <T> the class of the objects in the list
4926
* @param o the sole object to be stored in the returned list.
4927
* @return an immutable list containing only the specified object.
4928
* @since 1.3
4929
*/
4930
public static <T> List<T> singletonList(T o) {
4931
return new SingletonList<>(o);
4932
}
4933
4934
/**
4935
* @serial include
4936
*/
4937
private static class SingletonList<E>
4938
extends AbstractList<E>
4939
implements RandomAccess, Serializable {
4940
4941
@java.io.Serial
4942
private static final long serialVersionUID = 3093736618740652951L;
4943
4944
@SuppressWarnings("serial") // Conditionally serializable
4945
private final E element;
4946
4947
SingletonList(E obj) {element = obj;}
4948
4949
public Iterator<E> iterator() {
4950
return singletonIterator(element);
4951
}
4952
4953
public int size() {return 1;}
4954
4955
public boolean contains(Object obj) {return eq(obj, element);}
4956
4957
public E get(int index) {
4958
if (index != 0)
4959
throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");
4960
return element;
4961
}
4962
4963
// Override default methods for Collection
4964
@Override
4965
public void forEach(Consumer<? super E> action) {
4966
action.accept(element);
4967
}
4968
@Override
4969
public boolean removeIf(Predicate<? super E> filter) {
4970
throw new UnsupportedOperationException();
4971
}
4972
@Override
4973
public void replaceAll(UnaryOperator<E> operator) {
4974
throw new UnsupportedOperationException();
4975
}
4976
@Override
4977
public void sort(Comparator<? super E> c) {
4978
}
4979
@Override
4980
public Spliterator<E> spliterator() {
4981
return singletonSpliterator(element);
4982
}
4983
@Override
4984
public int hashCode() {
4985
return 31 + Objects.hashCode(element);
4986
}
4987
}
4988
4989
/**
4990
* Returns an immutable map, mapping only the specified key to the
4991
* specified value. The returned map is serializable.
4992
*
4993
* @param <K> the class of the map keys
4994
* @param <V> the class of the map values
4995
* @param key the sole key to be stored in the returned map.
4996
* @param value the value to which the returned map maps {@code key}.
4997
* @return an immutable map containing only the specified key-value
4998
* mapping.
4999
* @since 1.3
5000
*/
5001
public static <K,V> Map<K,V> singletonMap(K key, V value) {
5002
return new SingletonMap<>(key, value);
5003
}
5004
5005
/**
5006
* @serial include
5007
*/
5008
private static class SingletonMap<K,V>
5009
extends AbstractMap<K,V>
5010
implements Serializable {
5011
@java.io.Serial
5012
private static final long serialVersionUID = -6979724477215052911L;
5013
5014
@SuppressWarnings("serial") // Conditionally serializable
5015
private final K k;
5016
@SuppressWarnings("serial") // Conditionally serializable
5017
private final V v;
5018
5019
SingletonMap(K key, V value) {
5020
k = key;
5021
v = value;
5022
}
5023
5024
public int size() {return 1;}
5025
public boolean isEmpty() {return false;}
5026
public boolean containsKey(Object key) {return eq(key, k);}
5027
public boolean containsValue(Object value) {return eq(value, v);}
5028
public V get(Object key) {return (eq(key, k) ? v : null);}
5029
5030
private transient Set<K> keySet;
5031
private transient Set<Map.Entry<K,V>> entrySet;
5032
private transient Collection<V> values;
5033
5034
public Set<K> keySet() {
5035
if (keySet==null)
5036
keySet = singleton(k);
5037
return keySet;
5038
}
5039
5040
public Set<Map.Entry<K,V>> entrySet() {
5041
if (entrySet==null)
5042
entrySet = Collections.<Map.Entry<K,V>>singleton(
5043
new SimpleImmutableEntry<>(k, v));
5044
return entrySet;
5045
}
5046
5047
public Collection<V> values() {
5048
if (values==null)
5049
values = singleton(v);
5050
return values;
5051
}
5052
5053
// Override default methods in Map
5054
@Override
5055
public V getOrDefault(Object key, V defaultValue) {
5056
return eq(key, k) ? v : defaultValue;
5057
}
5058
5059
@Override
5060
public void forEach(BiConsumer<? super K, ? super V> action) {
5061
action.accept(k, v);
5062
}
5063
5064
@Override
5065
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
5066
throw new UnsupportedOperationException();
5067
}
5068
5069
@Override
5070
public V putIfAbsent(K key, V value) {
5071
throw new UnsupportedOperationException();
5072
}
5073
5074
@Override
5075
public boolean remove(Object key, Object value) {
5076
throw new UnsupportedOperationException();
5077
}
5078
5079
@Override
5080
public boolean replace(K key, V oldValue, V newValue) {
5081
throw new UnsupportedOperationException();
5082
}
5083
5084
@Override
5085
public V replace(K key, V value) {
5086
throw new UnsupportedOperationException();
5087
}
5088
5089
@Override
5090
public V computeIfAbsent(K key,
5091
Function<? super K, ? extends V> mappingFunction) {
5092
throw new UnsupportedOperationException();
5093
}
5094
5095
@Override
5096
public V computeIfPresent(K key,
5097
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
5098
throw new UnsupportedOperationException();
5099
}
5100
5101
@Override
5102
public V compute(K key,
5103
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
5104
throw new UnsupportedOperationException();
5105
}
5106
5107
@Override
5108
public V merge(K key, V value,
5109
BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
5110
throw new UnsupportedOperationException();
5111
}
5112
5113
@Override
5114
public int hashCode() {
5115
return Objects.hashCode(k) ^ Objects.hashCode(v);
5116
}
5117
}
5118
5119
// Miscellaneous
5120
5121
/**
5122
* Returns an immutable list consisting of {@code n} copies of the
5123
* specified object. The newly allocated data object is tiny (it contains
5124
* a single reference to the data object). This method is useful in
5125
* combination with the {@code List.addAll} method to grow lists.
5126
* The returned list is serializable.
5127
*
5128
* @param <T> the class of the object to copy and of the objects
5129
* in the returned list.
5130
* @param n the number of elements in the returned list.
5131
* @param o the element to appear repeatedly in the returned list.
5132
* @return an immutable list consisting of {@code n} copies of the
5133
* specified object.
5134
* @throws IllegalArgumentException if {@code n < 0}
5135
* @see List#addAll(Collection)
5136
* @see List#addAll(int, Collection)
5137
*/
5138
public static <T> List<T> nCopies(int n, T o) {
5139
if (n < 0)
5140
throw new IllegalArgumentException("List length = " + n);
5141
return new CopiesList<>(n, o);
5142
}
5143
5144
/**
5145
* @serial include
5146
*/
5147
private static class CopiesList<E>
5148
extends AbstractList<E>
5149
implements RandomAccess, Serializable
5150
{
5151
@java.io.Serial
5152
private static final long serialVersionUID = 2739099268398711800L;
5153
5154
final int n;
5155
@SuppressWarnings("serial") // Conditionally serializable
5156
final E element;
5157
5158
CopiesList(int n, E e) {
5159
assert n >= 0;
5160
this.n = n;
5161
element = e;
5162
}
5163
5164
public int size() {
5165
return n;
5166
}
5167
5168
public boolean contains(Object obj) {
5169
return n != 0 && eq(obj, element);
5170
}
5171
5172
public int indexOf(Object o) {
5173
return contains(o) ? 0 : -1;
5174
}
5175
5176
public int lastIndexOf(Object o) {
5177
return contains(o) ? n - 1 : -1;
5178
}
5179
5180
public E get(int index) {
5181
if (index < 0 || index >= n)
5182
throw new IndexOutOfBoundsException("Index: "+index+
5183
", Size: "+n);
5184
return element;
5185
}
5186
5187
public Object[] toArray() {
5188
final Object[] a = new Object[n];
5189
if (element != null)
5190
Arrays.fill(a, 0, n, element);
5191
return a;
5192
}
5193
5194
@SuppressWarnings("unchecked")
5195
public <T> T[] toArray(T[] a) {
5196
final int n = this.n;
5197
if (a.length < n) {
5198
a = (T[])java.lang.reflect.Array
5199
.newInstance(a.getClass().getComponentType(), n);
5200
if (element != null)
5201
Arrays.fill(a, 0, n, element);
5202
} else {
5203
Arrays.fill(a, 0, n, element);
5204
if (a.length > n)
5205
a[n] = null;
5206
}
5207
return a;
5208
}
5209
5210
public List<E> subList(int fromIndex, int toIndex) {
5211
if (fromIndex < 0)
5212
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
5213
if (toIndex > n)
5214
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
5215
if (fromIndex > toIndex)
5216
throw new IllegalArgumentException("fromIndex(" + fromIndex +
5217
") > toIndex(" + toIndex + ")");
5218
return new CopiesList<>(toIndex - fromIndex, element);
5219
}
5220
5221
@Override
5222
public int hashCode() {
5223
if (n == 0) return 1;
5224
// hashCode of n repeating elements is 31^n + elementHash * Sum(31^k, k = 0..n-1)
5225
// this implementation completes in O(log(n)) steps taking advantage of
5226
// 31^(2*n) = (31^n)^2 and Sum(31^k, k = 0..(2*n-1)) = Sum(31^k, k = 0..n-1) * (31^n + 1)
5227
int pow = 31;
5228
int sum = 1;
5229
for (int i = Integer.numberOfLeadingZeros(n) + 1; i < Integer.SIZE; i++) {
5230
sum *= pow + 1;
5231
pow *= pow;
5232
if ((n << i) < 0) {
5233
pow *= 31;
5234
sum = sum * 31 + 1;
5235
}
5236
}
5237
return pow + sum * (element == null ? 0 : element.hashCode());
5238
}
5239
5240
@Override
5241
public boolean equals(Object o) {
5242
if (o == this)
5243
return true;
5244
if (o instanceof CopiesList<?> other) {
5245
return n == other.n && (n == 0 || eq(element, other.element));
5246
}
5247
if (!(o instanceof List))
5248
return false;
5249
5250
int remaining = n;
5251
E e = element;
5252
Iterator<?> itr = ((List<?>) o).iterator();
5253
if (e == null) {
5254
while (itr.hasNext() && remaining-- > 0) {
5255
if (itr.next() != null)
5256
return false;
5257
}
5258
} else {
5259
while (itr.hasNext() && remaining-- > 0) {
5260
if (!e.equals(itr.next()))
5261
return false;
5262
}
5263
}
5264
return remaining == 0 && !itr.hasNext();
5265
}
5266
5267
// Override default methods in Collection
5268
@Override
5269
public Stream<E> stream() {
5270
return IntStream.range(0, n).mapToObj(i -> element);
5271
}
5272
5273
@Override
5274
public Stream<E> parallelStream() {
5275
return IntStream.range(0, n).parallel().mapToObj(i -> element);
5276
}
5277
5278
@Override
5279
public Spliterator<E> spliterator() {
5280
return stream().spliterator();
5281
}
5282
5283
@java.io.Serial
5284
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
5285
ois.defaultReadObject();
5286
SharedSecrets.getJavaObjectInputStreamAccess().checkArray(ois, Object[].class, n);
5287
}
5288
}
5289
5290
/**
5291
* Returns a comparator that imposes the reverse of the <em>natural
5292
* ordering</em> on a collection of objects that implement the
5293
* {@code Comparable} interface. (The natural ordering is the ordering
5294
* imposed by the objects' own {@code compareTo} method.) This enables a
5295
* simple idiom for sorting (or maintaining) collections (or arrays) of
5296
* objects that implement the {@code Comparable} interface in
5297
* reverse-natural-order. For example, suppose {@code a} is an array of
5298
* strings. Then: <pre>
5299
* Arrays.sort(a, Collections.reverseOrder());
5300
* </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>
5301
*
5302
* The returned comparator is serializable.
5303
*
5304
* @param <T> the class of the objects compared by the comparator
5305
* @return A comparator that imposes the reverse of the <i>natural
5306
* ordering</i> on a collection of objects that implement
5307
* the {@code Comparable} interface.
5308
* @see Comparable
5309
*/
5310
@SuppressWarnings("unchecked")
5311
public static <T> Comparator<T> reverseOrder() {
5312
return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
5313
}
5314
5315
/**
5316
* @serial include
5317
*/
5318
private static class ReverseComparator
5319
implements Comparator<Comparable<Object>>, Serializable {
5320
5321
@java.io.Serial
5322
private static final long serialVersionUID = 7207038068494060240L;
5323
5324
static final ReverseComparator REVERSE_ORDER
5325
= new ReverseComparator();
5326
5327
public int compare(Comparable<Object> c1, Comparable<Object> c2) {
5328
return c2.compareTo(c1);
5329
}
5330
5331
@java.io.Serial
5332
private Object readResolve() { return Collections.reverseOrder(); }
5333
5334
@Override
5335
public Comparator<Comparable<Object>> reversed() {
5336
return Comparator.naturalOrder();
5337
}
5338
}
5339
5340
/**
5341
* Returns a comparator that imposes the reverse ordering of the specified
5342
* comparator. If the specified comparator is {@code null}, this method is
5343
* equivalent to {@link #reverseOrder()} (in other words, it returns a
5344
* comparator that imposes the reverse of the <em>natural ordering</em> on
5345
* a collection of objects that implement the Comparable interface).
5346
*
5347
* <p>The returned comparator is serializable (assuming the specified
5348
* comparator is also serializable or {@code null}).
5349
*
5350
* @param <T> the class of the objects compared by the comparator
5351
* @param cmp a comparator who's ordering is to be reversed by the returned
5352
* comparator or {@code null}
5353
* @return A comparator that imposes the reverse ordering of the
5354
* specified comparator.
5355
* @since 1.5
5356
*/
5357
@SuppressWarnings("unchecked")
5358
public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) {
5359
if (cmp == null) {
5360
return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
5361
} else if (cmp == ReverseComparator.REVERSE_ORDER) {
5362
return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE;
5363
} else if (cmp == Comparators.NaturalOrderComparator.INSTANCE) {
5364
return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
5365
} else if (cmp instanceof ReverseComparator2) {
5366
return ((ReverseComparator2<T>) cmp).cmp;
5367
} else {
5368
return new ReverseComparator2<>(cmp);
5369
}
5370
}
5371
5372
/**
5373
* @serial include
5374
*/
5375
private static class ReverseComparator2<T> implements Comparator<T>,
5376
Serializable
5377
{
5378
@java.io.Serial
5379
private static final long serialVersionUID = 4374092139857L;
5380
5381
/**
5382
* The comparator specified in the static factory. This will never
5383
* be null, as the static factory returns a ReverseComparator
5384
* instance if its argument is null.
5385
*
5386
* @serial
5387
*/
5388
@SuppressWarnings("serial") // Conditionally serializable
5389
final Comparator<T> cmp;
5390
5391
ReverseComparator2(Comparator<T> cmp) {
5392
assert cmp != null;
5393
this.cmp = cmp;
5394
}
5395
5396
public int compare(T t1, T t2) {
5397
return cmp.compare(t2, t1);
5398
}
5399
5400
public boolean equals(Object o) {
5401
return (o == this) ||
5402
(o instanceof ReverseComparator2 &&
5403
cmp.equals(((ReverseComparator2)o).cmp));
5404
}
5405
5406
public int hashCode() {
5407
return cmp.hashCode() ^ Integer.MIN_VALUE;
5408
}
5409
5410
@Override
5411
public Comparator<T> reversed() {
5412
return cmp;
5413
}
5414
}
5415
5416
/**
5417
* Returns an enumeration over the specified collection. This provides
5418
* interoperability with legacy APIs that require an enumeration
5419
* as input.
5420
*
5421
* <p>The iterator returned from a call to {@link Enumeration#asIterator()}
5422
* does not support removal of elements from the specified collection. This
5423
* is necessary to avoid unintentionally increasing the capabilities of the
5424
* returned enumeration.
5425
*
5426
* @param <T> the class of the objects in the collection
5427
* @param c the collection for which an enumeration is to be returned.
5428
* @return an enumeration over the specified collection.
5429
* @see Enumeration
5430
*/
5431
public static <T> Enumeration<T> enumeration(final Collection<T> c) {
5432
return new Enumeration<T>() {
5433
private final Iterator<T> i = c.iterator();
5434
5435
public boolean hasMoreElements() {
5436
return i.hasNext();
5437
}
5438
5439
public T nextElement() {
5440
return i.next();
5441
}
5442
};
5443
}
5444
5445
/**
5446
* Returns an array list containing the elements returned by the
5447
* specified enumeration in the order they are returned by the
5448
* enumeration. This method provides interoperability between
5449
* legacy APIs that return enumerations and new APIs that require
5450
* collections.
5451
*
5452
* @param <T> the class of the objects returned by the enumeration
5453
* @param e enumeration providing elements for the returned
5454
* array list
5455
* @return an array list containing the elements returned
5456
* by the specified enumeration.
5457
* @since 1.4
5458
* @see Enumeration
5459
* @see ArrayList
5460
*/
5461
public static <T> ArrayList<T> list(Enumeration<T> e) {
5462
ArrayList<T> l = new ArrayList<>();
5463
while (e.hasMoreElements())
5464
l.add(e.nextElement());
5465
return l;
5466
}
5467
5468
/**
5469
* Returns true if the specified arguments are equal, or both null.
5470
*
5471
* NB: Do not replace with Object.equals until JDK-8015417 is resolved.
5472
*/
5473
static boolean eq(Object o1, Object o2) {
5474
return o1==null ? o2==null : o1.equals(o2);
5475
}
5476
5477
/**
5478
* Returns the number of elements in the specified collection equal to the
5479
* specified object. More formally, returns the number of elements
5480
* {@code e} in the collection such that
5481
* {@code Objects.equals(o, e)}.
5482
*
5483
* @param c the collection in which to determine the frequency
5484
* of {@code o}
5485
* @param o the object whose frequency is to be determined
5486
* @return the number of elements in {@code c} equal to {@code o}
5487
* @throws NullPointerException if {@code c} is null
5488
* @since 1.5
5489
*/
5490
public static int frequency(Collection<?> c, Object o) {
5491
int result = 0;
5492
if (o == null) {
5493
for (Object e : c)
5494
if (e == null)
5495
result++;
5496
} else {
5497
for (Object e : c)
5498
if (o.equals(e))
5499
result++;
5500
}
5501
return result;
5502
}
5503
5504
/**
5505
* Returns {@code true} if the two specified collections have no
5506
* elements in common.
5507
*
5508
* <p>Care must be exercised if this method is used on collections that
5509
* do not comply with the general contract for {@code Collection}.
5510
* Implementations may elect to iterate over either collection and test
5511
* for containment in the other collection (or to perform any equivalent
5512
* computation). If either collection uses a nonstandard equality test
5513
* (as does a {@link SortedSet} whose ordering is not <em>compatible with
5514
* equals</em>, or the key set of an {@link IdentityHashMap}), both
5515
* collections must use the same nonstandard equality test, or the
5516
* result of this method is undefined.
5517
*
5518
* <p>Care must also be exercised when using collections that have
5519
* restrictions on the elements that they may contain. Collection
5520
* implementations are allowed to throw exceptions for any operation
5521
* involving elements they deem ineligible. For absolute safety the
5522
* specified collections should contain only elements which are
5523
* eligible elements for both collections.
5524
*
5525
* <p>Note that it is permissible to pass the same collection in both
5526
* parameters, in which case the method will return {@code true} if and
5527
* only if the collection is empty.
5528
*
5529
* @param c1 a collection
5530
* @param c2 a collection
5531
* @return {@code true} if the two specified collections have no
5532
* elements in common.
5533
* @throws NullPointerException if either collection is {@code null}.
5534
* @throws NullPointerException if one collection contains a {@code null}
5535
* element and {@code null} is not an eligible element for the other collection.
5536
* (<a href="Collection.html#optional-restrictions">optional</a>)
5537
* @throws ClassCastException if one collection contains an element that is
5538
* of a type which is ineligible for the other collection.
5539
* (<a href="Collection.html#optional-restrictions">optional</a>)
5540
* @since 1.5
5541
*/
5542
public static boolean disjoint(Collection<?> c1, Collection<?> c2) {
5543
// The collection to be used for contains(). Preference is given to
5544
// the collection who's contains() has lower O() complexity.
5545
Collection<?> contains = c2;
5546
// The collection to be iterated. If the collections' contains() impl
5547
// are of different O() complexity, the collection with slower
5548
// contains() will be used for iteration. For collections who's
5549
// contains() are of the same complexity then best performance is
5550
// achieved by iterating the smaller collection.
5551
Collection<?> iterate = c1;
5552
5553
// Performance optimization cases. The heuristics:
5554
// 1. Generally iterate over c1.
5555
// 2. If c1 is a Set then iterate over c2.
5556
// 3. If either collection is empty then result is always true.
5557
// 4. Iterate over the smaller Collection.
5558
if (c1 instanceof Set) {
5559
// Use c1 for contains as a Set's contains() is expected to perform
5560
// better than O(N/2)
5561
iterate = c2;
5562
contains = c1;
5563
} else if (!(c2 instanceof Set)) {
5564
// Both are mere Collections. Iterate over smaller collection.
5565
// Example: If c1 contains 3 elements and c2 contains 50 elements and
5566
// assuming contains() requires ceiling(N/2) comparisons then
5567
// checking for all c1 elements in c2 would require 75 comparisons
5568
// (3 * ceiling(50/2)) vs. checking all c2 elements in c1 requiring
5569
// 100 comparisons (50 * ceiling(3/2)).
5570
int c1size = c1.size();
5571
int c2size = c2.size();
5572
if (c1size == 0 || c2size == 0) {
5573
// At least one collection is empty. Nothing will match.
5574
return true;
5575
}
5576
5577
if (c1size > c2size) {
5578
iterate = c2;
5579
contains = c1;
5580
}
5581
}
5582
5583
for (Object e : iterate) {
5584
if (contains.contains(e)) {
5585
// Found a common element. Collections are not disjoint.
5586
return false;
5587
}
5588
}
5589
5590
// No common elements were found.
5591
return true;
5592
}
5593
5594
/**
5595
* Adds all of the specified elements to the specified collection.
5596
* Elements to be added may be specified individually or as an array.
5597
* The behaviour of this convenience method is similar to that of
5598
* {@code cc.addAll(Collections.unmodifiableList(Arrays.asList(elements)))}.
5599
*
5600
* <p>When elements are specified individually, this method provides a
5601
* convenient way to add a few elements to an existing collection:
5602
* <pre>
5603
* Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");
5604
* </pre>
5605
*
5606
* @param <T> the class of the elements to add and of the collection
5607
* @param c the collection into which {@code elements} are to be inserted
5608
* @param elements the elements to insert into {@code c}
5609
* @return {@code true} if the collection changed as a result of the call
5610
* @throws UnsupportedOperationException if {@code c} does not support
5611
* the {@code add} operation
5612
* @throws NullPointerException if {@code elements} contains one or more
5613
* null values and {@code c} does not permit null elements, or
5614
* if {@code c} or {@code elements} are {@code null}
5615
* @throws IllegalArgumentException if some property of a value in
5616
* {@code elements} prevents it from being added to {@code c}
5617
* @see Collection#addAll(Collection)
5618
* @since 1.5
5619
*/
5620
@SafeVarargs
5621
public static <T> boolean addAll(Collection<? super T> c, T... elements) {
5622
boolean result = false;
5623
for (T element : elements)
5624
result |= c.add(element);
5625
return result;
5626
}
5627
5628
/**
5629
* Returns a set backed by the specified map. The resulting set displays
5630
* the same ordering, concurrency, and performance characteristics as the
5631
* backing map. In essence, this factory method provides a {@link Set}
5632
* implementation corresponding to any {@link Map} implementation. There
5633
* is no need to use this method on a {@link Map} implementation that
5634
* already has a corresponding {@link Set} implementation (such as {@link
5635
* HashMap} or {@link TreeMap}).
5636
*
5637
* <p>Each method invocation on the set returned by this method results in
5638
* exactly one method invocation on the backing map or its {@code keySet}
5639
* view, with one exception. The {@code addAll} method is implemented
5640
* as a sequence of {@code put} invocations on the backing map.
5641
*
5642
* <p>The specified map must be empty at the time this method is invoked,
5643
* and should not be accessed directly after this method returns. These
5644
* conditions are ensured if the map is created empty, passed directly
5645
* to this method, and no reference to the map is retained, as illustrated
5646
* in the following code fragment:
5647
* <pre>
5648
* Set&lt;Object&gt; weakHashSet = Collections.newSetFromMap(
5649
* new WeakHashMap&lt;Object, Boolean&gt;());
5650
* </pre>
5651
*
5652
* @param <E> the class of the map keys and of the objects in the
5653
* returned set
5654
* @param map the backing map
5655
* @return the set backed by the map
5656
* @throws IllegalArgumentException if {@code map} is not empty
5657
* @since 1.6
5658
*/
5659
public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
5660
return new SetFromMap<>(map);
5661
}
5662
5663
/**
5664
* @serial include
5665
*/
5666
private static class SetFromMap<E> extends AbstractSet<E>
5667
implements Set<E>, Serializable
5668
{
5669
@SuppressWarnings("serial") // Conditionally serializable
5670
private final Map<E, Boolean> m; // The backing map
5671
private transient Set<E> s; // Its keySet
5672
5673
SetFromMap(Map<E, Boolean> map) {
5674
if (!map.isEmpty())
5675
throw new IllegalArgumentException("Map is non-empty");
5676
m = map;
5677
s = map.keySet();
5678
}
5679
5680
public void clear() { m.clear(); }
5681
public int size() { return m.size(); }
5682
public boolean isEmpty() { return m.isEmpty(); }
5683
public boolean contains(Object o) { return m.containsKey(o); }
5684
public boolean remove(Object o) { return m.remove(o) != null; }
5685
public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; }
5686
public Iterator<E> iterator() { return s.iterator(); }
5687
public Object[] toArray() { return s.toArray(); }
5688
public <T> T[] toArray(T[] a) { return s.toArray(a); }
5689
public String toString() { return s.toString(); }
5690
public int hashCode() { return s.hashCode(); }
5691
public boolean equals(Object o) { return o == this || s.equals(o); }
5692
public boolean containsAll(Collection<?> c) {return s.containsAll(c);}
5693
public boolean removeAll(Collection<?> c) {return s.removeAll(c);}
5694
public boolean retainAll(Collection<?> c) {return s.retainAll(c);}
5695
// addAll is the only inherited implementation
5696
5697
// Override default methods in Collection
5698
@Override
5699
public void forEach(Consumer<? super E> action) {
5700
s.forEach(action);
5701
}
5702
@Override
5703
public boolean removeIf(Predicate<? super E> filter) {
5704
return s.removeIf(filter);
5705
}
5706
5707
@Override
5708
public Spliterator<E> spliterator() {return s.spliterator();}
5709
@Override
5710
public Stream<E> stream() {return s.stream();}
5711
@Override
5712
public Stream<E> parallelStream() {return s.parallelStream();}
5713
5714
@java.io.Serial
5715
private static final long serialVersionUID = 2454657854757543876L;
5716
5717
@java.io.Serial
5718
private void readObject(java.io.ObjectInputStream stream)
5719
throws IOException, ClassNotFoundException
5720
{
5721
stream.defaultReadObject();
5722
s = m.keySet();
5723
}
5724
}
5725
5726
/**
5727
* Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)
5728
* {@link Queue}. Method {@code add} is mapped to {@code push},
5729
* {@code remove} is mapped to {@code pop} and so on. This
5730
* view can be useful when you would like to use a method
5731
* requiring a {@code Queue} but you need Lifo ordering.
5732
*
5733
* <p>Each method invocation on the queue returned by this method
5734
* results in exactly one method invocation on the backing deque, with
5735
* one exception. The {@link Queue#addAll addAll} method is
5736
* implemented as a sequence of {@link Deque#addFirst addFirst}
5737
* invocations on the backing deque.
5738
*
5739
* @param <T> the class of the objects in the deque
5740
* @param deque the deque
5741
* @return the queue
5742
* @since 1.6
5743
*/
5744
public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
5745
return new AsLIFOQueue<>(Objects.requireNonNull(deque));
5746
}
5747
5748
/**
5749
* @serial include
5750
*/
5751
static class AsLIFOQueue<E> extends AbstractQueue<E>
5752
implements Queue<E>, Serializable {
5753
@java.io.Serial
5754
private static final long serialVersionUID = 1802017725587941708L;
5755
@SuppressWarnings("serial") // Conditionally serializable
5756
private final Deque<E> q;
5757
AsLIFOQueue(Deque<E> q) { this.q = q; }
5758
public boolean add(E e) { q.addFirst(e); return true; }
5759
public boolean offer(E e) { return q.offerFirst(e); }
5760
public E poll() { return q.pollFirst(); }
5761
public E remove() { return q.removeFirst(); }
5762
public E peek() { return q.peekFirst(); }
5763
public E element() { return q.getFirst(); }
5764
public void clear() { q.clear(); }
5765
public int size() { return q.size(); }
5766
public boolean isEmpty() { return q.isEmpty(); }
5767
public boolean contains(Object o) { return q.contains(o); }
5768
public boolean remove(Object o) { return q.remove(o); }
5769
public Iterator<E> iterator() { return q.iterator(); }
5770
public Object[] toArray() { return q.toArray(); }
5771
public <T> T[] toArray(T[] a) { return q.toArray(a); }
5772
public <T> T[] toArray(IntFunction<T[]> f) { return q.toArray(f); }
5773
public String toString() { return q.toString(); }
5774
public boolean containsAll(Collection<?> c) { return q.containsAll(c); }
5775
public boolean removeAll(Collection<?> c) { return q.removeAll(c); }
5776
public boolean retainAll(Collection<?> c) { return q.retainAll(c); }
5777
// We use inherited addAll; forwarding addAll would be wrong
5778
5779
// Override default methods in Collection
5780
@Override
5781
public void forEach(Consumer<? super E> action) {q.forEach(action);}
5782
@Override
5783
public boolean removeIf(Predicate<? super E> filter) {
5784
return q.removeIf(filter);
5785
}
5786
@Override
5787
public Spliterator<E> spliterator() {return q.spliterator();}
5788
@Override
5789
public Stream<E> stream() {return q.stream();}
5790
@Override
5791
public Stream<E> parallelStream() {return q.parallelStream();}
5792
}
5793
}
5794
5795