Print this page
Split |
Close |
Expand all |
Collapse all |
--- old/src/share/classes/java/util/Collections.java
+++ new/src/share/classes/java/util/Collections.java
1 1 /*
2 2 * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
3 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 4 *
5 5 * This code is free software; you can redistribute it and/or modify it
6 6 * under the terms of the GNU General Public License version 2 only, as
7 7 * published by the Free Software Foundation. Oracle designates this
8 8 * particular file as subject to the "Classpath" exception as provided
9 9 * by Oracle in the LICENSE file that accompanied this code.
10 10 *
11 11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 14 * version 2 for more details (a copy is included in the LICENSE file that
15 15 * accompanied this code).
16 16 *
17 17 * You should have received a copy of the GNU General Public License version
18 18 * 2 along with this work; if not, write to the Free Software Foundation,
19 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 20 *
21 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 22 * or visit www.oracle.com if you need additional information or have any
23 23 * questions.
24 24 */
25 25
26 26 package java.util;
27 27 import java.io.Serializable;
28 28 import java.io.ObjectOutputStream;
29 29 import java.io.IOException;
30 30 import java.lang.reflect.Array;
31 31
32 32 /**
33 33 * This class consists exclusively of static methods that operate on or return
34 34 * collections. It contains polymorphic algorithms that operate on
35 35 * collections, "wrappers", which return a new collection backed by a
36 36 * specified collection, and a few other odds and ends.
37 37 *
38 38 * <p>The methods of this class all throw a <tt>NullPointerException</tt>
39 39 * if the collections or class objects provided to them are null.
40 40 *
41 41 * <p>The documentation for the polymorphic algorithms contained in this class
42 42 * generally includes a brief description of the <i>implementation</i>. Such
43 43 * descriptions should be regarded as <i>implementation notes</i>, rather than
44 44 * parts of the <i>specification</i>. Implementors should feel free to
45 45 * substitute other algorithms, so long as the specification itself is adhered
46 46 * to. (For example, the algorithm used by <tt>sort</tt> does not have to be
47 47 * a mergesort, but it does have to be <i>stable</i>.)
48 48 *
49 49 * <p>The "destructive" algorithms contained in this class, that is, the
50 50 * algorithms that modify the collection on which they operate, are specified
51 51 * to throw <tt>UnsupportedOperationException</tt> if the collection does not
52 52 * support the appropriate mutation primitive(s), such as the <tt>set</tt>
53 53 * method. These algorithms may, but are not required to, throw this
54 54 * exception if an invocation would have no effect on the collection. For
55 55 * example, invoking the <tt>sort</tt> method on an unmodifiable list that is
56 56 * already sorted may or may not throw <tt>UnsupportedOperationException</tt>.
57 57 *
58 58 * <p>This class is a member of the
59 59 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
60 60 * Java Collections Framework</a>.
61 61 *
62 62 * @author Josh Bloch
63 63 * @author Neal Gafter
64 64 * @see Collection
65 65 * @see Set
66 66 * @see List
67 67 * @see Map
68 68 * @since 1.2
69 69 */
70 70
71 71 public class Collections {
72 72 // Suppresses default constructor, ensuring non-instantiability.
73 73 private Collections() {
74 74 }
75 75
76 76 // Algorithms
77 77
78 78 /*
79 79 * Tuning parameters for algorithms - Many of the List algorithms have
80 80 * two implementations, one of which is appropriate for RandomAccess
81 81 * lists, the other for "sequential." Often, the random access variant
82 82 * yields better performance on small sequential access lists. The
83 83 * tuning parameters below determine the cutoff point for what constitutes
84 84 * a "small" sequential access list for each algorithm. The values below
85 85 * were empirically determined to work well for LinkedList. Hopefully
86 86 * they should be reasonable for other sequential access List
87 87 * implementations. Those doing performance work on this code would
88 88 * do well to validate the values of these parameters from time to time.
89 89 * (The first word of each tuning parameter name is the algorithm to which
90 90 * it applies.)
91 91 */
92 92 private static final int BINARYSEARCH_THRESHOLD = 5000;
93 93 private static final int REVERSE_THRESHOLD = 18;
94 94 private static final int SHUFFLE_THRESHOLD = 5;
95 95 private static final int FILL_THRESHOLD = 25;
96 96 private static final int ROTATE_THRESHOLD = 100;
97 97 private static final int COPY_THRESHOLD = 10;
98 98 private static final int REPLACEALL_THRESHOLD = 11;
99 99 private static final int INDEXOFSUBLIST_THRESHOLD = 35;
100 100
101 101 /**
102 102 * Sorts the specified list into ascending order, according to the
103 103 * {@linkplain Comparable natural ordering} of its elements.
104 104 * All elements in the list must implement the {@link Comparable}
105 105 * interface. Furthermore, all elements in the list must be
106 106 * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)}
107 107 * must not throw a {@code ClassCastException} for any elements
108 108 * {@code e1} and {@code e2} in the list).
109 109 *
110 110 * <p>This sort is guaranteed to be <i>stable</i>: equal elements will
111 111 * not be reordered as a result of the sort.
112 112 *
113 113 * <p>The specified list must be modifiable, but need not be resizable.
114 114 *
115 115 * <p>Implementation note: This implementation is a stable, adaptive,
116 116 * iterative mergesort that requires far fewer than n lg(n) comparisons
↓ open down ↓ |
116 lines elided |
↑ open up ↑ |
117 117 * when the input array is partially sorted, while offering the
118 118 * performance of a traditional mergesort when the input array is
119 119 * randomly ordered. If the input array is nearly sorted, the
120 120 * implementation requires approximately n comparisons. Temporary
121 121 * storage requirements vary from a small constant for nearly sorted
122 122 * input arrays to n/2 object references for randomly ordered input
123 123 * arrays.
124 124 *
125 125 * <p>The implementation takes equal advantage of ascending and
126 126 * descending order in its input array, and can take advantage of
127 - * ascending and descending order in different parts of the the same
127 + * ascending and descending order in different parts of the same
128 128 * input array. It is well-suited to merging two or more sorted arrays:
129 129 * simply concatenate the arrays and sort the resulting array.
130 130 *
131 131 * <p>The implementation was adapted from Tim Peters's list sort for Python
132 132 * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
133 133 * TimSort</a>). It uses techiques from Peter McIlroy's "Optimistic
134 134 * Sorting and Information Theoretic Complexity", in Proceedings of the
135 135 * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
136 136 * January 1993.
137 137 *
138 138 * <p>This implementation dumps the specified list into an array, sorts
139 139 * the array, and iterates over the list resetting each element
140 140 * from the corresponding position in the array. This avoids the
141 141 * n<sup>2</sup> log(n) performance that would result from attempting
142 142 * to sort a linked list in place.
143 143 *
144 144 * @param list the list to be sorted.
145 145 * @throws ClassCastException if the list contains elements that are not
146 146 * <i>mutually comparable</i> (for example, strings and integers).
147 147 * @throws UnsupportedOperationException if the specified list's
148 148 * list-iterator does not support the {@code set} operation.
149 149 * @throws IllegalArgumentException (optional) if the implementation
150 150 * detects that the natural ordering of the list elements is
151 151 * found to violate the {@link Comparable} contract
152 152 */
153 153 public static <T extends Comparable<? super T>> void sort(List<T> list) {
154 154 Object[] a = list.toArray();
155 155 Arrays.sort(a);
156 156 ListIterator<T> i = list.listIterator();
157 157 for (int j=0; j<a.length; j++) {
158 158 i.next();
159 159 i.set((T)a[j]);
160 160 }
161 161 }
162 162
163 163 /**
164 164 * Sorts the specified list according to the order induced by the
165 165 * specified comparator. All elements in the list must be <i>mutually
166 166 * comparable</i> using the specified comparator (that is,
167 167 * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
168 168 * for any elements {@code e1} and {@code e2} in the list).
169 169 *
170 170 * <p>This sort is guaranteed to be <i>stable</i>: equal elements will
171 171 * not be reordered as a result of the sort.
172 172 *
173 173 * <p>The specified list must be modifiable, but need not be resizable.
174 174 *
175 175 * <p>Implementation note: This implementation is a stable, adaptive,
176 176 * iterative mergesort that requires far fewer than n lg(n) comparisons
↓ open down ↓ |
39 lines elided |
↑ open up ↑ |
177 177 * when the input array is partially sorted, while offering the
178 178 * performance of a traditional mergesort when the input array is
179 179 * randomly ordered. If the input array is nearly sorted, the
180 180 * implementation requires approximately n comparisons. Temporary
181 181 * storage requirements vary from a small constant for nearly sorted
182 182 * input arrays to n/2 object references for randomly ordered input
183 183 * arrays.
184 184 *
185 185 * <p>The implementation takes equal advantage of ascending and
186 186 * descending order in its input array, and can take advantage of
187 - * ascending and descending order in different parts of the the same
187 + * ascending and descending order in different parts of the same
188 188 * input array. It is well-suited to merging two or more sorted arrays:
189 189 * simply concatenate the arrays and sort the resulting array.
190 190 *
191 191 * <p>The implementation was adapted from Tim Peters's list sort for Python
192 192 * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
193 193 * TimSort</a>). It uses techiques from Peter McIlroy's "Optimistic
194 194 * Sorting and Information Theoretic Complexity", in Proceedings of the
195 195 * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
196 196 * January 1993.
197 197 *
198 198 * <p>This implementation dumps the specified list into an array, sorts
199 199 * the array, and iterates over the list resetting each element
200 200 * from the corresponding position in the array. This avoids the
201 201 * n<sup>2</sup> log(n) performance that would result from attempting
202 202 * to sort a linked list in place.
203 203 *
204 204 * @param list the list to be sorted.
205 205 * @param c the comparator to determine the order of the list. A
206 206 * {@code null} value indicates that the elements' <i>natural
207 207 * ordering</i> should be used.
208 208 * @throws ClassCastException if the list contains elements that are not
209 209 * <i>mutually comparable</i> using the specified comparator.
210 210 * @throws UnsupportedOperationException if the specified list's
211 211 * list-iterator does not support the {@code set} operation.
212 212 * @throws IllegalArgumentException (optional) if the comparator is
213 213 * found to violate the {@link Comparator} contract
214 214 */
215 215 public static <T> void sort(List<T> list, Comparator<? super T> c) {
216 216 Object[] a = list.toArray();
217 217 Arrays.sort(a, (Comparator)c);
218 218 ListIterator i = list.listIterator();
219 219 for (int j=0; j<a.length; j++) {
220 220 i.next();
221 221 i.set(a[j]);
222 222 }
223 223 }
224 224
225 225
226 226 /**
227 227 * Searches the specified list for the specified object using the binary
228 228 * search algorithm. The list must be sorted into ascending order
229 229 * according to the {@linkplain Comparable natural ordering} of its
230 230 * elements (as by the {@link #sort(List)} method) prior to making this
231 231 * call. If it is not sorted, the results are undefined. If the list
232 232 * contains multiple elements equal to the specified object, there is no
233 233 * guarantee which one will be found.
234 234 *
235 235 * <p>This method runs in log(n) time for a "random access" list (which
236 236 * provides near-constant-time positional access). If the specified list
237 237 * does not implement the {@link RandomAccess} interface and is large,
238 238 * this method will do an iterator-based binary search that performs
239 239 * O(n) link traversals and O(log n) element comparisons.
240 240 *
241 241 * @param list the list to be searched.
242 242 * @param key the key to be searched for.
243 243 * @return the index of the search key, if it is contained in the list;
244 244 * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
245 245 * <i>insertion point</i> is defined as the point at which the
246 246 * key would be inserted into the list: the index of the first
247 247 * element greater than the key, or <tt>list.size()</tt> if all
248 248 * elements in the list are less than the specified key. Note
249 249 * that this guarantees that the return value will be >= 0 if
250 250 * and only if the key is found.
251 251 * @throws ClassCastException if the list contains elements that are not
252 252 * <i>mutually comparable</i> (for example, strings and
253 253 * integers), or the search key is not mutually comparable
254 254 * with the elements of the list.
255 255 */
256 256 public static <T>
257 257 int binarySearch(List<? extends Comparable<? super T>> list, T key) {
258 258 if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
259 259 return Collections.indexedBinarySearch(list, key);
260 260 else
261 261 return Collections.iteratorBinarySearch(list, key);
262 262 }
263 263
264 264 private static <T>
265 265 int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key)
266 266 {
267 267 int low = 0;
268 268 int high = list.size()-1;
269 269
270 270 while (low <= high) {
271 271 int mid = (low + high) >>> 1;
272 272 Comparable<? super T> midVal = list.get(mid);
273 273 int cmp = midVal.compareTo(key);
274 274
275 275 if (cmp < 0)
276 276 low = mid + 1;
277 277 else if (cmp > 0)
278 278 high = mid - 1;
279 279 else
280 280 return mid; // key found
281 281 }
282 282 return -(low + 1); // key not found
283 283 }
284 284
285 285 private static <T>
286 286 int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key)
287 287 {
288 288 int low = 0;
289 289 int high = list.size()-1;
290 290 ListIterator<? extends Comparable<? super T>> i = list.listIterator();
291 291
292 292 while (low <= high) {
293 293 int mid = (low + high) >>> 1;
294 294 Comparable<? super T> midVal = get(i, mid);
295 295 int cmp = midVal.compareTo(key);
296 296
297 297 if (cmp < 0)
298 298 low = mid + 1;
299 299 else if (cmp > 0)
300 300 high = mid - 1;
301 301 else
302 302 return mid; // key found
303 303 }
304 304 return -(low + 1); // key not found
305 305 }
306 306
307 307 /**
308 308 * Gets the ith element from the given list by repositioning the specified
309 309 * list listIterator.
310 310 */
311 311 private static <T> T get(ListIterator<? extends T> i, int index) {
312 312 T obj = null;
313 313 int pos = i.nextIndex();
314 314 if (pos <= index) {
315 315 do {
316 316 obj = i.next();
317 317 } while (pos++ < index);
318 318 } else {
319 319 do {
320 320 obj = i.previous();
321 321 } while (--pos > index);
322 322 }
323 323 return obj;
324 324 }
325 325
326 326 /**
327 327 * Searches the specified list for the specified object using the binary
328 328 * search algorithm. The list must be sorted into ascending order
329 329 * according to the specified comparator (as by the
330 330 * {@link #sort(List, Comparator) sort(List, Comparator)}
331 331 * method), prior to making this call. If it is
332 332 * not sorted, the results are undefined. If the list contains multiple
333 333 * elements equal to the specified object, there is no guarantee which one
334 334 * will be found.
335 335 *
336 336 * <p>This method runs in log(n) time for a "random access" list (which
337 337 * provides near-constant-time positional access). If the specified list
338 338 * does not implement the {@link RandomAccess} interface and is large,
339 339 * this method will do an iterator-based binary search that performs
340 340 * O(n) link traversals and O(log n) element comparisons.
341 341 *
342 342 * @param list the list to be searched.
343 343 * @param key the key to be searched for.
344 344 * @param c the comparator by which the list is ordered.
345 345 * A <tt>null</tt> value indicates that the elements'
346 346 * {@linkplain Comparable natural ordering} should be used.
347 347 * @return the index of the search key, if it is contained in the list;
348 348 * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
349 349 * <i>insertion point</i> is defined as the point at which the
350 350 * key would be inserted into the list: the index of the first
351 351 * element greater than the key, or <tt>list.size()</tt> if all
352 352 * elements in the list are less than the specified key. Note
353 353 * that this guarantees that the return value will be >= 0 if
354 354 * and only if the key is found.
355 355 * @throws ClassCastException if the list contains elements that are not
356 356 * <i>mutually comparable</i> using the specified comparator,
357 357 * or the search key is not mutually comparable with the
358 358 * elements of the list using this comparator.
359 359 */
360 360 public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) {
361 361 if (c==null)
362 362 return binarySearch((List) list, key);
363 363
364 364 if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
365 365 return Collections.indexedBinarySearch(list, key, c);
366 366 else
367 367 return Collections.iteratorBinarySearch(list, key, c);
368 368 }
369 369
370 370 private static <T> int indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {
371 371 int low = 0;
372 372 int high = l.size()-1;
373 373
374 374 while (low <= high) {
375 375 int mid = (low + high) >>> 1;
376 376 T midVal = l.get(mid);
377 377 int cmp = c.compare(midVal, key);
378 378
379 379 if (cmp < 0)
380 380 low = mid + 1;
381 381 else if (cmp > 0)
382 382 high = mid - 1;
383 383 else
384 384 return mid; // key found
385 385 }
386 386 return -(low + 1); // key not found
387 387 }
388 388
389 389 private static <T> int iteratorBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {
390 390 int low = 0;
391 391 int high = l.size()-1;
392 392 ListIterator<? extends T> i = l.listIterator();
393 393
394 394 while (low <= high) {
395 395 int mid = (low + high) >>> 1;
396 396 T midVal = get(i, mid);
397 397 int cmp = c.compare(midVal, key);
398 398
399 399 if (cmp < 0)
400 400 low = mid + 1;
401 401 else if (cmp > 0)
402 402 high = mid - 1;
403 403 else
404 404 return mid; // key found
405 405 }
406 406 return -(low + 1); // key not found
407 407 }
408 408
409 409 private interface SelfComparable extends Comparable<SelfComparable> {}
410 410
411 411
412 412 /**
413 413 * Reverses the order of the elements in the specified list.<p>
414 414 *
415 415 * This method runs in linear time.
416 416 *
417 417 * @param list the list whose elements are to be reversed.
418 418 * @throws UnsupportedOperationException if the specified list or
419 419 * its list-iterator does not support the <tt>set</tt> operation.
420 420 */
421 421 public static void reverse(List<?> list) {
422 422 int size = list.size();
423 423 if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
424 424 for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
425 425 swap(list, i, j);
426 426 } else {
427 427 ListIterator fwd = list.listIterator();
428 428 ListIterator rev = list.listIterator(size);
429 429 for (int i=0, mid=list.size()>>1; i<mid; i++) {
430 430 Object tmp = fwd.next();
431 431 fwd.set(rev.previous());
432 432 rev.set(tmp);
433 433 }
434 434 }
435 435 }
436 436
437 437 /**
438 438 * Randomly permutes the specified list using a default source of
439 439 * randomness. All permutations occur with approximately equal
440 440 * likelihood.<p>
441 441 *
442 442 * The hedge "approximately" is used in the foregoing description because
443 443 * default source of randomness is only approximately an unbiased source
444 444 * of independently chosen bits. If it were a perfect source of randomly
445 445 * chosen bits, then the algorithm would choose permutations with perfect
446 446 * uniformity.<p>
447 447 *
448 448 * This implementation traverses the list backwards, from the last element
449 449 * up to the second, repeatedly swapping a randomly selected element into
450 450 * the "current position". Elements are randomly selected from the
451 451 * portion of the list that runs from the first element to the current
452 452 * position, inclusive.<p>
453 453 *
454 454 * This method runs in linear time. If the specified list does not
455 455 * implement the {@link RandomAccess} interface and is large, this
456 456 * implementation dumps the specified list into an array before shuffling
457 457 * it, and dumps the shuffled array back into the list. This avoids the
458 458 * quadratic behavior that would result from shuffling a "sequential
459 459 * access" list in place.
460 460 *
461 461 * @param list the list to be shuffled.
462 462 * @throws UnsupportedOperationException if the specified list or
463 463 * its list-iterator does not support the <tt>set</tt> operation.
464 464 */
465 465 public static void shuffle(List<?> list) {
466 466 Random rnd = r;
467 467 if (rnd == null)
468 468 r = rnd = new Random();
469 469 shuffle(list, rnd);
470 470 }
471 471 private static Random r;
472 472
473 473 /**
474 474 * Randomly permute the specified list using the specified source of
475 475 * randomness. All permutations occur with equal likelihood
476 476 * assuming that the source of randomness is fair.<p>
477 477 *
478 478 * This implementation traverses the list backwards, from the last element
479 479 * up to the second, repeatedly swapping a randomly selected element into
480 480 * the "current position". Elements are randomly selected from the
481 481 * portion of the list that runs from the first element to the current
482 482 * position, inclusive.<p>
483 483 *
484 484 * This method runs in linear time. If the specified list does not
485 485 * implement the {@link RandomAccess} interface and is large, this
486 486 * implementation dumps the specified list into an array before shuffling
487 487 * it, and dumps the shuffled array back into the list. This avoids the
488 488 * quadratic behavior that would result from shuffling a "sequential
489 489 * access" list in place.
490 490 *
491 491 * @param list the list to be shuffled.
492 492 * @param rnd the source of randomness to use to shuffle the list.
493 493 * @throws UnsupportedOperationException if the specified list or its
494 494 * list-iterator does not support the <tt>set</tt> operation.
495 495 */
496 496 public static void shuffle(List<?> list, Random rnd) {
497 497 int size = list.size();
498 498 if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
499 499 for (int i=size; i>1; i--)
500 500 swap(list, i-1, rnd.nextInt(i));
501 501 } else {
502 502 Object arr[] = list.toArray();
503 503
504 504 // Shuffle array
505 505 for (int i=size; i>1; i--)
506 506 swap(arr, i-1, rnd.nextInt(i));
507 507
508 508 // Dump array back into list
509 509 ListIterator it = list.listIterator();
510 510 for (int i=0; i<arr.length; i++) {
511 511 it.next();
512 512 it.set(arr[i]);
513 513 }
514 514 }
515 515 }
516 516
517 517 /**
518 518 * Swaps the elements at the specified positions in the specified list.
519 519 * (If the specified positions are equal, invoking this method leaves
520 520 * the list unchanged.)
521 521 *
522 522 * @param list The list in which to swap elements.
523 523 * @param i the index of one element to be swapped.
524 524 * @param j the index of the other element to be swapped.
525 525 * @throws IndexOutOfBoundsException if either <tt>i</tt> or <tt>j</tt>
526 526 * is out of range (i < 0 || i >= list.size()
527 527 * || j < 0 || j >= list.size()).
528 528 * @since 1.4
529 529 */
530 530 public static void swap(List<?> list, int i, int j) {
531 531 final List l = list;
532 532 l.set(i, l.set(j, l.get(i)));
533 533 }
534 534
535 535 /**
536 536 * Swaps the two specified elements in the specified array.
537 537 */
538 538 private static void swap(Object[] arr, int i, int j) {
539 539 Object tmp = arr[i];
540 540 arr[i] = arr[j];
541 541 arr[j] = tmp;
542 542 }
543 543
544 544 /**
545 545 * Replaces all of the elements of the specified list with the specified
546 546 * element. <p>
547 547 *
548 548 * This method runs in linear time.
549 549 *
550 550 * @param list the list to be filled with the specified element.
551 551 * @param obj The element with which to fill the specified list.
552 552 * @throws UnsupportedOperationException if the specified list or its
553 553 * list-iterator does not support the <tt>set</tt> operation.
554 554 */
555 555 public static <T> void fill(List<? super T> list, T obj) {
556 556 int size = list.size();
557 557
558 558 if (size < FILL_THRESHOLD || list instanceof RandomAccess) {
559 559 for (int i=0; i<size; i++)
560 560 list.set(i, obj);
561 561 } else {
562 562 ListIterator<? super T> itr = list.listIterator();
563 563 for (int i=0; i<size; i++) {
564 564 itr.next();
565 565 itr.set(obj);
566 566 }
567 567 }
568 568 }
569 569
570 570 /**
571 571 * Copies all of the elements from one list into another. After the
572 572 * operation, the index of each copied element in the destination list
573 573 * will be identical to its index in the source list. The destination
574 574 * list must be at least as long as the source list. If it is longer, the
575 575 * remaining elements in the destination list are unaffected. <p>
576 576 *
577 577 * This method runs in linear time.
578 578 *
579 579 * @param dest The destination list.
580 580 * @param src The source list.
581 581 * @throws IndexOutOfBoundsException if the destination list is too small
582 582 * to contain the entire source List.
583 583 * @throws UnsupportedOperationException if the destination list's
584 584 * list-iterator does not support the <tt>set</tt> operation.
585 585 */
586 586 public static <T> void copy(List<? super T> dest, List<? extends T> src) {
587 587 int srcSize = src.size();
588 588 if (srcSize > dest.size())
589 589 throw new IndexOutOfBoundsException("Source does not fit in dest");
590 590
591 591 if (srcSize < COPY_THRESHOLD ||
592 592 (src instanceof RandomAccess && dest instanceof RandomAccess)) {
593 593 for (int i=0; i<srcSize; i++)
594 594 dest.set(i, src.get(i));
595 595 } else {
596 596 ListIterator<? super T> di=dest.listIterator();
597 597 ListIterator<? extends T> si=src.listIterator();
598 598 for (int i=0; i<srcSize; i++) {
599 599 di.next();
600 600 di.set(si.next());
601 601 }
602 602 }
603 603 }
604 604
605 605 /**
606 606 * Returns the minimum element of the given collection, according to the
607 607 * <i>natural ordering</i> of its elements. All elements in the
608 608 * collection must implement the <tt>Comparable</tt> interface.
609 609 * Furthermore, all elements in the collection must be <i>mutually
610 610 * comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a
611 611 * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
612 612 * <tt>e2</tt> in the collection).<p>
613 613 *
614 614 * This method iterates over the entire collection, hence it requires
615 615 * time proportional to the size of the collection.
616 616 *
617 617 * @param coll the collection whose minimum element is to be determined.
618 618 * @return the minimum element of the given collection, according
619 619 * to the <i>natural ordering</i> of its elements.
620 620 * @throws ClassCastException if the collection contains elements that are
621 621 * not <i>mutually comparable</i> (for example, strings and
622 622 * integers).
623 623 * @throws NoSuchElementException if the collection is empty.
624 624 * @see Comparable
625 625 */
626 626 public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
627 627 Iterator<? extends T> i = coll.iterator();
628 628 T candidate = i.next();
629 629
630 630 while (i.hasNext()) {
631 631 T next = i.next();
632 632 if (next.compareTo(candidate) < 0)
633 633 candidate = next;
634 634 }
635 635 return candidate;
636 636 }
637 637
638 638 /**
639 639 * Returns the minimum element of the given collection, according to the
640 640 * order induced by the specified comparator. All elements in the
641 641 * collection must be <i>mutually comparable</i> by the specified
642 642 * comparator (that is, <tt>comp.compare(e1, e2)</tt> must not throw a
643 643 * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
644 644 * <tt>e2</tt> in the collection).<p>
645 645 *
646 646 * This method iterates over the entire collection, hence it requires
647 647 * time proportional to the size of the collection.
648 648 *
649 649 * @param coll the collection whose minimum element is to be determined.
650 650 * @param comp the comparator with which to determine the minimum element.
651 651 * A <tt>null</tt> value indicates that the elements' <i>natural
652 652 * ordering</i> should be used.
653 653 * @return the minimum element of the given collection, according
654 654 * to the specified comparator.
655 655 * @throws ClassCastException if the collection contains elements that are
656 656 * not <i>mutually comparable</i> using the specified comparator.
657 657 * @throws NoSuchElementException if the collection is empty.
658 658 * @see Comparable
659 659 */
660 660 public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {
661 661 if (comp==null)
662 662 return (T)min((Collection<SelfComparable>) (Collection) coll);
663 663
664 664 Iterator<? extends T> i = coll.iterator();
665 665 T candidate = i.next();
666 666
667 667 while (i.hasNext()) {
668 668 T next = i.next();
669 669 if (comp.compare(next, candidate) < 0)
670 670 candidate = next;
671 671 }
672 672 return candidate;
673 673 }
674 674
675 675 /**
676 676 * Returns the maximum element of the given collection, according to the
677 677 * <i>natural ordering</i> of its elements. All elements in the
678 678 * collection must implement the <tt>Comparable</tt> interface.
679 679 * Furthermore, all elements in the collection must be <i>mutually
680 680 * comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a
681 681 * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
682 682 * <tt>e2</tt> in the collection).<p>
683 683 *
684 684 * This method iterates over the entire collection, hence it requires
685 685 * time proportional to the size of the collection.
686 686 *
687 687 * @param coll the collection whose maximum element is to be determined.
688 688 * @return the maximum element of the given collection, according
689 689 * to the <i>natural ordering</i> of its elements.
690 690 * @throws ClassCastException if the collection contains elements that are
691 691 * not <i>mutually comparable</i> (for example, strings and
692 692 * integers).
693 693 * @throws NoSuchElementException if the collection is empty.
694 694 * @see Comparable
695 695 */
696 696 public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
697 697 Iterator<? extends T> i = coll.iterator();
698 698 T candidate = i.next();
699 699
700 700 while (i.hasNext()) {
701 701 T next = i.next();
702 702 if (next.compareTo(candidate) > 0)
703 703 candidate = next;
704 704 }
705 705 return candidate;
706 706 }
707 707
708 708 /**
709 709 * Returns the maximum element of the given collection, according to the
710 710 * order induced by the specified comparator. All elements in the
711 711 * collection must be <i>mutually comparable</i> by the specified
712 712 * comparator (that is, <tt>comp.compare(e1, e2)</tt> must not throw a
713 713 * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
714 714 * <tt>e2</tt> in the collection).<p>
715 715 *
716 716 * This method iterates over the entire collection, hence it requires
717 717 * time proportional to the size of the collection.
718 718 *
719 719 * @param coll the collection whose maximum element is to be determined.
720 720 * @param comp the comparator with which to determine the maximum element.
721 721 * A <tt>null</tt> value indicates that the elements' <i>natural
722 722 * ordering</i> should be used.
723 723 * @return the maximum element of the given collection, according
724 724 * to the specified comparator.
725 725 * @throws ClassCastException if the collection contains elements that are
726 726 * not <i>mutually comparable</i> using the specified comparator.
727 727 * @throws NoSuchElementException if the collection is empty.
728 728 * @see Comparable
729 729 */
730 730 public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {
731 731 if (comp==null)
732 732 return (T)max((Collection<SelfComparable>) (Collection) coll);
733 733
734 734 Iterator<? extends T> i = coll.iterator();
735 735 T candidate = i.next();
736 736
737 737 while (i.hasNext()) {
738 738 T next = i.next();
739 739 if (comp.compare(next, candidate) > 0)
740 740 candidate = next;
741 741 }
742 742 return candidate;
743 743 }
744 744
745 745 /**
746 746 * Rotates the elements in the specified list by the specified distance.
747 747 * After calling this method, the element at index <tt>i</tt> will be
748 748 * the element previously at index <tt>(i - distance)</tt> mod
749 749 * <tt>list.size()</tt>, for all values of <tt>i</tt> between <tt>0</tt>
750 750 * and <tt>list.size()-1</tt>, inclusive. (This method has no effect on
751 751 * the size of the list.)
752 752 *
753 753 * <p>For example, suppose <tt>list</tt> comprises<tt> [t, a, n, k, s]</tt>.
754 754 * After invoking <tt>Collections.rotate(list, 1)</tt> (or
755 755 * <tt>Collections.rotate(list, -4)</tt>), <tt>list</tt> will comprise
756 756 * <tt>[s, t, a, n, k]</tt>.
757 757 *
758 758 * <p>Note that this method can usefully be applied to sublists to
759 759 * move one or more elements within a list while preserving the
760 760 * order of the remaining elements. For example, the following idiom
761 761 * moves the element at index <tt>j</tt> forward to position
762 762 * <tt>k</tt> (which must be greater than or equal to <tt>j</tt>):
763 763 * <pre>
764 764 * Collections.rotate(list.subList(j, k+1), -1);
765 765 * </pre>
766 766 * To make this concrete, suppose <tt>list</tt> comprises
767 767 * <tt>[a, b, c, d, e]</tt>. To move the element at index <tt>1</tt>
768 768 * (<tt>b</tt>) forward two positions, perform the following invocation:
769 769 * <pre>
770 770 * Collections.rotate(l.subList(1, 4), -1);
771 771 * </pre>
772 772 * The resulting list is <tt>[a, c, d, b, e]</tt>.
773 773 *
774 774 * <p>To move more than one element forward, increase the absolute value
775 775 * of the rotation distance. To move elements backward, use a positive
776 776 * shift distance.
777 777 *
778 778 * <p>If the specified list is small or implements the {@link
779 779 * RandomAccess} interface, this implementation exchanges the first
780 780 * element into the location it should go, and then repeatedly exchanges
781 781 * the displaced element into the location it should go until a displaced
782 782 * element is swapped into the first element. If necessary, the process
783 783 * is repeated on the second and successive elements, until the rotation
784 784 * is complete. If the specified list is large and doesn't implement the
785 785 * <tt>RandomAccess</tt> interface, this implementation breaks the
786 786 * list into two sublist views around index <tt>-distance mod size</tt>.
787 787 * Then the {@link #reverse(List)} method is invoked on each sublist view,
788 788 * and finally it is invoked on the entire list. For a more complete
789 789 * description of both algorithms, see Section 2.3 of Jon Bentley's
790 790 * <i>Programming Pearls</i> (Addison-Wesley, 1986).
791 791 *
792 792 * @param list the list to be rotated.
793 793 * @param distance the distance to rotate the list. There are no
794 794 * constraints on this value; it may be zero, negative, or
795 795 * greater than <tt>list.size()</tt>.
796 796 * @throws UnsupportedOperationException if the specified list or
797 797 * its list-iterator does not support the <tt>set</tt> operation.
798 798 * @since 1.4
799 799 */
800 800 public static void rotate(List<?> list, int distance) {
801 801 if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD)
802 802 rotate1(list, distance);
803 803 else
804 804 rotate2(list, distance);
805 805 }
806 806
807 807 private static <T> void rotate1(List<T> list, int distance) {
808 808 int size = list.size();
809 809 if (size == 0)
810 810 return;
811 811 distance = distance % size;
812 812 if (distance < 0)
813 813 distance += size;
814 814 if (distance == 0)
815 815 return;
↓ open down ↓ |
618 lines elided |
↑ open up ↑ |
816 816
817 817 for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) {
818 818 T displaced = list.get(cycleStart);
819 819 int i = cycleStart;
820 820 do {
821 821 i += distance;
822 822 if (i >= size)
823 823 i -= size;
824 824 displaced = list.set(i, displaced);
825 825 nMoved ++;
826 - } while(i != cycleStart);
826 + } while (i != cycleStart);
827 827 }
828 828 }
829 829
830 830 private static void rotate2(List<?> list, int distance) {
831 831 int size = list.size();
832 832 if (size == 0)
833 833 return;
834 834 int mid = -distance % size;
835 835 if (mid < 0)
836 836 mid += size;
837 837 if (mid == 0)
838 838 return;
839 839
840 840 reverse(list.subList(0, mid));
841 841 reverse(list.subList(mid, size));
842 842 reverse(list);
843 843 }
844 844
845 845 /**
846 846 * Replaces all occurrences of one specified value in a list with another.
847 847 * More formally, replaces with <tt>newVal</tt> each element <tt>e</tt>
848 848 * in <tt>list</tt> such that
849 849 * <tt>(oldVal==null ? e==null : oldVal.equals(e))</tt>.
850 850 * (This method has no effect on the size of the list.)
851 851 *
852 852 * @param list the list in which replacement is to occur.
853 853 * @param oldVal the old value to be replaced.
854 854 * @param newVal the new value with which <tt>oldVal</tt> is to be
855 855 * replaced.
856 856 * @return <tt>true</tt> if <tt>list</tt> contained one or more elements
857 857 * <tt>e</tt> such that
858 858 * <tt>(oldVal==null ? e==null : oldVal.equals(e))</tt>.
859 859 * @throws UnsupportedOperationException if the specified list or
860 860 * its list-iterator does not support the <tt>set</tt> operation.
861 861 * @since 1.4
862 862 */
863 863 public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) {
864 864 boolean result = false;
865 865 int size = list.size();
866 866 if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) {
867 867 if (oldVal==null) {
868 868 for (int i=0; i<size; i++) {
869 869 if (list.get(i)==null) {
870 870 list.set(i, newVal);
871 871 result = true;
872 872 }
873 873 }
874 874 } else {
875 875 for (int i=0; i<size; i++) {
876 876 if (oldVal.equals(list.get(i))) {
877 877 list.set(i, newVal);
878 878 result = true;
879 879 }
880 880 }
881 881 }
882 882 } else {
883 883 ListIterator<T> itr=list.listIterator();
884 884 if (oldVal==null) {
885 885 for (int i=0; i<size; i++) {
886 886 if (itr.next()==null) {
887 887 itr.set(newVal);
888 888 result = true;
889 889 }
890 890 }
891 891 } else {
892 892 for (int i=0; i<size; i++) {
893 893 if (oldVal.equals(itr.next())) {
894 894 itr.set(newVal);
895 895 result = true;
896 896 }
897 897 }
898 898 }
899 899 }
900 900 return result;
901 901 }
902 902
903 903 /**
904 904 * Returns the starting position of the first occurrence of the specified
905 905 * target list within the specified source list, or -1 if there is no
906 906 * such occurrence. More formally, returns the lowest index <tt>i</tt>
907 907 * such that <tt>source.subList(i, i+target.size()).equals(target)</tt>,
908 908 * or -1 if there is no such index. (Returns -1 if
909 909 * <tt>target.size() > source.size()</tt>.)
910 910 *
911 911 * <p>This implementation uses the "brute force" technique of scanning
912 912 * over the source list, looking for a match with the target at each
913 913 * location in turn.
914 914 *
915 915 * @param source the list in which to search for the first occurrence
916 916 * of <tt>target</tt>.
917 917 * @param target the list to search for as a subList of <tt>source</tt>.
918 918 * @return the starting position of the first occurrence of the specified
919 919 * target list within the specified source list, or -1 if there
920 920 * is no such occurrence.
921 921 * @since 1.4
922 922 */
923 923 public static int indexOfSubList(List<?> source, List<?> target) {
924 924 int sourceSize = source.size();
925 925 int targetSize = target.size();
926 926 int maxCandidate = sourceSize - targetSize;
927 927
928 928 if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
929 929 (source instanceof RandomAccess&&target instanceof RandomAccess)) {
930 930 nextCand:
931 931 for (int candidate = 0; candidate <= maxCandidate; candidate++) {
932 932 for (int i=0, j=candidate; i<targetSize; i++, j++)
933 933 if (!eq(target.get(i), source.get(j)))
934 934 continue nextCand; // Element mismatch, try next cand
935 935 return candidate; // All elements of candidate matched target
936 936 }
937 937 } else { // Iterator version of above algorithm
938 938 ListIterator<?> si = source.listIterator();
939 939 nextCand:
940 940 for (int candidate = 0; candidate <= maxCandidate; candidate++) {
941 941 ListIterator<?> ti = target.listIterator();
942 942 for (int i=0; i<targetSize; i++) {
943 943 if (!eq(ti.next(), si.next())) {
944 944 // Back up source iterator to next candidate
945 945 for (int j=0; j<i; j++)
946 946 si.previous();
947 947 continue nextCand;
948 948 }
949 949 }
950 950 return candidate;
951 951 }
952 952 }
953 953 return -1; // No candidate matched the target
954 954 }
955 955
956 956 /**
957 957 * Returns the starting position of the last occurrence of the specified
958 958 * target list within the specified source list, or -1 if there is no such
959 959 * occurrence. More formally, returns the highest index <tt>i</tt>
960 960 * such that <tt>source.subList(i, i+target.size()).equals(target)</tt>,
961 961 * or -1 if there is no such index. (Returns -1 if
962 962 * <tt>target.size() > source.size()</tt>.)
963 963 *
964 964 * <p>This implementation uses the "brute force" technique of iterating
965 965 * over the source list, looking for a match with the target at each
966 966 * location in turn.
967 967 *
968 968 * @param source the list in which to search for the last occurrence
969 969 * of <tt>target</tt>.
970 970 * @param target the list to search for as a subList of <tt>source</tt>.
971 971 * @return the starting position of the last occurrence of the specified
972 972 * target list within the specified source list, or -1 if there
973 973 * is no such occurrence.
974 974 * @since 1.4
975 975 */
976 976 public static int lastIndexOfSubList(List<?> source, List<?> target) {
977 977 int sourceSize = source.size();
978 978 int targetSize = target.size();
979 979 int maxCandidate = sourceSize - targetSize;
980 980
981 981 if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
982 982 source instanceof RandomAccess) { // Index access version
983 983 nextCand:
984 984 for (int candidate = maxCandidate; candidate >= 0; candidate--) {
985 985 for (int i=0, j=candidate; i<targetSize; i++, j++)
986 986 if (!eq(target.get(i), source.get(j)))
987 987 continue nextCand; // Element mismatch, try next cand
988 988 return candidate; // All elements of candidate matched target
989 989 }
990 990 } else { // Iterator version of above algorithm
991 991 if (maxCandidate < 0)
992 992 return -1;
993 993 ListIterator<?> si = source.listIterator(maxCandidate);
994 994 nextCand:
995 995 for (int candidate = maxCandidate; candidate >= 0; candidate--) {
996 996 ListIterator<?> ti = target.listIterator();
997 997 for (int i=0; i<targetSize; i++) {
998 998 if (!eq(ti.next(), si.next())) {
999 999 if (candidate != 0) {
1000 1000 // Back up source iterator to next candidate
1001 1001 for (int j=0; j<=i+1; j++)
1002 1002 si.previous();
1003 1003 }
1004 1004 continue nextCand;
1005 1005 }
1006 1006 }
1007 1007 return candidate;
1008 1008 }
1009 1009 }
1010 1010 return -1; // No candidate matched the target
1011 1011 }
1012 1012
1013 1013
1014 1014 // Unmodifiable Wrappers
1015 1015
1016 1016 /**
1017 1017 * Returns an unmodifiable view of the specified collection. This method
1018 1018 * allows modules to provide users with "read-only" access to internal
1019 1019 * collections. Query operations on the returned collection "read through"
1020 1020 * to the specified collection, and attempts to modify the returned
1021 1021 * collection, whether direct or via its iterator, result in an
1022 1022 * <tt>UnsupportedOperationException</tt>.<p>
1023 1023 *
1024 1024 * The returned collection does <i>not</i> pass the hashCode and equals
1025 1025 * operations through to the backing collection, but relies on
1026 1026 * <tt>Object</tt>'s <tt>equals</tt> and <tt>hashCode</tt> methods. This
1027 1027 * is necessary to preserve the contracts of these operations in the case
1028 1028 * that the backing collection is a set or a list.<p>
1029 1029 *
1030 1030 * The returned collection will be serializable if the specified collection
1031 1031 * is serializable.
1032 1032 *
1033 1033 * @param c the collection for which an unmodifiable view is to be
1034 1034 * returned.
1035 1035 * @return an unmodifiable view of the specified collection.
1036 1036 */
1037 1037 public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
1038 1038 return new UnmodifiableCollection<T>(c);
1039 1039 }
1040 1040
1041 1041 /**
1042 1042 * @serial include
1043 1043 */
1044 1044 static class UnmodifiableCollection<E> implements Collection<E>, Serializable {
1045 1045 private static final long serialVersionUID = 1820017752578914078L;
1046 1046
1047 1047 final Collection<? extends E> c;
1048 1048
1049 1049 UnmodifiableCollection(Collection<? extends E> c) {
1050 1050 if (c==null)
1051 1051 throw new NullPointerException();
1052 1052 this.c = c;
1053 1053 }
1054 1054
1055 1055 public int size() {return c.size();}
1056 1056 public boolean isEmpty() {return c.isEmpty();}
1057 1057 public boolean contains(Object o) {return c.contains(o);}
1058 1058 public Object[] toArray() {return c.toArray();}
1059 1059 public <T> T[] toArray(T[] a) {return c.toArray(a);}
1060 1060 public String toString() {return c.toString();}
1061 1061
1062 1062 public Iterator<E> iterator() {
1063 1063 return new Iterator<E>() {
1064 1064 private final Iterator<? extends E> i = c.iterator();
1065 1065
1066 1066 public boolean hasNext() {return i.hasNext();}
1067 1067 public E next() {return i.next();}
1068 1068 public void remove() {
1069 1069 throw new UnsupportedOperationException();
1070 1070 }
1071 1071 };
1072 1072 }
1073 1073
1074 1074 public boolean add(E e) {
1075 1075 throw new UnsupportedOperationException();
1076 1076 }
1077 1077 public boolean remove(Object o) {
1078 1078 throw new UnsupportedOperationException();
1079 1079 }
1080 1080
1081 1081 public boolean containsAll(Collection<?> coll) {
1082 1082 return c.containsAll(coll);
1083 1083 }
1084 1084 public boolean addAll(Collection<? extends E> coll) {
1085 1085 throw new UnsupportedOperationException();
1086 1086 }
1087 1087 public boolean removeAll(Collection<?> coll) {
1088 1088 throw new UnsupportedOperationException();
1089 1089 }
1090 1090 public boolean retainAll(Collection<?> coll) {
1091 1091 throw new UnsupportedOperationException();
1092 1092 }
1093 1093 public void clear() {
1094 1094 throw new UnsupportedOperationException();
1095 1095 }
1096 1096 }
1097 1097
1098 1098 /**
1099 1099 * Returns an unmodifiable view of the specified set. This method allows
1100 1100 * modules to provide users with "read-only" access to internal sets.
1101 1101 * Query operations on the returned set "read through" to the specified
1102 1102 * set, and attempts to modify the returned set, whether direct or via its
1103 1103 * iterator, result in an <tt>UnsupportedOperationException</tt>.<p>
1104 1104 *
1105 1105 * The returned set will be serializable if the specified set
1106 1106 * is serializable.
1107 1107 *
1108 1108 * @param s the set for which an unmodifiable view is to be returned.
1109 1109 * @return an unmodifiable view of the specified set.
1110 1110 */
1111 1111 public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
1112 1112 return new UnmodifiableSet<T>(s);
1113 1113 }
1114 1114
1115 1115 /**
1116 1116 * @serial include
1117 1117 */
1118 1118 static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
1119 1119 implements Set<E>, Serializable {
1120 1120 private static final long serialVersionUID = -9215047833775013803L;
1121 1121
1122 1122 UnmodifiableSet(Set<? extends E> s) {super(s);}
1123 1123 public boolean equals(Object o) {return o == this || c.equals(o);}
1124 1124 public int hashCode() {return c.hashCode();}
1125 1125 }
1126 1126
1127 1127 /**
1128 1128 * Returns an unmodifiable view of the specified sorted set. This method
1129 1129 * allows modules to provide users with "read-only" access to internal
1130 1130 * sorted sets. Query operations on the returned sorted set "read
1131 1131 * through" to the specified sorted set. Attempts to modify the returned
1132 1132 * sorted set, whether direct, via its iterator, or via its
1133 1133 * <tt>subSet</tt>, <tt>headSet</tt>, or <tt>tailSet</tt> views, result in
1134 1134 * an <tt>UnsupportedOperationException</tt>.<p>
1135 1135 *
1136 1136 * The returned sorted set will be serializable if the specified sorted set
1137 1137 * is serializable.
1138 1138 *
1139 1139 * @param s the sorted set for which an unmodifiable view is to be
1140 1140 * returned.
1141 1141 * @return an unmodifiable view of the specified sorted set.
1142 1142 */
1143 1143 public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
1144 1144 return new UnmodifiableSortedSet<T>(s);
1145 1145 }
1146 1146
1147 1147 /**
1148 1148 * @serial include
1149 1149 */
1150 1150 static class UnmodifiableSortedSet<E>
1151 1151 extends UnmodifiableSet<E>
1152 1152 implements SortedSet<E>, Serializable {
1153 1153 private static final long serialVersionUID = -4929149591599911165L;
1154 1154 private final SortedSet<E> ss;
1155 1155
1156 1156 UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}
1157 1157
1158 1158 public Comparator<? super E> comparator() {return ss.comparator();}
1159 1159
1160 1160 public SortedSet<E> subSet(E fromElement, E toElement) {
1161 1161 return new UnmodifiableSortedSet<E>(ss.subSet(fromElement,toElement));
1162 1162 }
1163 1163 public SortedSet<E> headSet(E toElement) {
1164 1164 return new UnmodifiableSortedSet<E>(ss.headSet(toElement));
1165 1165 }
1166 1166 public SortedSet<E> tailSet(E fromElement) {
1167 1167 return new UnmodifiableSortedSet<E>(ss.tailSet(fromElement));
1168 1168 }
1169 1169
1170 1170 public E first() {return ss.first();}
1171 1171 public E last() {return ss.last();}
1172 1172 }
1173 1173
1174 1174 /**
1175 1175 * Returns an unmodifiable view of the specified list. This method allows
1176 1176 * modules to provide users with "read-only" access to internal
1177 1177 * lists. Query operations on the returned list "read through" to the
1178 1178 * specified list, and attempts to modify the returned list, whether
1179 1179 * direct or via its iterator, result in an
1180 1180 * <tt>UnsupportedOperationException</tt>.<p>
1181 1181 *
1182 1182 * The returned list will be serializable if the specified list
1183 1183 * is serializable. Similarly, the returned list will implement
1184 1184 * {@link RandomAccess} if the specified list does.
1185 1185 *
1186 1186 * @param list the list for which an unmodifiable view is to be returned.
1187 1187 * @return an unmodifiable view of the specified list.
1188 1188 */
1189 1189 public static <T> List<T> unmodifiableList(List<? extends T> list) {
1190 1190 return (list instanceof RandomAccess ?
1191 1191 new UnmodifiableRandomAccessList<T>(list) :
1192 1192 new UnmodifiableList<T>(list));
1193 1193 }
1194 1194
1195 1195 /**
1196 1196 * @serial include
1197 1197 */
1198 1198 static class UnmodifiableList<E> extends UnmodifiableCollection<E>
1199 1199 implements List<E> {
1200 1200 private static final long serialVersionUID = -283967356065247728L;
1201 1201 final List<? extends E> list;
1202 1202
1203 1203 UnmodifiableList(List<? extends E> list) {
1204 1204 super(list);
1205 1205 this.list = list;
1206 1206 }
1207 1207
1208 1208 public boolean equals(Object o) {return o == this || list.equals(o);}
1209 1209 public int hashCode() {return list.hashCode();}
1210 1210
1211 1211 public E get(int index) {return list.get(index);}
1212 1212 public E set(int index, E element) {
1213 1213 throw new UnsupportedOperationException();
1214 1214 }
1215 1215 public void add(int index, E element) {
1216 1216 throw new UnsupportedOperationException();
1217 1217 }
1218 1218 public E remove(int index) {
1219 1219 throw new UnsupportedOperationException();
1220 1220 }
1221 1221 public int indexOf(Object o) {return list.indexOf(o);}
1222 1222 public int lastIndexOf(Object o) {return list.lastIndexOf(o);}
1223 1223 public boolean addAll(int index, Collection<? extends E> c) {
1224 1224 throw new UnsupportedOperationException();
1225 1225 }
1226 1226 public ListIterator<E> listIterator() {return listIterator(0);}
1227 1227
1228 1228 public ListIterator<E> listIterator(final int index) {
1229 1229 return new ListIterator<E>() {
1230 1230 private final ListIterator<? extends E> i
1231 1231 = list.listIterator(index);
1232 1232
1233 1233 public boolean hasNext() {return i.hasNext();}
1234 1234 public E next() {return i.next();}
1235 1235 public boolean hasPrevious() {return i.hasPrevious();}
1236 1236 public E previous() {return i.previous();}
1237 1237 public int nextIndex() {return i.nextIndex();}
1238 1238 public int previousIndex() {return i.previousIndex();}
1239 1239
1240 1240 public void remove() {
1241 1241 throw new UnsupportedOperationException();
1242 1242 }
1243 1243 public void set(E e) {
1244 1244 throw new UnsupportedOperationException();
1245 1245 }
1246 1246 public void add(E e) {
1247 1247 throw new UnsupportedOperationException();
1248 1248 }
1249 1249 };
1250 1250 }
1251 1251
1252 1252 public List<E> subList(int fromIndex, int toIndex) {
1253 1253 return new UnmodifiableList<E>(list.subList(fromIndex, toIndex));
1254 1254 }
1255 1255
1256 1256 /**
1257 1257 * UnmodifiableRandomAccessList instances are serialized as
1258 1258 * UnmodifiableList instances to allow them to be deserialized
1259 1259 * in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList).
1260 1260 * This method inverts the transformation. As a beneficial
1261 1261 * side-effect, it also grafts the RandomAccess marker onto
1262 1262 * UnmodifiableList instances that were serialized in pre-1.4 JREs.
1263 1263 *
1264 1264 * Note: Unfortunately, UnmodifiableRandomAccessList instances
1265 1265 * serialized in 1.4.1 and deserialized in 1.4 will become
1266 1266 * UnmodifiableList instances, as this method was missing in 1.4.
1267 1267 */
1268 1268 private Object readResolve() {
1269 1269 return (list instanceof RandomAccess
1270 1270 ? new UnmodifiableRandomAccessList<E>(list)
1271 1271 : this);
1272 1272 }
1273 1273 }
1274 1274
1275 1275 /**
1276 1276 * @serial include
1277 1277 */
1278 1278 static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E>
1279 1279 implements RandomAccess
1280 1280 {
1281 1281 UnmodifiableRandomAccessList(List<? extends E> list) {
1282 1282 super(list);
1283 1283 }
1284 1284
1285 1285 public List<E> subList(int fromIndex, int toIndex) {
1286 1286 return new UnmodifiableRandomAccessList<E>(
1287 1287 list.subList(fromIndex, toIndex));
1288 1288 }
1289 1289
1290 1290 private static final long serialVersionUID = -2542308836966382001L;
1291 1291
1292 1292 /**
1293 1293 * Allows instances to be deserialized in pre-1.4 JREs (which do
1294 1294 * not have UnmodifiableRandomAccessList). UnmodifiableList has
1295 1295 * a readResolve method that inverts this transformation upon
1296 1296 * deserialization.
1297 1297 */
1298 1298 private Object writeReplace() {
1299 1299 return new UnmodifiableList<E>(list);
1300 1300 }
1301 1301 }
1302 1302
1303 1303 /**
1304 1304 * Returns an unmodifiable view of the specified map. This method
1305 1305 * allows modules to provide users with "read-only" access to internal
1306 1306 * maps. Query operations on the returned map "read through"
1307 1307 * to the specified map, and attempts to modify the returned
1308 1308 * map, whether direct or via its collection views, result in an
1309 1309 * <tt>UnsupportedOperationException</tt>.<p>
1310 1310 *
1311 1311 * The returned map will be serializable if the specified map
1312 1312 * is serializable.
1313 1313 *
1314 1314 * @param m the map for which an unmodifiable view is to be returned.
1315 1315 * @return an unmodifiable view of the specified map.
1316 1316 */
1317 1317 public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
1318 1318 return new UnmodifiableMap<K,V>(m);
1319 1319 }
1320 1320
1321 1321 /**
1322 1322 * @serial include
1323 1323 */
1324 1324 private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {
1325 1325 private static final long serialVersionUID = -1034234728574286014L;
1326 1326
1327 1327 private final Map<? extends K, ? extends V> m;
1328 1328
1329 1329 UnmodifiableMap(Map<? extends K, ? extends V> m) {
1330 1330 if (m==null)
1331 1331 throw new NullPointerException();
1332 1332 this.m = m;
1333 1333 }
1334 1334
1335 1335 public int size() {return m.size();}
1336 1336 public boolean isEmpty() {return m.isEmpty();}
1337 1337 public boolean containsKey(Object key) {return m.containsKey(key);}
1338 1338 public boolean containsValue(Object val) {return m.containsValue(val);}
1339 1339 public V get(Object key) {return m.get(key);}
1340 1340
1341 1341 public V put(K key, V value) {
1342 1342 throw new UnsupportedOperationException();
1343 1343 }
1344 1344 public V remove(Object key) {
1345 1345 throw new UnsupportedOperationException();
1346 1346 }
1347 1347 public void putAll(Map<? extends K, ? extends V> m) {
1348 1348 throw new UnsupportedOperationException();
1349 1349 }
1350 1350 public void clear() {
1351 1351 throw new UnsupportedOperationException();
1352 1352 }
1353 1353
1354 1354 private transient Set<K> keySet = null;
1355 1355 private transient Set<Map.Entry<K,V>> entrySet = null;
1356 1356 private transient Collection<V> values = null;
1357 1357
1358 1358 public Set<K> keySet() {
1359 1359 if (keySet==null)
1360 1360 keySet = unmodifiableSet(m.keySet());
1361 1361 return keySet;
1362 1362 }
1363 1363
1364 1364 public Set<Map.Entry<K,V>> entrySet() {
1365 1365 if (entrySet==null)
1366 1366 entrySet = new UnmodifiableEntrySet<K,V>(m.entrySet());
1367 1367 return entrySet;
1368 1368 }
1369 1369
1370 1370 public Collection<V> values() {
1371 1371 if (values==null)
1372 1372 values = unmodifiableCollection(m.values());
1373 1373 return values;
1374 1374 }
1375 1375
1376 1376 public boolean equals(Object o) {return o == this || m.equals(o);}
1377 1377 public int hashCode() {return m.hashCode();}
1378 1378 public String toString() {return m.toString();}
1379 1379
1380 1380 /**
1381 1381 * We need this class in addition to UnmodifiableSet as
1382 1382 * Map.Entries themselves permit modification of the backing Map
1383 1383 * via their setValue operation. This class is subtle: there are
1384 1384 * many possible attacks that must be thwarted.
1385 1385 *
1386 1386 * @serial include
1387 1387 */
1388 1388 static class UnmodifiableEntrySet<K,V>
1389 1389 extends UnmodifiableSet<Map.Entry<K,V>> {
1390 1390 private static final long serialVersionUID = 7854390611657943733L;
1391 1391
1392 1392 UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) {
1393 1393 super((Set)s);
1394 1394 }
1395 1395 public Iterator<Map.Entry<K,V>> iterator() {
1396 1396 return new Iterator<Map.Entry<K,V>>() {
1397 1397 private final Iterator<? extends Map.Entry<? extends K, ? extends V>> i = c.iterator();
1398 1398
1399 1399 public boolean hasNext() {
1400 1400 return i.hasNext();
1401 1401 }
1402 1402 public Map.Entry<K,V> next() {
1403 1403 return new UnmodifiableEntry<K,V>(i.next());
1404 1404 }
1405 1405 public void remove() {
1406 1406 throw new UnsupportedOperationException();
1407 1407 }
1408 1408 };
1409 1409 }
1410 1410
1411 1411 public Object[] toArray() {
1412 1412 Object[] a = c.toArray();
1413 1413 for (int i=0; i<a.length; i++)
1414 1414 a[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)a[i]);
1415 1415 return a;
1416 1416 }
1417 1417
1418 1418 public <T> T[] toArray(T[] a) {
1419 1419 // We don't pass a to c.toArray, to avoid window of
1420 1420 // vulnerability wherein an unscrupulous multithreaded client
1421 1421 // could get his hands on raw (unwrapped) Entries from c.
1422 1422 Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
1423 1423
1424 1424 for (int i=0; i<arr.length; i++)
1425 1425 arr[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)arr[i]);
1426 1426
1427 1427 if (arr.length > a.length)
1428 1428 return (T[])arr;
1429 1429
1430 1430 System.arraycopy(arr, 0, a, 0, arr.length);
1431 1431 if (a.length > arr.length)
1432 1432 a[arr.length] = null;
1433 1433 return a;
1434 1434 }
1435 1435
1436 1436 /**
1437 1437 * This method is overridden to protect the backing set against
1438 1438 * an object with a nefarious equals function that senses
1439 1439 * that the equality-candidate is Map.Entry and calls its
1440 1440 * setValue method.
1441 1441 */
1442 1442 public boolean contains(Object o) {
1443 1443 if (!(o instanceof Map.Entry))
1444 1444 return false;
↓ open down ↓ |
608 lines elided |
↑ open up ↑ |
1445 1445 return c.contains(
1446 1446 new UnmodifiableEntry<Object,Object>((Map.Entry<?,?>) o));
1447 1447 }
1448 1448
1449 1449 /**
1450 1450 * The next two methods are overridden to protect against
1451 1451 * an unscrupulous List whose contains(Object o) method senses
1452 1452 * when o is a Map.Entry, and calls o.setValue.
1453 1453 */
1454 1454 public boolean containsAll(Collection<?> coll) {
1455 - Iterator<?> e = coll.iterator();
1456 - while (e.hasNext())
1457 - if (!contains(e.next())) // Invokes safe contains() above
1455 + Iterator<?> it = coll.iterator();
1456 + while (it.hasNext())
1457 + if (!contains(it.next())) // Invokes safe contains() above
1458 1458 return false;
1459 1459 return true;
1460 1460 }
1461 1461 public boolean equals(Object o) {
1462 1462 if (o == this)
1463 1463 return true;
1464 1464
1465 1465 if (!(o instanceof Set))
1466 1466 return false;
1467 1467 Set s = (Set) o;
1468 1468 if (s.size() != c.size())
1469 1469 return false;
1470 1470 return containsAll(s); // Invokes safe containsAll() above
1471 1471 }
1472 1472
1473 1473 /**
1474 1474 * This "wrapper class" serves two purposes: it prevents
↓ open down ↓ |
7 lines elided |
↑ open up ↑ |
1475 1475 * the client from modifying the backing Map, by short-circuiting
1476 1476 * the setValue method, and it protects the backing Map against
1477 1477 * an ill-behaved Map.Entry that attempts to modify another
1478 1478 * Map Entry when asked to perform an equality check.
1479 1479 */
1480 1480 private static class UnmodifiableEntry<K,V> implements Map.Entry<K,V> {
1481 1481 private Map.Entry<? extends K, ? extends V> e;
1482 1482
1483 1483 UnmodifiableEntry(Map.Entry<? extends K, ? extends V> e) {this.e = e;}
1484 1484
1485 - public K getKey() {return e.getKey();}
1486 - public V getValue() {return e.getValue();}
1485 + public K getKey() {return e.getKey();}
1486 + public V getValue() {return e.getValue();}
1487 1487 public V setValue(V value) {
1488 1488 throw new UnsupportedOperationException();
1489 1489 }
1490 - public int hashCode() {return e.hashCode();}
1490 + public int hashCode() {return e.hashCode();}
1491 1491 public boolean equals(Object o) {
1492 1492 if (!(o instanceof Map.Entry))
1493 1493 return false;
1494 1494 Map.Entry t = (Map.Entry)o;
1495 1495 return eq(e.getKey(), t.getKey()) &&
1496 1496 eq(e.getValue(), t.getValue());
1497 1497 }
1498 - public String toString() {return e.toString();}
1498 + public String toString() {return e.toString();}
1499 1499 }
1500 1500 }
1501 1501 }
1502 1502
1503 1503 /**
1504 1504 * Returns an unmodifiable view of the specified sorted map. This method
1505 1505 * allows modules to provide users with "read-only" access to internal
1506 1506 * sorted maps. Query operations on the returned sorted map "read through"
1507 1507 * to the specified sorted map. Attempts to modify the returned
1508 1508 * sorted map, whether direct, via its collection views, or via its
1509 1509 * <tt>subMap</tt>, <tt>headMap</tt>, or <tt>tailMap</tt> views, result in
1510 1510 * an <tt>UnsupportedOperationException</tt>.<p>
1511 1511 *
1512 1512 * The returned sorted map will be serializable if the specified sorted map
1513 1513 * is serializable.
1514 1514 *
1515 1515 * @param m the sorted map for which an unmodifiable view is to be
1516 1516 * returned.
1517 1517 * @return an unmodifiable view of the specified sorted map.
1518 1518 */
1519 1519 public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {
1520 1520 return new UnmodifiableSortedMap<K,V>(m);
1521 1521 }
1522 1522
1523 1523 /**
1524 1524 * @serial include
1525 1525 */
1526 1526 static class UnmodifiableSortedMap<K,V>
1527 1527 extends UnmodifiableMap<K,V>
1528 1528 implements SortedMap<K,V>, Serializable {
1529 1529 private static final long serialVersionUID = -8806743815996713206L;
1530 1530
1531 1531 private final SortedMap<K, ? extends V> sm;
1532 1532
1533 1533 UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m;}
1534 1534
1535 1535 public Comparator<? super K> comparator() {return sm.comparator();}
1536 1536
1537 1537 public SortedMap<K,V> subMap(K fromKey, K toKey) {
1538 1538 return new UnmodifiableSortedMap<K,V>(sm.subMap(fromKey, toKey));
1539 1539 }
1540 1540 public SortedMap<K,V> headMap(K toKey) {
1541 1541 return new UnmodifiableSortedMap<K,V>(sm.headMap(toKey));
1542 1542 }
1543 1543 public SortedMap<K,V> tailMap(K fromKey) {
1544 1544 return new UnmodifiableSortedMap<K,V>(sm.tailMap(fromKey));
1545 1545 }
1546 1546
1547 1547 public K firstKey() {return sm.firstKey();}
1548 1548 public K lastKey() {return sm.lastKey();}
1549 1549 }
1550 1550
1551 1551
1552 1552 // Synch Wrappers
1553 1553
1554 1554 /**
↓ open down ↓ |
46 lines elided |
↑ open up ↑ |
1555 1555 * Returns a synchronized (thread-safe) collection backed by the specified
1556 1556 * collection. In order to guarantee serial access, it is critical that
1557 1557 * <strong>all</strong> access to the backing collection is accomplished
1558 1558 * through the returned collection.<p>
1559 1559 *
1560 1560 * It is imperative that the user manually synchronize on the returned
1561 1561 * collection when iterating over it:
1562 1562 * <pre>
1563 1563 * Collection c = Collections.synchronizedCollection(myCollection);
1564 1564 * ...
1565 - * synchronized(c) {
1565 + * synchronized (c) {
1566 1566 * Iterator i = c.iterator(); // Must be in the synchronized block
1567 1567 * while (i.hasNext())
1568 1568 * foo(i.next());
1569 1569 * }
1570 1570 * </pre>
1571 1571 * Failure to follow this advice may result in non-deterministic behavior.
1572 1572 *
1573 1573 * <p>The returned collection does <i>not</i> pass the <tt>hashCode</tt>
1574 1574 * and <tt>equals</tt> operations through to the backing collection, but
1575 1575 * relies on <tt>Object</tt>'s equals and hashCode methods. This is
1576 1576 * necessary to preserve the contracts of these operations in the case
1577 1577 * that the backing collection is a set or a list.<p>
1578 1578 *
1579 1579 * The returned collection will be serializable if the specified collection
1580 1580 * is serializable.
1581 1581 *
1582 1582 * @param c the collection to be "wrapped" in a synchronized collection.
1583 1583 * @return a synchronized view of the specified collection.
1584 1584 */
1585 1585 public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
1586 1586 return new SynchronizedCollection<T>(c);
1587 1587 }
1588 1588
1589 1589 static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {
1590 1590 return new SynchronizedCollection<T>(c, mutex);
1591 1591 }
1592 1592
1593 1593 /**
1594 1594 * @serial include
1595 1595 */
1596 1596 static class SynchronizedCollection<E> implements Collection<E>, Serializable {
1597 1597 private static final long serialVersionUID = 3053995032091335093L;
1598 1598
1599 1599 final Collection<E> c; // Backing Collection
1600 1600 final Object mutex; // Object on which to synchronize
1601 1601
1602 1602 SynchronizedCollection(Collection<E> c) {
1603 1603 if (c==null)
↓ open down ↓ |
28 lines elided |
↑ open up ↑ |
1604 1604 throw new NullPointerException();
1605 1605 this.c = c;
1606 1606 mutex = this;
1607 1607 }
1608 1608 SynchronizedCollection(Collection<E> c, Object mutex) {
1609 1609 this.c = c;
1610 1610 this.mutex = mutex;
1611 1611 }
1612 1612
1613 1613 public int size() {
1614 - synchronized(mutex) {return c.size();}
1614 + synchronized (mutex) {return c.size();}
1615 1615 }
1616 1616 public boolean isEmpty() {
1617 - synchronized(mutex) {return c.isEmpty();}
1617 + synchronized (mutex) {return c.isEmpty();}
1618 1618 }
1619 1619 public boolean contains(Object o) {
1620 - synchronized(mutex) {return c.contains(o);}
1620 + synchronized (mutex) {return c.contains(o);}
1621 1621 }
1622 1622 public Object[] toArray() {
1623 - synchronized(mutex) {return c.toArray();}
1623 + synchronized (mutex) {return c.toArray();}
1624 1624 }
1625 1625 public <T> T[] toArray(T[] a) {
1626 - synchronized(mutex) {return c.toArray(a);}
1626 + synchronized (mutex) {return c.toArray(a);}
1627 1627 }
1628 1628
1629 1629 public Iterator<E> iterator() {
1630 1630 return c.iterator(); // Must be manually synched by user!
1631 1631 }
1632 1632
1633 1633 public boolean add(E e) {
1634 - synchronized(mutex) {return c.add(e);}
1634 + synchronized (mutex) {return c.add(e);}
1635 1635 }
1636 1636 public boolean remove(Object o) {
1637 - synchronized(mutex) {return c.remove(o);}
1637 + synchronized (mutex) {return c.remove(o);}
1638 1638 }
1639 1639
1640 1640 public boolean containsAll(Collection<?> coll) {
1641 - synchronized(mutex) {return c.containsAll(coll);}
1641 + synchronized (mutex) {return c.containsAll(coll);}
1642 1642 }
1643 1643 public boolean addAll(Collection<? extends E> coll) {
1644 - synchronized(mutex) {return c.addAll(coll);}
1644 + synchronized (mutex) {return c.addAll(coll);}
1645 1645 }
1646 1646 public boolean removeAll(Collection<?> coll) {
1647 - synchronized(mutex) {return c.removeAll(coll);}
1647 + synchronized (mutex) {return c.removeAll(coll);}
1648 1648 }
1649 1649 public boolean retainAll(Collection<?> coll) {
1650 - synchronized(mutex) {return c.retainAll(coll);}
1650 + synchronized (mutex) {return c.retainAll(coll);}
1651 1651 }
1652 1652 public void clear() {
1653 - synchronized(mutex) {c.clear();}
1653 + synchronized (mutex) {c.clear();}
1654 1654 }
1655 1655 public String toString() {
1656 - synchronized(mutex) {return c.toString();}
1656 + synchronized (mutex) {return c.toString();}
1657 1657 }
1658 1658 private void writeObject(ObjectOutputStream s) throws IOException {
1659 - synchronized(mutex) {s.defaultWriteObject();}
1659 + synchronized (mutex) {s.defaultWriteObject();}
1660 1660 }
1661 1661 }
1662 1662
1663 1663 /**
1664 1664 * Returns a synchronized (thread-safe) set backed by the specified
1665 1665 * set. In order to guarantee serial access, it is critical that
1666 1666 * <strong>all</strong> access to the backing set is accomplished
1667 1667 * through the returned set.<p>
1668 1668 *
1669 1669 * It is imperative that the user manually synchronize on the returned
1670 1670 * set when iterating over it:
1671 1671 * <pre>
1672 1672 * Set s = Collections.synchronizedSet(new HashSet());
1673 1673 * ...
1674 - * synchronized(s) {
1674 + * synchronized (s) {
1675 1675 * Iterator i = s.iterator(); // Must be in the synchronized block
1676 1676 * while (i.hasNext())
1677 1677 * foo(i.next());
1678 1678 * }
1679 1679 * </pre>
1680 1680 * Failure to follow this advice may result in non-deterministic behavior.
1681 1681 *
1682 1682 * <p>The returned set will be serializable if the specified set is
1683 1683 * serializable.
1684 1684 *
1685 1685 * @param s the set to be "wrapped" in a synchronized set.
1686 1686 * @return a synchronized view of the specified set.
1687 1687 */
1688 1688 public static <T> Set<T> synchronizedSet(Set<T> s) {
1689 1689 return new SynchronizedSet<T>(s);
1690 1690 }
1691 1691
1692 1692 static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {
1693 1693 return new SynchronizedSet<T>(s, mutex);
1694 1694 }
1695 1695
1696 1696 /**
1697 1697 * @serial include
1698 1698 */
1699 1699 static class SynchronizedSet<E>
1700 1700 extends SynchronizedCollection<E>
1701 1701 implements Set<E> {
↓ open down ↓ |
17 lines elided |
↑ open up ↑ |
1702 1702 private static final long serialVersionUID = 487447009682186044L;
1703 1703
1704 1704 SynchronizedSet(Set<E> s) {
1705 1705 super(s);
1706 1706 }
1707 1707 SynchronizedSet(Set<E> s, Object mutex) {
1708 1708 super(s, mutex);
1709 1709 }
1710 1710
1711 1711 public boolean equals(Object o) {
1712 - synchronized(mutex) {return c.equals(o);}
1712 + synchronized (mutex) {return c.equals(o);}
1713 1713 }
1714 1714 public int hashCode() {
1715 - synchronized(mutex) {return c.hashCode();}
1715 + synchronized (mutex) {return c.hashCode();}
1716 1716 }
1717 1717 }
1718 1718
1719 1719 /**
1720 1720 * Returns a synchronized (thread-safe) sorted set backed by the specified
1721 1721 * sorted set. In order to guarantee serial access, it is critical that
1722 1722 * <strong>all</strong> access to the backing sorted set is accomplished
1723 1723 * through the returned sorted set (or its views).<p>
1724 1724 *
1725 1725 * It is imperative that the user manually synchronize on the returned
1726 1726 * sorted set when iterating over it or any of its <tt>subSet</tt>,
1727 1727 * <tt>headSet</tt>, or <tt>tailSet</tt> views.
1728 1728 * <pre>
1729 1729 * SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
1730 1730 * ...
1731 - * synchronized(s) {
1731 + * synchronized (s) {
1732 1732 * Iterator i = s.iterator(); // Must be in the synchronized block
1733 1733 * while (i.hasNext())
1734 1734 * foo(i.next());
1735 1735 * }
1736 1736 * </pre>
1737 1737 * or:
1738 1738 * <pre>
1739 1739 * SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
1740 1740 * SortedSet s2 = s.headSet(foo);
1741 1741 * ...
1742 - * synchronized(s) { // Note: s, not s2!!!
1742 + * synchronized (s) { // Note: s, not s2!!!
1743 1743 * Iterator i = s2.iterator(); // Must be in the synchronized block
1744 1744 * while (i.hasNext())
1745 1745 * foo(i.next());
1746 1746 * }
1747 1747 * </pre>
1748 1748 * Failure to follow this advice may result in non-deterministic behavior.
1749 1749 *
1750 1750 * <p>The returned sorted set will be serializable if the specified
1751 1751 * sorted set is serializable.
1752 1752 *
1753 1753 * @param s the sorted set to be "wrapped" in a synchronized sorted set.
1754 1754 * @return a synchronized view of the specified sorted set.
1755 1755 */
1756 1756 public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) {
1757 1757 return new SynchronizedSortedSet<T>(s);
1758 1758 }
↓ open down ↓ |
6 lines elided |
↑ open up ↑ |
1759 1759
1760 1760 /**
1761 1761 * @serial include
1762 1762 */
1763 1763 static class SynchronizedSortedSet<E>
1764 1764 extends SynchronizedSet<E>
1765 1765 implements SortedSet<E>
1766 1766 {
1767 1767 private static final long serialVersionUID = 8695801310862127406L;
1768 1768
1769 - final private SortedSet<E> ss;
1769 + private final SortedSet<E> ss;
1770 1770
1771 1771 SynchronizedSortedSet(SortedSet<E> s) {
1772 1772 super(s);
1773 1773 ss = s;
1774 1774 }
1775 1775 SynchronizedSortedSet(SortedSet<E> s, Object mutex) {
1776 1776 super(s, mutex);
1777 1777 ss = s;
1778 1778 }
1779 1779
1780 1780 public Comparator<? super E> comparator() {
1781 - synchronized(mutex) {return ss.comparator();}
1781 + synchronized (mutex) {return ss.comparator();}
1782 1782 }
1783 1783
1784 1784 public SortedSet<E> subSet(E fromElement, E toElement) {
1785 - synchronized(mutex) {
1785 + synchronized (mutex) {
1786 1786 return new SynchronizedSortedSet<E>(
1787 1787 ss.subSet(fromElement, toElement), mutex);
1788 1788 }
1789 1789 }
1790 1790 public SortedSet<E> headSet(E toElement) {
1791 - synchronized(mutex) {
1791 + synchronized (mutex) {
1792 1792 return new SynchronizedSortedSet<E>(ss.headSet(toElement), mutex);
1793 1793 }
1794 1794 }
1795 1795 public SortedSet<E> tailSet(E fromElement) {
1796 - synchronized(mutex) {
1796 + synchronized (mutex) {
1797 1797 return new SynchronizedSortedSet<E>(ss.tailSet(fromElement),mutex);
1798 1798 }
1799 1799 }
1800 1800
1801 1801 public E first() {
1802 - synchronized(mutex) {return ss.first();}
1802 + synchronized (mutex) {return ss.first();}
1803 1803 }
1804 1804 public E last() {
1805 - synchronized(mutex) {return ss.last();}
1805 + synchronized (mutex) {return ss.last();}
1806 1806 }
1807 1807 }
1808 1808
1809 1809 /**
1810 1810 * Returns a synchronized (thread-safe) list backed by the specified
1811 1811 * list. In order to guarantee serial access, it is critical that
1812 1812 * <strong>all</strong> access to the backing list is accomplished
1813 1813 * through the returned list.<p>
1814 1814 *
1815 1815 * It is imperative that the user manually synchronize on the returned
1816 1816 * list when iterating over it:
1817 1817 * <pre>
1818 1818 * List list = Collections.synchronizedList(new ArrayList());
1819 1819 * ...
1820 - * synchronized(list) {
1820 + * synchronized (list) {
1821 1821 * Iterator i = list.iterator(); // Must be in synchronized block
1822 1822 * while (i.hasNext())
1823 1823 * foo(i.next());
1824 1824 * }
1825 1825 * </pre>
1826 1826 * Failure to follow this advice may result in non-deterministic behavior.
1827 1827 *
1828 1828 * <p>The returned list will be serializable if the specified list is
1829 1829 * serializable.
1830 1830 *
1831 1831 * @param list the list to be "wrapped" in a synchronized list.
1832 1832 * @return a synchronized view of the specified list.
1833 1833 */
1834 1834 public static <T> List<T> synchronizedList(List<T> list) {
1835 1835 return (list instanceof RandomAccess ?
1836 1836 new SynchronizedRandomAccessList<T>(list) :
1837 1837 new SynchronizedList<T>(list));
1838 1838 }
1839 1839
1840 1840 static <T> List<T> synchronizedList(List<T> list, Object mutex) {
1841 1841 return (list instanceof RandomAccess ?
1842 1842 new SynchronizedRandomAccessList<T>(list, mutex) :
1843 1843 new SynchronizedList<T>(list, mutex));
1844 1844 }
1845 1845
1846 1846 /**
1847 1847 * @serial include
1848 1848 */
1849 1849 static class SynchronizedList<E>
1850 1850 extends SynchronizedCollection<E>
1851 1851 implements List<E> {
1852 1852 private static final long serialVersionUID = -7754090372962971524L;
1853 1853
1854 1854 final List<E> list;
1855 1855
↓ open down ↓ |
25 lines elided |
↑ open up ↑ |
1856 1856 SynchronizedList(List<E> list) {
1857 1857 super(list);
1858 1858 this.list = list;
1859 1859 }
1860 1860 SynchronizedList(List<E> list, Object mutex) {
1861 1861 super(list, mutex);
1862 1862 this.list = list;
1863 1863 }
1864 1864
1865 1865 public boolean equals(Object o) {
1866 - synchronized(mutex) {return list.equals(o);}
1866 + synchronized (mutex) {return list.equals(o);}
1867 1867 }
1868 1868 public int hashCode() {
1869 - synchronized(mutex) {return list.hashCode();}
1869 + synchronized (mutex) {return list.hashCode();}
1870 1870 }
1871 1871
1872 1872 public E get(int index) {
1873 - synchronized(mutex) {return list.get(index);}
1873 + synchronized (mutex) {return list.get(index);}
1874 1874 }
1875 1875 public E set(int index, E element) {
1876 - synchronized(mutex) {return list.set(index, element);}
1876 + synchronized (mutex) {return list.set(index, element);}
1877 1877 }
1878 1878 public void add(int index, E element) {
1879 - synchronized(mutex) {list.add(index, element);}
1879 + synchronized (mutex) {list.add(index, element);}
1880 1880 }
1881 1881 public E remove(int index) {
1882 - synchronized(mutex) {return list.remove(index);}
1882 + synchronized (mutex) {return list.remove(index);}
1883 1883 }
1884 1884
1885 1885 public int indexOf(Object o) {
1886 - synchronized(mutex) {return list.indexOf(o);}
1886 + synchronized (mutex) {return list.indexOf(o);}
1887 1887 }
1888 1888 public int lastIndexOf(Object o) {
1889 - synchronized(mutex) {return list.lastIndexOf(o);}
1889 + synchronized (mutex) {return list.lastIndexOf(o);}
1890 1890 }
1891 1891
1892 1892 public boolean addAll(int index, Collection<? extends E> c) {
1893 - synchronized(mutex) {return list.addAll(index, c);}
1893 + synchronized (mutex) {return list.addAll(index, c);}
1894 1894 }
1895 1895
1896 1896 public ListIterator<E> listIterator() {
1897 1897 return list.listIterator(); // Must be manually synched by user
1898 1898 }
1899 1899
1900 1900 public ListIterator<E> listIterator(int index) {
1901 1901 return list.listIterator(index); // Must be manually synched by user
1902 1902 }
1903 1903
1904 1904 public List<E> subList(int fromIndex, int toIndex) {
1905 - synchronized(mutex) {
1905 + synchronized (mutex) {
1906 1906 return new SynchronizedList<E>(list.subList(fromIndex, toIndex),
1907 1907 mutex);
1908 1908 }
1909 1909 }
1910 1910
1911 1911 /**
1912 1912 * SynchronizedRandomAccessList instances are serialized as
1913 1913 * SynchronizedList instances to allow them to be deserialized
1914 1914 * in pre-1.4 JREs (which do not have SynchronizedRandomAccessList).
1915 1915 * This method inverts the transformation. As a beneficial
1916 1916 * side-effect, it also grafts the RandomAccess marker onto
1917 1917 * SynchronizedList instances that were serialized in pre-1.4 JREs.
1918 1918 *
1919 1919 * Note: Unfortunately, SynchronizedRandomAccessList instances
1920 1920 * serialized in 1.4.1 and deserialized in 1.4 will become
1921 1921 * SynchronizedList instances, as this method was missing in 1.4.
1922 1922 */
1923 1923 private Object readResolve() {
1924 1924 return (list instanceof RandomAccess
1925 1925 ? new SynchronizedRandomAccessList<E>(list)
1926 1926 : this);
1927 1927 }
1928 1928 }
1929 1929
1930 1930 /**
1931 1931 * @serial include
1932 1932 */
1933 1933 static class SynchronizedRandomAccessList<E>
1934 1934 extends SynchronizedList<E>
1935 1935 implements RandomAccess {
↓ open down ↓ |
20 lines elided |
↑ open up ↑ |
1936 1936
1937 1937 SynchronizedRandomAccessList(List<E> list) {
1938 1938 super(list);
1939 1939 }
1940 1940
1941 1941 SynchronizedRandomAccessList(List<E> list, Object mutex) {
1942 1942 super(list, mutex);
1943 1943 }
1944 1944
1945 1945 public List<E> subList(int fromIndex, int toIndex) {
1946 - synchronized(mutex) {
1946 + synchronized (mutex) {
1947 1947 return new SynchronizedRandomAccessList<E>(
1948 1948 list.subList(fromIndex, toIndex), mutex);
1949 1949 }
1950 1950 }
1951 1951
1952 1952 private static final long serialVersionUID = 1530674583602358482L;
1953 1953
1954 1954 /**
1955 1955 * Allows instances to be deserialized in pre-1.4 JREs (which do
1956 1956 * not have SynchronizedRandomAccessList). SynchronizedList has
1957 1957 * a readResolve method that inverts this transformation upon
1958 1958 * deserialization.
1959 1959 */
1960 1960 private Object writeReplace() {
1961 1961 return new SynchronizedList<E>(list);
1962 1962 }
1963 1963 }
1964 1964
1965 1965 /**
1966 1966 * Returns a synchronized (thread-safe) map backed by the specified
1967 1967 * map. In order to guarantee serial access, it is critical that
↓ open down ↓ |
11 lines elided |
↑ open up ↑ |
1968 1968 * <strong>all</strong> access to the backing map is accomplished
1969 1969 * through the returned map.<p>
1970 1970 *
1971 1971 * It is imperative that the user manually synchronize on the returned
1972 1972 * map when iterating over any of its collection views:
1973 1973 * <pre>
1974 1974 * Map m = Collections.synchronizedMap(new HashMap());
1975 1975 * ...
1976 1976 * Set s = m.keySet(); // Needn't be in synchronized block
1977 1977 * ...
1978 - * synchronized(m) { // Synchronizing on m, not s!
1978 + * synchronized (m) { // Synchronizing on m, not s!
1979 1979 * Iterator i = s.iterator(); // Must be in synchronized block
1980 1980 * while (i.hasNext())
1981 1981 * foo(i.next());
1982 1982 * }
1983 1983 * </pre>
1984 1984 * Failure to follow this advice may result in non-deterministic behavior.
1985 1985 *
1986 1986 * <p>The returned map will be serializable if the specified map is
1987 1987 * serializable.
1988 1988 *
1989 1989 * @param m the map to be "wrapped" in a synchronized map.
1990 1990 * @return a synchronized view of the specified map.
1991 1991 */
1992 1992 public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
1993 1993 return new SynchronizedMap<K,V>(m);
1994 1994 }
1995 1995
1996 1996 /**
1997 1997 * @serial include
1998 1998 */
1999 1999 private static class SynchronizedMap<K,V>
2000 2000 implements Map<K,V>, Serializable {
2001 2001 private static final long serialVersionUID = 1978198479659022715L;
2002 2002
2003 2003 private final Map<K,V> m; // Backing Map
2004 2004 final Object mutex; // Object on which to synchronize
2005 2005
2006 2006 SynchronizedMap(Map<K,V> m) {
2007 2007 if (m==null)
2008 2008 throw new NullPointerException();
↓ open down ↓ |
20 lines elided |
↑ open up ↑ |
2009 2009 this.m = m;
2010 2010 mutex = this;
2011 2011 }
2012 2012
2013 2013 SynchronizedMap(Map<K,V> m, Object mutex) {
2014 2014 this.m = m;
2015 2015 this.mutex = mutex;
2016 2016 }
2017 2017
2018 2018 public int size() {
2019 - synchronized(mutex) {return m.size();}
2019 + synchronized (mutex) {return m.size();}
2020 2020 }
2021 2021 public boolean isEmpty() {
2022 - synchronized(mutex) {return m.isEmpty();}
2022 + synchronized (mutex) {return m.isEmpty();}
2023 2023 }
2024 2024 public boolean containsKey(Object key) {
2025 - synchronized(mutex) {return m.containsKey(key);}
2025 + synchronized (mutex) {return m.containsKey(key);}
2026 2026 }
2027 2027 public boolean containsValue(Object value) {
2028 - synchronized(mutex) {return m.containsValue(value);}
2028 + synchronized (mutex) {return m.containsValue(value);}
2029 2029 }
2030 2030 public V get(Object key) {
2031 - synchronized(mutex) {return m.get(key);}
2031 + synchronized (mutex) {return m.get(key);}
2032 2032 }
2033 2033
2034 2034 public V put(K key, V value) {
2035 - synchronized(mutex) {return m.put(key, value);}
2035 + synchronized (mutex) {return m.put(key, value);}
2036 2036 }
2037 2037 public V remove(Object key) {
2038 - synchronized(mutex) {return m.remove(key);}
2038 + synchronized (mutex) {return m.remove(key);}
2039 2039 }
2040 2040 public void putAll(Map<? extends K, ? extends V> map) {
2041 - synchronized(mutex) {m.putAll(map);}
2041 + synchronized (mutex) {m.putAll(map);}
2042 2042 }
2043 2043 public void clear() {
2044 - synchronized(mutex) {m.clear();}
2044 + synchronized (mutex) {m.clear();}
2045 2045 }
2046 2046
2047 2047 private transient Set<K> keySet = null;
2048 2048 private transient Set<Map.Entry<K,V>> entrySet = null;
2049 2049 private transient Collection<V> values = null;
2050 2050
2051 2051 public Set<K> keySet() {
2052 - synchronized(mutex) {
2052 + synchronized (mutex) {
2053 2053 if (keySet==null)
2054 2054 keySet = new SynchronizedSet<K>(m.keySet(), mutex);
2055 2055 return keySet;
2056 2056 }
2057 2057 }
2058 2058
2059 2059 public Set<Map.Entry<K,V>> entrySet() {
2060 - synchronized(mutex) {
2060 + synchronized (mutex) {
2061 2061 if (entrySet==null)
2062 2062 entrySet = new SynchronizedSet<Map.Entry<K,V>>(m.entrySet(), mutex);
2063 2063 return entrySet;
2064 2064 }
2065 2065 }
2066 2066
2067 2067 public Collection<V> values() {
2068 - synchronized(mutex) {
2068 + synchronized (mutex) {
2069 2069 if (values==null)
2070 2070 values = new SynchronizedCollection<V>(m.values(), mutex);
2071 2071 return values;
2072 2072 }
2073 2073 }
2074 2074
2075 2075 public boolean equals(Object o) {
2076 - synchronized(mutex) {return m.equals(o);}
2076 + synchronized (mutex) {return m.equals(o);}
2077 2077 }
2078 2078 public int hashCode() {
2079 - synchronized(mutex) {return m.hashCode();}
2079 + synchronized (mutex) {return m.hashCode();}
2080 2080 }
2081 2081 public String toString() {
2082 - synchronized(mutex) {return m.toString();}
2082 + synchronized (mutex) {return m.toString();}
2083 2083 }
2084 2084 private void writeObject(ObjectOutputStream s) throws IOException {
2085 - synchronized(mutex) {s.defaultWriteObject();}
2085 + synchronized (mutex) {s.defaultWriteObject();}
2086 2086 }
2087 2087 }
2088 2088
2089 2089 /**
2090 2090 * Returns a synchronized (thread-safe) sorted map backed by the specified
2091 2091 * sorted map. In order to guarantee serial access, it is critical that
2092 2092 * <strong>all</strong> access to the backing sorted map is accomplished
2093 2093 * through the returned sorted map (or its views).<p>
2094 2094 *
2095 2095 * It is imperative that the user manually synchronize on the returned
2096 2096 * sorted map when iterating over any of its collection views, or the
2097 2097 * collections views of any of its <tt>subMap</tt>, <tt>headMap</tt> or
2098 2098 * <tt>tailMap</tt> views.
2099 2099 * <pre>
2100 2100 * SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2101 2101 * ...
2102 2102 * Set s = m.keySet(); // Needn't be in synchronized block
2103 2103 * ...
2104 - * synchronized(m) { // Synchronizing on m, not s!
2104 + * synchronized (m) { // Synchronizing on m, not s!
2105 2105 * Iterator i = s.iterator(); // Must be in synchronized block
2106 2106 * while (i.hasNext())
2107 2107 * foo(i.next());
2108 2108 * }
2109 2109 * </pre>
2110 2110 * or:
2111 2111 * <pre>
2112 2112 * SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2113 2113 * SortedMap m2 = m.subMap(foo, bar);
2114 2114 * ...
2115 2115 * Set s2 = m2.keySet(); // Needn't be in synchronized block
2116 2116 * ...
2117 - * synchronized(m) { // Synchronizing on m, not m2 or s2!
2117 + * synchronized (m) { // Synchronizing on m, not m2 or s2!
2118 2118 * Iterator i = s.iterator(); // Must be in synchronized block
2119 2119 * while (i.hasNext())
2120 2120 * foo(i.next());
2121 2121 * }
2122 2122 * </pre>
2123 2123 * Failure to follow this advice may result in non-deterministic behavior.
2124 2124 *
2125 2125 * <p>The returned sorted map will be serializable if the specified
2126 2126 * sorted map is serializable.
2127 2127 *
2128 2128 * @param m the sorted map to be "wrapped" in a synchronized sorted map.
2129 2129 * @return a synchronized view of the specified sorted map.
2130 2130 */
2131 2131 public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {
2132 2132 return new SynchronizedSortedMap<K,V>(m);
2133 2133 }
2134 2134
2135 2135
2136 2136 /**
2137 2137 * @serial include
2138 2138 */
2139 2139 static class SynchronizedSortedMap<K,V>
2140 2140 extends SynchronizedMap<K,V>
2141 2141 implements SortedMap<K,V>
2142 2142 {
2143 2143 private static final long serialVersionUID = -8798146769416483793L;
2144 2144
2145 2145 private final SortedMap<K,V> sm;
2146 2146
↓ open down ↓ |
19 lines elided |
↑ open up ↑ |
2147 2147 SynchronizedSortedMap(SortedMap<K,V> m) {
2148 2148 super(m);
2149 2149 sm = m;
2150 2150 }
2151 2151 SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) {
2152 2152 super(m, mutex);
2153 2153 sm = m;
2154 2154 }
2155 2155
2156 2156 public Comparator<? super K> comparator() {
2157 - synchronized(mutex) {return sm.comparator();}
2157 + synchronized (mutex) {return sm.comparator();}
2158 2158 }
2159 2159
2160 2160 public SortedMap<K,V> subMap(K fromKey, K toKey) {
2161 - synchronized(mutex) {
2161 + synchronized (mutex) {
2162 2162 return new SynchronizedSortedMap<K,V>(
2163 2163 sm.subMap(fromKey, toKey), mutex);
2164 2164 }
2165 2165 }
2166 2166 public SortedMap<K,V> headMap(K toKey) {
2167 - synchronized(mutex) {
2167 + synchronized (mutex) {
2168 2168 return new SynchronizedSortedMap<K,V>(sm.headMap(toKey), mutex);
2169 2169 }
2170 2170 }
2171 2171 public SortedMap<K,V> tailMap(K fromKey) {
2172 - synchronized(mutex) {
2172 + synchronized (mutex) {
2173 2173 return new SynchronizedSortedMap<K,V>(sm.tailMap(fromKey),mutex);
2174 2174 }
2175 2175 }
2176 2176
2177 2177 public K firstKey() {
2178 - synchronized(mutex) {return sm.firstKey();}
2178 + synchronized (mutex) {return sm.firstKey();}
2179 2179 }
2180 2180 public K lastKey() {
2181 - synchronized(mutex) {return sm.lastKey();}
2181 + synchronized (mutex) {return sm.lastKey();}
2182 2182 }
2183 2183 }
2184 2184
2185 2185 // Dynamically typesafe collection wrappers
2186 2186
2187 2187 /**
2188 2188 * Returns a dynamically typesafe view of the specified collection.
2189 2189 * Any attempt to insert an element of the wrong type will result in an
2190 2190 * immediate {@link ClassCastException}. Assuming a collection
2191 2191 * contains no incorrectly typed elements prior to the time a
2192 2192 * dynamically typesafe view is generated, and that all subsequent
2193 2193 * access to the collection takes place through the view, it is
2194 2194 * <i>guaranteed</i> that the collection cannot contain an incorrectly
2195 2195 * typed element.
2196 2196 *
2197 2197 * <p>The generics mechanism in the language provides compile-time
2198 2198 * (static) type checking, but it is possible to defeat this mechanism
2199 2199 * with unchecked casts. Usually this is not a problem, as the compiler
2200 2200 * issues warnings on all such unchecked operations. There are, however,
2201 2201 * times when static type checking alone is not sufficient. For example,
2202 2202 * suppose a collection is passed to a third-party library and it is
2203 2203 * imperative that the library code not corrupt the collection by
2204 2204 * inserting an element of the wrong type.
2205 2205 *
2206 2206 * <p>Another use of dynamically typesafe views is debugging. Suppose a
2207 2207 * program fails with a {@code ClassCastException}, indicating that an
2208 2208 * incorrectly typed element was put into a parameterized collection.
2209 2209 * Unfortunately, the exception can occur at any time after the erroneous
2210 2210 * element is inserted, so it typically provides little or no information
2211 2211 * as to the real source of the problem. If the problem is reproducible,
2212 2212 * one can quickly determine its source by temporarily modifying the
2213 2213 * program to wrap the collection with a dynamically typesafe view.
2214 2214 * For example, this declaration:
2215 2215 * <pre> {@code
2216 2216 * Collection<String> c = new HashSet<String>();
2217 2217 * }</pre>
2218 2218 * may be replaced temporarily by this one:
2219 2219 * <pre> {@code
2220 2220 * Collection<String> c = Collections.checkedCollection(
2221 2221 * new HashSet<String>(), String.class);
2222 2222 * }</pre>
2223 2223 * Running the program again will cause it to fail at the point where
2224 2224 * an incorrectly typed element is inserted into the collection, clearly
2225 2225 * identifying the source of the problem. Once the problem is fixed, the
2226 2226 * modified declaration may be reverted back to the original.
2227 2227 *
2228 2228 * <p>The returned collection does <i>not</i> pass the hashCode and equals
2229 2229 * operations through to the backing collection, but relies on
2230 2230 * {@code Object}'s {@code equals} and {@code hashCode} methods. This
2231 2231 * is necessary to preserve the contracts of these operations in the case
2232 2232 * that the backing collection is a set or a list.
2233 2233 *
2234 2234 * <p>The returned collection will be serializable if the specified
2235 2235 * collection is serializable.
2236 2236 *
2237 2237 * <p>Since {@code null} is considered to be a value of any reference
2238 2238 * type, the returned collection permits insertion of null elements
2239 2239 * whenever the backing collection does.
2240 2240 *
2241 2241 * @param c the collection for which a dynamically typesafe view is to be
2242 2242 * returned
2243 2243 * @param type the type of element that {@code c} is permitted to hold
2244 2244 * @return a dynamically typesafe view of the specified collection
2245 2245 * @since 1.5
2246 2246 */
2247 2247 public static <E> Collection<E> checkedCollection(Collection<E> c,
2248 2248 Class<E> type) {
2249 2249 return new CheckedCollection<E>(c, type);
2250 2250 }
2251 2251
2252 2252 @SuppressWarnings("unchecked")
2253 2253 static <T> T[] zeroLengthArray(Class<T> type) {
2254 2254 return (T[]) Array.newInstance(type, 0);
2255 2255 }
2256 2256
2257 2257 /**
2258 2258 * @serial include
2259 2259 */
2260 2260 static class CheckedCollection<E> implements Collection<E>, Serializable {
2261 2261 private static final long serialVersionUID = 1578914078182001775L;
2262 2262
2263 2263 final Collection<E> c;
2264 2264 final Class<E> type;
2265 2265
2266 2266 void typeCheck(Object o) {
2267 2267 if (o != null && !type.isInstance(o))
2268 2268 throw new ClassCastException(badElementMsg(o));
2269 2269 }
2270 2270
2271 2271 private String badElementMsg(Object o) {
2272 2272 return "Attempt to insert " + o.getClass() +
2273 2273 " element into collection with element type " + type;
2274 2274 }
2275 2275
2276 2276 CheckedCollection(Collection<E> c, Class<E> type) {
2277 2277 if (c==null || type == null)
2278 2278 throw new NullPointerException();
2279 2279 this.c = c;
2280 2280 this.type = type;
2281 2281 }
2282 2282
2283 2283 public int size() { return c.size(); }
2284 2284 public boolean isEmpty() { return c.isEmpty(); }
2285 2285 public boolean contains(Object o) { return c.contains(o); }
2286 2286 public Object[] toArray() { return c.toArray(); }
2287 2287 public <T> T[] toArray(T[] a) { return c.toArray(a); }
2288 2288 public String toString() { return c.toString(); }
2289 2289 public boolean remove(Object o) { return c.remove(o); }
2290 2290 public void clear() { c.clear(); }
2291 2291
2292 2292 public boolean containsAll(Collection<?> coll) {
2293 2293 return c.containsAll(coll);
2294 2294 }
2295 2295 public boolean removeAll(Collection<?> coll) {
2296 2296 return c.removeAll(coll);
2297 2297 }
2298 2298 public boolean retainAll(Collection<?> coll) {
2299 2299 return c.retainAll(coll);
2300 2300 }
2301 2301
2302 2302 public Iterator<E> iterator() {
2303 2303 final Iterator<E> it = c.iterator();
2304 2304 return new Iterator<E>() {
2305 2305 public boolean hasNext() { return it.hasNext(); }
2306 2306 public E next() { return it.next(); }
2307 2307 public void remove() { it.remove(); }};
2308 2308 }
2309 2309
2310 2310 public boolean add(E e) {
2311 2311 typeCheck(e);
2312 2312 return c.add(e);
2313 2313 }
2314 2314
2315 2315 private E[] zeroLengthElementArray = null; // Lazily initialized
2316 2316
2317 2317 private E[] zeroLengthElementArray() {
2318 2318 return zeroLengthElementArray != null ? zeroLengthElementArray :
2319 2319 (zeroLengthElementArray = zeroLengthArray(type));
2320 2320 }
2321 2321
2322 2322 @SuppressWarnings("unchecked")
2323 2323 Collection<E> checkedCopyOf(Collection<? extends E> coll) {
2324 2324 Object[] a = null;
2325 2325 try {
2326 2326 E[] z = zeroLengthElementArray();
2327 2327 a = coll.toArray(z);
2328 2328 // Defend against coll violating the toArray contract
2329 2329 if (a.getClass() != z.getClass())
2330 2330 a = Arrays.copyOf(a, a.length, z.getClass());
2331 2331 } catch (ArrayStoreException ignore) {
2332 2332 // To get better and consistent diagnostics,
2333 2333 // we call typeCheck explicitly on each element.
2334 2334 // We call clone() to defend against coll retaining a
2335 2335 // reference to the returned array and storing a bad
2336 2336 // element into it after it has been type checked.
2337 2337 a = coll.toArray().clone();
2338 2338 for (Object o : a)
2339 2339 typeCheck(o);
2340 2340 }
2341 2341 // A slight abuse of the type system, but safe here.
2342 2342 return (Collection<E>) Arrays.asList(a);
2343 2343 }
2344 2344
2345 2345 public boolean addAll(Collection<? extends E> coll) {
2346 2346 // Doing things this way insulates us from concurrent changes
2347 2347 // in the contents of coll and provides all-or-nothing
2348 2348 // semantics (which we wouldn't get if we type-checked each
2349 2349 // element as we added it)
2350 2350 return c.addAll(checkedCopyOf(coll));
2351 2351 }
2352 2352 }
2353 2353
2354 2354 /**
2355 2355 * Returns a dynamically typesafe view of the specified set.
2356 2356 * Any attempt to insert an element of the wrong type will result in
2357 2357 * an immediate {@link ClassCastException}. Assuming a set contains
2358 2358 * no incorrectly typed elements prior to the time a dynamically typesafe
2359 2359 * view is generated, and that all subsequent access to the set
2360 2360 * takes place through the view, it is <i>guaranteed</i> that the
2361 2361 * set cannot contain an incorrectly typed element.
2362 2362 *
2363 2363 * <p>A discussion of the use of dynamically typesafe views may be
2364 2364 * found in the documentation for the {@link #checkedCollection
2365 2365 * checkedCollection} method.
2366 2366 *
2367 2367 * <p>The returned set will be serializable if the specified set is
2368 2368 * serializable.
2369 2369 *
2370 2370 * <p>Since {@code null} is considered to be a value of any reference
2371 2371 * type, the returned set permits insertion of null elements whenever
2372 2372 * the backing set does.
2373 2373 *
2374 2374 * @param s the set for which a dynamically typesafe view is to be
2375 2375 * returned
2376 2376 * @param type the type of element that {@code s} is permitted to hold
2377 2377 * @return a dynamically typesafe view of the specified set
2378 2378 * @since 1.5
2379 2379 */
2380 2380 public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {
2381 2381 return new CheckedSet<E>(s, type);
2382 2382 }
2383 2383
2384 2384 /**
2385 2385 * @serial include
2386 2386 */
2387 2387 static class CheckedSet<E> extends CheckedCollection<E>
2388 2388 implements Set<E>, Serializable
2389 2389 {
2390 2390 private static final long serialVersionUID = 4694047833775013803L;
2391 2391
2392 2392 CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); }
2393 2393
2394 2394 public boolean equals(Object o) { return o == this || c.equals(o); }
2395 2395 public int hashCode() { return c.hashCode(); }
2396 2396 }
2397 2397
2398 2398 /**
2399 2399 * Returns a dynamically typesafe view of the specified sorted set.
2400 2400 * Any attempt to insert an element of the wrong type will result in an
2401 2401 * immediate {@link ClassCastException}. Assuming a sorted set
2402 2402 * contains no incorrectly typed elements prior to the time a
2403 2403 * dynamically typesafe view is generated, and that all subsequent
2404 2404 * access to the sorted set takes place through the view, it is
2405 2405 * <i>guaranteed</i> that the sorted set cannot contain an incorrectly
2406 2406 * typed element.
2407 2407 *
2408 2408 * <p>A discussion of the use of dynamically typesafe views may be
2409 2409 * found in the documentation for the {@link #checkedCollection
2410 2410 * checkedCollection} method.
2411 2411 *
2412 2412 * <p>The returned sorted set will be serializable if the specified sorted
2413 2413 * set is serializable.
2414 2414 *
2415 2415 * <p>Since {@code null} is considered to be a value of any reference
2416 2416 * type, the returned sorted set permits insertion of null elements
2417 2417 * whenever the backing sorted set does.
2418 2418 *
2419 2419 * @param s the sorted set for which a dynamically typesafe view is to be
2420 2420 * returned
2421 2421 * @param type the type of element that {@code s} is permitted to hold
2422 2422 * @return a dynamically typesafe view of the specified sorted set
2423 2423 * @since 1.5
2424 2424 */
2425 2425 public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
2426 2426 Class<E> type) {
2427 2427 return new CheckedSortedSet<E>(s, type);
2428 2428 }
2429 2429
2430 2430 /**
2431 2431 * @serial include
2432 2432 */
2433 2433 static class CheckedSortedSet<E> extends CheckedSet<E>
2434 2434 implements SortedSet<E>, Serializable
2435 2435 {
2436 2436 private static final long serialVersionUID = 1599911165492914959L;
2437 2437 private final SortedSet<E> ss;
2438 2438
2439 2439 CheckedSortedSet(SortedSet<E> s, Class<E> type) {
2440 2440 super(s, type);
2441 2441 ss = s;
2442 2442 }
2443 2443
2444 2444 public Comparator<? super E> comparator() { return ss.comparator(); }
2445 2445 public E first() { return ss.first(); }
2446 2446 public E last() { return ss.last(); }
2447 2447
2448 2448 public SortedSet<E> subSet(E fromElement, E toElement) {
2449 2449 return checkedSortedSet(ss.subSet(fromElement,toElement), type);
2450 2450 }
2451 2451 public SortedSet<E> headSet(E toElement) {
2452 2452 return checkedSortedSet(ss.headSet(toElement), type);
2453 2453 }
2454 2454 public SortedSet<E> tailSet(E fromElement) {
2455 2455 return checkedSortedSet(ss.tailSet(fromElement), type);
2456 2456 }
2457 2457 }
2458 2458
2459 2459 /**
2460 2460 * Returns a dynamically typesafe view of the specified list.
2461 2461 * Any attempt to insert an element of the wrong type will result in
2462 2462 * an immediate {@link ClassCastException}. Assuming a list contains
2463 2463 * no incorrectly typed elements prior to the time a dynamically typesafe
2464 2464 * view is generated, and that all subsequent access to the list
2465 2465 * takes place through the view, it is <i>guaranteed</i> that the
2466 2466 * list cannot contain an incorrectly typed element.
2467 2467 *
2468 2468 * <p>A discussion of the use of dynamically typesafe views may be
2469 2469 * found in the documentation for the {@link #checkedCollection
2470 2470 * checkedCollection} method.
2471 2471 *
2472 2472 * <p>The returned list will be serializable if the specified list
2473 2473 * is serializable.
2474 2474 *
2475 2475 * <p>Since {@code null} is considered to be a value of any reference
2476 2476 * type, the returned list permits insertion of null elements whenever
2477 2477 * the backing list does.
2478 2478 *
2479 2479 * @param list the list for which a dynamically typesafe view is to be
2480 2480 * returned
2481 2481 * @param type the type of element that {@code list} is permitted to hold
2482 2482 * @return a dynamically typesafe view of the specified list
2483 2483 * @since 1.5
2484 2484 */
2485 2485 public static <E> List<E> checkedList(List<E> list, Class<E> type) {
2486 2486 return (list instanceof RandomAccess ?
2487 2487 new CheckedRandomAccessList<E>(list, type) :
2488 2488 new CheckedList<E>(list, type));
2489 2489 }
2490 2490
2491 2491 /**
2492 2492 * @serial include
2493 2493 */
2494 2494 static class CheckedList<E>
2495 2495 extends CheckedCollection<E>
2496 2496 implements List<E>
2497 2497 {
2498 2498 private static final long serialVersionUID = 65247728283967356L;
2499 2499 final List<E> list;
2500 2500
2501 2501 CheckedList(List<E> list, Class<E> type) {
2502 2502 super(list, type);
2503 2503 this.list = list;
2504 2504 }
2505 2505
2506 2506 public boolean equals(Object o) { return o == this || list.equals(o); }
2507 2507 public int hashCode() { return list.hashCode(); }
2508 2508 public E get(int index) { return list.get(index); }
2509 2509 public E remove(int index) { return list.remove(index); }
2510 2510 public int indexOf(Object o) { return list.indexOf(o); }
2511 2511 public int lastIndexOf(Object o) { return list.lastIndexOf(o); }
2512 2512
2513 2513 public E set(int index, E element) {
2514 2514 typeCheck(element);
2515 2515 return list.set(index, element);
2516 2516 }
2517 2517
2518 2518 public void add(int index, E element) {
2519 2519 typeCheck(element);
2520 2520 list.add(index, element);
2521 2521 }
2522 2522
2523 2523 public boolean addAll(int index, Collection<? extends E> c) {
2524 2524 return list.addAll(index, checkedCopyOf(c));
2525 2525 }
2526 2526 public ListIterator<E> listIterator() { return listIterator(0); }
2527 2527
2528 2528 public ListIterator<E> listIterator(final int index) {
2529 2529 final ListIterator<E> i = list.listIterator(index);
2530 2530
2531 2531 return new ListIterator<E>() {
2532 2532 public boolean hasNext() { return i.hasNext(); }
2533 2533 public E next() { return i.next(); }
2534 2534 public boolean hasPrevious() { return i.hasPrevious(); }
2535 2535 public E previous() { return i.previous(); }
2536 2536 public int nextIndex() { return i.nextIndex(); }
2537 2537 public int previousIndex() { return i.previousIndex(); }
2538 2538 public void remove() { i.remove(); }
2539 2539
2540 2540 public void set(E e) {
2541 2541 typeCheck(e);
2542 2542 i.set(e);
2543 2543 }
2544 2544
2545 2545 public void add(E e) {
2546 2546 typeCheck(e);
2547 2547 i.add(e);
2548 2548 }
2549 2549 };
2550 2550 }
2551 2551
2552 2552 public List<E> subList(int fromIndex, int toIndex) {
2553 2553 return new CheckedList<E>(list.subList(fromIndex, toIndex), type);
2554 2554 }
2555 2555 }
2556 2556
2557 2557 /**
2558 2558 * @serial include
2559 2559 */
2560 2560 static class CheckedRandomAccessList<E> extends CheckedList<E>
2561 2561 implements RandomAccess
2562 2562 {
2563 2563 private static final long serialVersionUID = 1638200125423088369L;
2564 2564
2565 2565 CheckedRandomAccessList(List<E> list, Class<E> type) {
2566 2566 super(list, type);
2567 2567 }
2568 2568
2569 2569 public List<E> subList(int fromIndex, int toIndex) {
2570 2570 return new CheckedRandomAccessList<E>(
2571 2571 list.subList(fromIndex, toIndex), type);
2572 2572 }
2573 2573 }
2574 2574
2575 2575 /**
2576 2576 * Returns a dynamically typesafe view of the specified map.
2577 2577 * Any attempt to insert a mapping whose key or value have the wrong
2578 2578 * type will result in an immediate {@link ClassCastException}.
2579 2579 * Similarly, any attempt to modify the value currently associated with
2580 2580 * a key will result in an immediate {@link ClassCastException},
2581 2581 * whether the modification is attempted directly through the map
2582 2582 * itself, or through a {@link Map.Entry} instance obtained from the
2583 2583 * map's {@link Map#entrySet() entry set} view.
2584 2584 *
2585 2585 * <p>Assuming a map contains no incorrectly typed keys or values
2586 2586 * prior to the time a dynamically typesafe view is generated, and
2587 2587 * that all subsequent access to the map takes place through the view
2588 2588 * (or one of its collection views), it is <i>guaranteed</i> that the
2589 2589 * map cannot contain an incorrectly typed key or value.
2590 2590 *
2591 2591 * <p>A discussion of the use of dynamically typesafe views may be
2592 2592 * found in the documentation for the {@link #checkedCollection
2593 2593 * checkedCollection} method.
2594 2594 *
2595 2595 * <p>The returned map will be serializable if the specified map is
2596 2596 * serializable.
2597 2597 *
2598 2598 * <p>Since {@code null} is considered to be a value of any reference
2599 2599 * type, the returned map permits insertion of null keys or values
2600 2600 * whenever the backing map does.
2601 2601 *
2602 2602 * @param m the map for which a dynamically typesafe view is to be
2603 2603 * returned
2604 2604 * @param keyType the type of key that {@code m} is permitted to hold
2605 2605 * @param valueType the type of value that {@code m} is permitted to hold
2606 2606 * @return a dynamically typesafe view of the specified map
2607 2607 * @since 1.5
2608 2608 */
2609 2609 public static <K, V> Map<K, V> checkedMap(Map<K, V> m,
2610 2610 Class<K> keyType,
2611 2611 Class<V> valueType) {
2612 2612 return new CheckedMap<K,V>(m, keyType, valueType);
2613 2613 }
2614 2614
2615 2615
2616 2616 /**
2617 2617 * @serial include
2618 2618 */
2619 2619 private static class CheckedMap<K,V>
2620 2620 implements Map<K,V>, Serializable
2621 2621 {
2622 2622 private static final long serialVersionUID = 5742860141034234728L;
2623 2623
2624 2624 private final Map<K, V> m;
2625 2625 final Class<K> keyType;
2626 2626 final Class<V> valueType;
2627 2627
2628 2628 private void typeCheck(Object key, Object value) {
2629 2629 if (key != null && !keyType.isInstance(key))
2630 2630 throw new ClassCastException(badKeyMsg(key));
2631 2631
2632 2632 if (value != null && !valueType.isInstance(value))
2633 2633 throw new ClassCastException(badValueMsg(value));
2634 2634 }
2635 2635
2636 2636 private String badKeyMsg(Object key) {
2637 2637 return "Attempt to insert " + key.getClass() +
2638 2638 " key into map with key type " + keyType;
2639 2639 }
2640 2640
2641 2641 private String badValueMsg(Object value) {
2642 2642 return "Attempt to insert " + value.getClass() +
2643 2643 " value into map with value type " + valueType;
2644 2644 }
2645 2645
2646 2646 CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) {
2647 2647 if (m == null || keyType == null || valueType == null)
2648 2648 throw new NullPointerException();
2649 2649 this.m = m;
2650 2650 this.keyType = keyType;
2651 2651 this.valueType = valueType;
2652 2652 }
2653 2653
2654 2654 public int size() { return m.size(); }
2655 2655 public boolean isEmpty() { return m.isEmpty(); }
2656 2656 public boolean containsKey(Object key) { return m.containsKey(key); }
2657 2657 public boolean containsValue(Object v) { return m.containsValue(v); }
2658 2658 public V get(Object key) { return m.get(key); }
2659 2659 public V remove(Object key) { return m.remove(key); }
2660 2660 public void clear() { m.clear(); }
2661 2661 public Set<K> keySet() { return m.keySet(); }
2662 2662 public Collection<V> values() { return m.values(); }
2663 2663 public boolean equals(Object o) { return o == this || m.equals(o); }
2664 2664 public int hashCode() { return m.hashCode(); }
2665 2665 public String toString() { return m.toString(); }
2666 2666
2667 2667 public V put(K key, V value) {
2668 2668 typeCheck(key, value);
2669 2669 return m.put(key, value);
2670 2670 }
2671 2671
2672 2672 @SuppressWarnings("unchecked")
2673 2673 public void putAll(Map<? extends K, ? extends V> t) {
2674 2674 // Satisfy the following goals:
2675 2675 // - good diagnostics in case of type mismatch
2676 2676 // - all-or-nothing semantics
2677 2677 // - protection from malicious t
2678 2678 // - correct behavior if t is a concurrent map
2679 2679 Object[] entries = t.entrySet().toArray();
2680 2680 List<Map.Entry<K,V>> checked =
2681 2681 new ArrayList<Map.Entry<K,V>>(entries.length);
2682 2682 for (Object o : entries) {
2683 2683 Map.Entry<?,?> e = (Map.Entry<?,?>) o;
2684 2684 Object k = e.getKey();
2685 2685 Object v = e.getValue();
2686 2686 typeCheck(k, v);
2687 2687 checked.add(
2688 2688 new AbstractMap.SimpleImmutableEntry<K,V>((K) k, (V) v));
2689 2689 }
2690 2690 for (Map.Entry<K,V> e : checked)
2691 2691 m.put(e.getKey(), e.getValue());
2692 2692 }
2693 2693
2694 2694 private transient Set<Map.Entry<K,V>> entrySet = null;
2695 2695
2696 2696 public Set<Map.Entry<K,V>> entrySet() {
2697 2697 if (entrySet==null)
2698 2698 entrySet = new CheckedEntrySet<K,V>(m.entrySet(), valueType);
2699 2699 return entrySet;
2700 2700 }
2701 2701
2702 2702 /**
2703 2703 * We need this class in addition to CheckedSet as Map.Entry permits
2704 2704 * modification of the backing Map via the setValue operation. This
2705 2705 * class is subtle: there are many possible attacks that must be
2706 2706 * thwarted.
2707 2707 *
2708 2708 * @serial exclude
2709 2709 */
2710 2710 static class CheckedEntrySet<K,V> implements Set<Map.Entry<K,V>> {
2711 2711 private final Set<Map.Entry<K,V>> s;
2712 2712 private final Class<V> valueType;
2713 2713
2714 2714 CheckedEntrySet(Set<Map.Entry<K, V>> s, Class<V> valueType) {
2715 2715 this.s = s;
2716 2716 this.valueType = valueType;
2717 2717 }
2718 2718
2719 2719 public int size() { return s.size(); }
2720 2720 public boolean isEmpty() { return s.isEmpty(); }
2721 2721 public String toString() { return s.toString(); }
2722 2722 public int hashCode() { return s.hashCode(); }
2723 2723 public void clear() { s.clear(); }
2724 2724
2725 2725 public boolean add(Map.Entry<K, V> e) {
2726 2726 throw new UnsupportedOperationException();
2727 2727 }
2728 2728 public boolean addAll(Collection<? extends Map.Entry<K, V>> coll) {
2729 2729 throw new UnsupportedOperationException();
2730 2730 }
2731 2731
2732 2732 public Iterator<Map.Entry<K,V>> iterator() {
2733 2733 final Iterator<Map.Entry<K, V>> i = s.iterator();
2734 2734 final Class<V> valueType = this.valueType;
2735 2735
2736 2736 return new Iterator<Map.Entry<K,V>>() {
2737 2737 public boolean hasNext() { return i.hasNext(); }
2738 2738 public void remove() { i.remove(); }
2739 2739
2740 2740 public Map.Entry<K,V> next() {
2741 2741 return checkedEntry(i.next(), valueType);
2742 2742 }
2743 2743 };
2744 2744 }
2745 2745
2746 2746 @SuppressWarnings("unchecked")
2747 2747 public Object[] toArray() {
2748 2748 Object[] source = s.toArray();
2749 2749
2750 2750 /*
2751 2751 * Ensure that we don't get an ArrayStoreException even if
2752 2752 * s.toArray returns an array of something other than Object
2753 2753 */
2754 2754 Object[] dest = (CheckedEntry.class.isInstance(
2755 2755 source.getClass().getComponentType()) ? source :
2756 2756 new Object[source.length]);
2757 2757
2758 2758 for (int i = 0; i < source.length; i++)
2759 2759 dest[i] = checkedEntry((Map.Entry<K,V>)source[i],
2760 2760 valueType);
2761 2761 return dest;
2762 2762 }
2763 2763
2764 2764 @SuppressWarnings("unchecked")
2765 2765 public <T> T[] toArray(T[] a) {
2766 2766 // We don't pass a to s.toArray, to avoid window of
2767 2767 // vulnerability wherein an unscrupulous multithreaded client
2768 2768 // could get his hands on raw (unwrapped) Entries from s.
2769 2769 T[] arr = s.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
2770 2770
2771 2771 for (int i=0; i<arr.length; i++)
2772 2772 arr[i] = (T) checkedEntry((Map.Entry<K,V>)arr[i],
2773 2773 valueType);
2774 2774 if (arr.length > a.length)
2775 2775 return arr;
2776 2776
2777 2777 System.arraycopy(arr, 0, a, 0, arr.length);
2778 2778 if (a.length > arr.length)
2779 2779 a[arr.length] = null;
2780 2780 return a;
2781 2781 }
2782 2782
2783 2783 /**
2784 2784 * This method is overridden to protect the backing set against
2785 2785 * an object with a nefarious equals function that senses
2786 2786 * that the equality-candidate is Map.Entry and calls its
2787 2787 * setValue method.
2788 2788 */
2789 2789 public boolean contains(Object o) {
2790 2790 if (!(o instanceof Map.Entry))
2791 2791 return false;
2792 2792 Map.Entry<?,?> e = (Map.Entry<?,?>) o;
2793 2793 return s.contains(
2794 2794 (e instanceof CheckedEntry) ? e : checkedEntry(e, valueType));
2795 2795 }
2796 2796
2797 2797 /**
2798 2798 * The bulk collection methods are overridden to protect
2799 2799 * against an unscrupulous collection whose contains(Object o)
2800 2800 * method senses when o is a Map.Entry, and calls o.setValue.
2801 2801 */
2802 2802 public boolean containsAll(Collection<?> c) {
2803 2803 for (Object o : c)
2804 2804 if (!contains(o)) // Invokes safe contains() above
2805 2805 return false;
2806 2806 return true;
2807 2807 }
2808 2808
2809 2809 public boolean remove(Object o) {
2810 2810 if (!(o instanceof Map.Entry))
2811 2811 return false;
2812 2812 return s.remove(new AbstractMap.SimpleImmutableEntry
2813 2813 <Object, Object>((Map.Entry<?,?>)o));
2814 2814 }
2815 2815
2816 2816 public boolean removeAll(Collection<?> c) {
2817 2817 return batchRemove(c, false);
2818 2818 }
2819 2819 public boolean retainAll(Collection<?> c) {
2820 2820 return batchRemove(c, true);
2821 2821 }
2822 2822 private boolean batchRemove(Collection<?> c, boolean complement) {
2823 2823 boolean modified = false;
2824 2824 Iterator<Map.Entry<K,V>> it = iterator();
2825 2825 while (it.hasNext()) {
2826 2826 if (c.contains(it.next()) != complement) {
2827 2827 it.remove();
2828 2828 modified = true;
2829 2829 }
2830 2830 }
2831 2831 return modified;
2832 2832 }
2833 2833
2834 2834 public boolean equals(Object o) {
2835 2835 if (o == this)
2836 2836 return true;
2837 2837 if (!(o instanceof Set))
2838 2838 return false;
2839 2839 Set<?> that = (Set<?>) o;
2840 2840 return that.size() == s.size()
2841 2841 && containsAll(that); // Invokes safe containsAll() above
2842 2842 }
2843 2843
2844 2844 static <K,V,T> CheckedEntry<K,V,T> checkedEntry(Map.Entry<K,V> e,
2845 2845 Class<T> valueType) {
2846 2846 return new CheckedEntry<K,V,T>(e, valueType);
2847 2847 }
2848 2848
2849 2849 /**
2850 2850 * This "wrapper class" serves two purposes: it prevents
2851 2851 * the client from modifying the backing Map, by short-circuiting
2852 2852 * the setValue method, and it protects the backing Map against
2853 2853 * an ill-behaved Map.Entry that attempts to modify another
2854 2854 * Map.Entry when asked to perform an equality check.
2855 2855 */
2856 2856 private static class CheckedEntry<K,V,T> implements Map.Entry<K,V> {
2857 2857 private final Map.Entry<K, V> e;
2858 2858 private final Class<T> valueType;
2859 2859
2860 2860 CheckedEntry(Map.Entry<K, V> e, Class<T> valueType) {
2861 2861 this.e = e;
2862 2862 this.valueType = valueType;
2863 2863 }
2864 2864
2865 2865 public K getKey() { return e.getKey(); }
2866 2866 public V getValue() { return e.getValue(); }
2867 2867 public int hashCode() { return e.hashCode(); }
2868 2868 public String toString() { return e.toString(); }
2869 2869
2870 2870 public V setValue(V value) {
2871 2871 if (value != null && !valueType.isInstance(value))
2872 2872 throw new ClassCastException(badValueMsg(value));
2873 2873 return e.setValue(value);
2874 2874 }
2875 2875
2876 2876 private String badValueMsg(Object value) {
2877 2877 return "Attempt to insert " + value.getClass() +
2878 2878 " value into map with value type " + valueType;
2879 2879 }
2880 2880
2881 2881 public boolean equals(Object o) {
2882 2882 if (o == this)
2883 2883 return true;
2884 2884 if (!(o instanceof Map.Entry))
2885 2885 return false;
2886 2886 return e.equals(new AbstractMap.SimpleImmutableEntry
2887 2887 <Object, Object>((Map.Entry<?,?>)o));
2888 2888 }
2889 2889 }
2890 2890 }
2891 2891 }
2892 2892
2893 2893 /**
2894 2894 * Returns a dynamically typesafe view of the specified sorted map.
2895 2895 * Any attempt to insert a mapping whose key or value have the wrong
2896 2896 * type will result in an immediate {@link ClassCastException}.
2897 2897 * Similarly, any attempt to modify the value currently associated with
2898 2898 * a key will result in an immediate {@link ClassCastException},
2899 2899 * whether the modification is attempted directly through the map
2900 2900 * itself, or through a {@link Map.Entry} instance obtained from the
2901 2901 * map's {@link Map#entrySet() entry set} view.
2902 2902 *
2903 2903 * <p>Assuming a map contains no incorrectly typed keys or values
2904 2904 * prior to the time a dynamically typesafe view is generated, and
2905 2905 * that all subsequent access to the map takes place through the view
2906 2906 * (or one of its collection views), it is <i>guaranteed</i> that the
2907 2907 * map cannot contain an incorrectly typed key or value.
2908 2908 *
2909 2909 * <p>A discussion of the use of dynamically typesafe views may be
2910 2910 * found in the documentation for the {@link #checkedCollection
2911 2911 * checkedCollection} method.
2912 2912 *
2913 2913 * <p>The returned map will be serializable if the specified map is
2914 2914 * serializable.
2915 2915 *
2916 2916 * <p>Since {@code null} is considered to be a value of any reference
2917 2917 * type, the returned map permits insertion of null keys or values
2918 2918 * whenever the backing map does.
2919 2919 *
2920 2920 * @param m the map for which a dynamically typesafe view is to be
2921 2921 * returned
2922 2922 * @param keyType the type of key that {@code m} is permitted to hold
2923 2923 * @param valueType the type of value that {@code m} is permitted to hold
2924 2924 * @return a dynamically typesafe view of the specified map
2925 2925 * @since 1.5
2926 2926 */
2927 2927 public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,
2928 2928 Class<K> keyType,
2929 2929 Class<V> valueType) {
2930 2930 return new CheckedSortedMap<K,V>(m, keyType, valueType);
2931 2931 }
2932 2932
2933 2933 /**
2934 2934 * @serial include
2935 2935 */
2936 2936 static class CheckedSortedMap<K,V> extends CheckedMap<K,V>
2937 2937 implements SortedMap<K,V>, Serializable
2938 2938 {
2939 2939 private static final long serialVersionUID = 1599671320688067438L;
2940 2940
2941 2941 private final SortedMap<K, V> sm;
2942 2942
2943 2943 CheckedSortedMap(SortedMap<K, V> m,
2944 2944 Class<K> keyType, Class<V> valueType) {
2945 2945 super(m, keyType, valueType);
2946 2946 sm = m;
2947 2947 }
2948 2948
2949 2949 public Comparator<? super K> comparator() { return sm.comparator(); }
2950 2950 public K firstKey() { return sm.firstKey(); }
2951 2951 public K lastKey() { return sm.lastKey(); }
2952 2952
2953 2953 public SortedMap<K,V> subMap(K fromKey, K toKey) {
2954 2954 return checkedSortedMap(sm.subMap(fromKey, toKey),
2955 2955 keyType, valueType);
2956 2956 }
2957 2957 public SortedMap<K,V> headMap(K toKey) {
2958 2958 return checkedSortedMap(sm.headMap(toKey), keyType, valueType);
2959 2959 }
2960 2960 public SortedMap<K,V> tailMap(K fromKey) {
2961 2961 return checkedSortedMap(sm.tailMap(fromKey), keyType, valueType);
2962 2962 }
2963 2963 }
2964 2964
2965 2965 // Empty collections
2966 2966
2967 2967 /**
2968 2968 * Returns an iterator that has no elements. More precisely,
2969 2969 *
2970 2970 * <ul compact>
2971 2971 *
2972 2972 * <li>{@link Iterator#hasNext hasNext} always returns {@code
2973 2973 * false}.
2974 2974 *
2975 2975 * <li>{@link Iterator#next next} always throws {@link
2976 2976 * NoSuchElementException}.
2977 2977 *
2978 2978 * <li>{@link Iterator#remove remove} always throws {@link
2979 2979 * IllegalStateException}.
2980 2980 *
2981 2981 * </ul>
2982 2982 *
2983 2983 * <p>Implementations of this method are permitted, but not
2984 2984 * required, to return the same object from multiple invocations.
2985 2985 *
2986 2986 * @return an empty iterator
2987 2987 * @since 1.7
2988 2988 */
2989 2989 @SuppressWarnings("unchecked")
2990 2990 public static <T> Iterator<T> emptyIterator() {
2991 2991 return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR;
2992 2992 }
2993 2993
2994 2994 private static class EmptyIterator<E> implements Iterator<E> {
2995 2995 static final EmptyIterator<Object> EMPTY_ITERATOR
2996 2996 = new EmptyIterator<Object>();
2997 2997
2998 2998 public boolean hasNext() { return false; }
2999 2999 public E next() { throw new NoSuchElementException(); }
3000 3000 public void remove() { throw new IllegalStateException(); }
3001 3001 }
3002 3002
3003 3003 /**
3004 3004 * Returns a list iterator that has no elements. More precisely,
3005 3005 *
3006 3006 * <ul compact>
3007 3007 *
3008 3008 * <li>{@link Iterator#hasNext hasNext} and {@link
3009 3009 * ListIterator#hasPrevious hasPrevious} always return {@code
3010 3010 * false}.
3011 3011 *
3012 3012 * <li>{@link Iterator#next next} and {@link ListIterator#previous
3013 3013 * previous} always throw {@link NoSuchElementException}.
3014 3014 *
3015 3015 * <li>{@link Iterator#remove remove} and {@link ListIterator#set
3016 3016 * set} always throw {@link IllegalStateException}.
3017 3017 *
3018 3018 * <li>{@link ListIterator#add add} always throws {@link
3019 3019 * UnsupportedOperationException}.
3020 3020 *
3021 3021 * <li>{@link ListIterator#nextIndex nextIndex} always returns
3022 3022 * {@code 0} .
3023 3023 *
3024 3024 * <li>{@link ListIterator#previousIndex previousIndex} always
3025 3025 * returns {@code -1}.
3026 3026 *
3027 3027 * </ul>
3028 3028 *
3029 3029 * <p>Implementations of this method are permitted, but not
3030 3030 * required, to return the same object from multiple invocations.
3031 3031 *
3032 3032 * @return an empty list iterator
3033 3033 * @since 1.7
3034 3034 */
3035 3035 @SuppressWarnings("unchecked")
3036 3036 public static <T> ListIterator<T> emptyListIterator() {
3037 3037 return (ListIterator<T>) EmptyListIterator.EMPTY_ITERATOR;
3038 3038 }
3039 3039
3040 3040 private static class EmptyListIterator<E>
3041 3041 extends EmptyIterator<E>
3042 3042 implements ListIterator<E>
3043 3043 {
3044 3044 static final EmptyListIterator<Object> EMPTY_ITERATOR
3045 3045 = new EmptyListIterator<Object>();
3046 3046
3047 3047 public boolean hasPrevious() { return false; }
3048 3048 public E previous() { throw new NoSuchElementException(); }
3049 3049 public int nextIndex() { return 0; }
3050 3050 public int previousIndex() { return -1; }
3051 3051 public void set(E e) { throw new IllegalStateException(); }
3052 3052 public void add(E e) { throw new UnsupportedOperationException(); }
3053 3053 }
3054 3054
3055 3055 /**
3056 3056 * Returns an enumeration that has no elements. More precisely,
3057 3057 *
3058 3058 * <ul compact>
3059 3059 *
3060 3060 * <li>{@link Enumeration#hasMoreElements hasMoreElements} always
3061 3061 * returns {@code false}.
3062 3062 *
3063 3063 * <li> {@link Enumeration#nextElement nextElement} always throws
3064 3064 * {@link NoSuchElementException}.
3065 3065 *
3066 3066 * </ul>
3067 3067 *
3068 3068 * <p>Implementations of this method are permitted, but not
3069 3069 * required, to return the same object from multiple invocations.
3070 3070 *
3071 3071 * @return an empty enumeration
3072 3072 * @since 1.7
3073 3073 */
3074 3074 @SuppressWarnings("unchecked")
3075 3075 public static <T> Enumeration<T> emptyEnumeration() {
3076 3076 return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION;
3077 3077 }
3078 3078
3079 3079 private static class EmptyEnumeration<E> implements Enumeration<E> {
3080 3080 static final EmptyEnumeration<Object> EMPTY_ENUMERATION
3081 3081 = new EmptyEnumeration<Object>();
3082 3082
3083 3083 public boolean hasMoreElements() { return false; }
3084 3084 public E nextElement() { throw new NoSuchElementException(); }
3085 3085 }
3086 3086
3087 3087 /**
3088 3088 * The empty set (immutable). This set is serializable.
3089 3089 *
3090 3090 * @see #emptySet()
3091 3091 */
3092 3092 @SuppressWarnings("unchecked")
3093 3093 public static final Set EMPTY_SET = new EmptySet<Object>();
3094 3094
3095 3095 /**
3096 3096 * Returns the empty set (immutable). This set is serializable.
3097 3097 * Unlike the like-named field, this method is parameterized.
3098 3098 *
3099 3099 * <p>This example illustrates the type-safe way to obtain an empty set:
3100 3100 * <pre>
3101 3101 * Set<String> s = Collections.emptySet();
3102 3102 * </pre>
3103 3103 * Implementation note: Implementations of this method need not
3104 3104 * create a separate <tt>Set</tt> object for each call. Using this
3105 3105 * method is likely to have comparable cost to using the like-named
3106 3106 * field. (Unlike this method, the field does not provide type safety.)
3107 3107 *
3108 3108 * @see #EMPTY_SET
3109 3109 * @since 1.5
3110 3110 */
3111 3111 @SuppressWarnings("unchecked")
3112 3112 public static final <T> Set<T> emptySet() {
3113 3113 return (Set<T>) EMPTY_SET;
3114 3114 }
3115 3115
3116 3116 /**
3117 3117 * @serial include
3118 3118 */
3119 3119 private static class EmptySet<E>
3120 3120 extends AbstractSet<E>
3121 3121 implements Serializable
3122 3122 {
3123 3123 private static final long serialVersionUID = 1582296315990362920L;
3124 3124
3125 3125 public Iterator<E> iterator() { return emptyIterator(); }
3126 3126
3127 3127 public int size() {return 0;}
3128 3128 public boolean isEmpty() {return true;}
3129 3129
3130 3130 public boolean contains(Object obj) {return false;}
3131 3131 public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
3132 3132
3133 3133 public Object[] toArray() { return new Object[0]; }
3134 3134
3135 3135 public <T> T[] toArray(T[] a) {
3136 3136 if (a.length > 0)
3137 3137 a[0] = null;
3138 3138 return a;
3139 3139 }
3140 3140
3141 3141 // Preserves singleton property
3142 3142 private Object readResolve() {
3143 3143 return EMPTY_SET;
3144 3144 }
3145 3145 }
3146 3146
3147 3147 /**
3148 3148 * The empty list (immutable). This list is serializable.
3149 3149 *
3150 3150 * @see #emptyList()
3151 3151 */
3152 3152 @SuppressWarnings("unchecked")
3153 3153 public static final List EMPTY_LIST = new EmptyList<Object>();
3154 3154
3155 3155 /**
3156 3156 * Returns the empty list (immutable). This list is serializable.
3157 3157 *
3158 3158 * <p>This example illustrates the type-safe way to obtain an empty list:
3159 3159 * <pre>
3160 3160 * List<String> s = Collections.emptyList();
3161 3161 * </pre>
3162 3162 * Implementation note: Implementations of this method need not
3163 3163 * create a separate <tt>List</tt> object for each call. Using this
3164 3164 * method is likely to have comparable cost to using the like-named
3165 3165 * field. (Unlike this method, the field does not provide type safety.)
3166 3166 *
3167 3167 * @see #EMPTY_LIST
3168 3168 * @since 1.5
3169 3169 */
3170 3170 @SuppressWarnings("unchecked")
3171 3171 public static final <T> List<T> emptyList() {
3172 3172 return (List<T>) EMPTY_LIST;
3173 3173 }
3174 3174
3175 3175 /**
3176 3176 * @serial include
3177 3177 */
3178 3178 private static class EmptyList<E>
3179 3179 extends AbstractList<E>
3180 3180 implements RandomAccess, Serializable {
3181 3181 private static final long serialVersionUID = 8842843931221139166L;
3182 3182
3183 3183 public Iterator<E> iterator() {
3184 3184 return emptyIterator();
3185 3185 }
3186 3186 public ListIterator<E> listIterator() {
3187 3187 return emptyListIterator();
3188 3188 }
3189 3189
3190 3190 public int size() {return 0;}
3191 3191 public boolean isEmpty() {return true;}
3192 3192
3193 3193 public boolean contains(Object obj) {return false;}
3194 3194 public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
3195 3195
3196 3196 public Object[] toArray() { return new Object[0]; }
3197 3197
3198 3198 public <T> T[] toArray(T[] a) {
3199 3199 if (a.length > 0)
3200 3200 a[0] = null;
3201 3201 return a;
3202 3202 }
3203 3203
3204 3204 public E get(int index) {
3205 3205 throw new IndexOutOfBoundsException("Index: "+index);
3206 3206 }
3207 3207
3208 3208 public boolean equals(Object o) {
3209 3209 return (o instanceof List) && ((List<?>)o).isEmpty();
3210 3210 }
3211 3211
3212 3212 public int hashCode() { return 1; }
3213 3213
3214 3214 // Preserves singleton property
3215 3215 private Object readResolve() {
3216 3216 return EMPTY_LIST;
3217 3217 }
3218 3218 }
3219 3219
3220 3220 /**
3221 3221 * The empty map (immutable). This map is serializable.
3222 3222 *
3223 3223 * @see #emptyMap()
3224 3224 * @since 1.3
3225 3225 */
3226 3226 @SuppressWarnings("unchecked")
3227 3227 public static final Map EMPTY_MAP = new EmptyMap<Object,Object>();
3228 3228
3229 3229 /**
3230 3230 * Returns the empty map (immutable). This map is serializable.
3231 3231 *
3232 3232 * <p>This example illustrates the type-safe way to obtain an empty set:
3233 3233 * <pre>
3234 3234 * Map<String, Date> s = Collections.emptyMap();
3235 3235 * </pre>
3236 3236 * Implementation note: Implementations of this method need not
3237 3237 * create a separate <tt>Map</tt> object for each call. Using this
3238 3238 * method is likely to have comparable cost to using the like-named
3239 3239 * field. (Unlike this method, the field does not provide type safety.)
3240 3240 *
3241 3241 * @see #EMPTY_MAP
3242 3242 * @since 1.5
3243 3243 */
3244 3244 @SuppressWarnings("unchecked")
3245 3245 public static final <K,V> Map<K,V> emptyMap() {
3246 3246 return (Map<K,V>) EMPTY_MAP;
3247 3247 }
3248 3248
3249 3249 /**
3250 3250 * @serial include
3251 3251 */
3252 3252 private static class EmptyMap<K,V>
3253 3253 extends AbstractMap<K,V>
3254 3254 implements Serializable
3255 3255 {
3256 3256 private static final long serialVersionUID = 6428348081105594320L;
3257 3257
3258 3258 public int size() {return 0;}
3259 3259 public boolean isEmpty() {return true;}
3260 3260 public boolean containsKey(Object key) {return false;}
3261 3261 public boolean containsValue(Object value) {return false;}
3262 3262 public V get(Object key) {return null;}
3263 3263 public Set<K> keySet() {return emptySet();}
3264 3264 public Collection<V> values() {return emptySet();}
3265 3265 public Set<Map.Entry<K,V>> entrySet() {return emptySet();}
3266 3266
3267 3267 public boolean equals(Object o) {
3268 3268 return (o instanceof Map) && ((Map<?,?>)o).isEmpty();
3269 3269 }
3270 3270
3271 3271 public int hashCode() {return 0;}
3272 3272
3273 3273 // Preserves singleton property
3274 3274 private Object readResolve() {
3275 3275 return EMPTY_MAP;
3276 3276 }
3277 3277 }
3278 3278
3279 3279 // Singleton collections
3280 3280
3281 3281 /**
3282 3282 * Returns an immutable set containing only the specified object.
3283 3283 * The returned set is serializable.
3284 3284 *
3285 3285 * @param o the sole object to be stored in the returned set.
3286 3286 * @return an immutable set containing only the specified object.
3287 3287 */
3288 3288 public static <T> Set<T> singleton(T o) {
3289 3289 return new SingletonSet<T>(o);
3290 3290 }
3291 3291
3292 3292 static <E> Iterator<E> singletonIterator(final E e) {
3293 3293 return new Iterator<E>() {
3294 3294 private boolean hasNext = true;
3295 3295 public boolean hasNext() {
3296 3296 return hasNext;
3297 3297 }
3298 3298 public E next() {
3299 3299 if (hasNext) {
3300 3300 hasNext = false;
3301 3301 return e;
3302 3302 }
3303 3303 throw new NoSuchElementException();
3304 3304 }
3305 3305 public void remove() {
3306 3306 throw new UnsupportedOperationException();
3307 3307 }
3308 3308 };
3309 3309 }
↓ open down ↓ |
1118 lines elided |
↑ open up ↑ |
3310 3310
3311 3311 /**
3312 3312 * @serial include
3313 3313 */
3314 3314 private static class SingletonSet<E>
3315 3315 extends AbstractSet<E>
3316 3316 implements Serializable
3317 3317 {
3318 3318 private static final long serialVersionUID = 3193687207550431679L;
3319 3319
3320 - final private E element;
3320 + private final E element;
3321 3321
3322 3322 SingletonSet(E e) {element = e;}
3323 3323
3324 3324 public Iterator<E> iterator() {
3325 3325 return singletonIterator(element);
3326 3326 }
3327 3327
3328 3328 public int size() {return 1;}
3329 3329
3330 3330 public boolean contains(Object o) {return eq(o, element);}
3331 3331 }
3332 3332
3333 3333 /**
3334 3334 * Returns an immutable list containing only the specified object.
3335 3335 * The returned list is serializable.
3336 3336 *
3337 3337 * @param o the sole object to be stored in the returned list.
3338 3338 * @return an immutable list containing only the specified object.
3339 3339 * @since 1.3
3340 3340 */
3341 3341 public static <T> List<T> singletonList(T o) {
3342 3342 return new SingletonList<T>(o);
3343 3343 }
3344 3344
3345 3345 /**
3346 3346 * @serial include
3347 3347 */
3348 3348 private static class SingletonList<E>
3349 3349 extends AbstractList<E>
3350 3350 implements RandomAccess, Serializable {
3351 3351
3352 3352 private static final long serialVersionUID = 3093736618740652951L;
3353 3353
3354 3354 private final E element;
3355 3355
3356 3356 SingletonList(E obj) {element = obj;}
3357 3357
3358 3358 public Iterator<E> iterator() {
3359 3359 return singletonIterator(element);
3360 3360 }
3361 3361
3362 3362 public int size() {return 1;}
3363 3363
3364 3364 public boolean contains(Object obj) {return eq(obj, element);}
3365 3365
3366 3366 public E get(int index) {
3367 3367 if (index != 0)
3368 3368 throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");
3369 3369 return element;
3370 3370 }
3371 3371 }
3372 3372
3373 3373 /**
3374 3374 * Returns an immutable map, mapping only the specified key to the
3375 3375 * specified value. The returned map is serializable.
3376 3376 *
3377 3377 * @param key the sole key to be stored in the returned map.
3378 3378 * @param value the value to which the returned map maps <tt>key</tt>.
3379 3379 * @return an immutable map containing only the specified key-value
3380 3380 * mapping.
3381 3381 * @since 1.3
3382 3382 */
3383 3383 public static <K,V> Map<K,V> singletonMap(K key, V value) {
3384 3384 return new SingletonMap<K,V>(key, value);
3385 3385 }
3386 3386
3387 3387 /**
3388 3388 * @serial include
3389 3389 */
3390 3390 private static class SingletonMap<K,V>
3391 3391 extends AbstractMap<K,V>
3392 3392 implements Serializable {
3393 3393 private static final long serialVersionUID = -6979724477215052911L;
3394 3394
3395 3395 private final K k;
3396 3396 private final V v;
3397 3397
3398 3398 SingletonMap(K key, V value) {
3399 3399 k = key;
3400 3400 v = value;
3401 3401 }
3402 3402
3403 3403 public int size() {return 1;}
3404 3404
3405 3405 public boolean isEmpty() {return false;}
3406 3406
3407 3407 public boolean containsKey(Object key) {return eq(key, k);}
3408 3408
3409 3409 public boolean containsValue(Object value) {return eq(value, v);}
3410 3410
3411 3411 public V get(Object key) {return (eq(key, k) ? v : null);}
3412 3412
3413 3413 private transient Set<K> keySet = null;
3414 3414 private transient Set<Map.Entry<K,V>> entrySet = null;
3415 3415 private transient Collection<V> values = null;
3416 3416
3417 3417 public Set<K> keySet() {
3418 3418 if (keySet==null)
3419 3419 keySet = singleton(k);
3420 3420 return keySet;
3421 3421 }
3422 3422
3423 3423 public Set<Map.Entry<K,V>> entrySet() {
3424 3424 if (entrySet==null)
3425 3425 entrySet = Collections.<Map.Entry<K,V>>singleton(
3426 3426 new SimpleImmutableEntry<K,V>(k, v));
3427 3427 return entrySet;
3428 3428 }
3429 3429
3430 3430 public Collection<V> values() {
3431 3431 if (values==null)
3432 3432 values = singleton(v);
3433 3433 return values;
3434 3434 }
3435 3435
3436 3436 }
3437 3437
3438 3438 // Miscellaneous
3439 3439
3440 3440 /**
↓ open down ↓ |
110 lines elided |
↑ open up ↑ |
3441 3441 * Returns an immutable list consisting of <tt>n</tt> copies of the
3442 3442 * specified object. The newly allocated data object is tiny (it contains
3443 3443 * a single reference to the data object). This method is useful in
3444 3444 * combination with the <tt>List.addAll</tt> method to grow lists.
3445 3445 * The returned list is serializable.
3446 3446 *
3447 3447 * @param n the number of elements in the returned list.
3448 3448 * @param o the element to appear repeatedly in the returned list.
3449 3449 * @return an immutable list consisting of <tt>n</tt> copies of the
3450 3450 * specified object.
3451 - * @throws IllegalArgumentException if n < 0.
3451 + * @throws IllegalArgumentException if {@code n < 0}
3452 3452 * @see List#addAll(Collection)
3453 3453 * @see List#addAll(int, Collection)
3454 3454 */
3455 3455 public static <T> List<T> nCopies(int n, T o) {
3456 3456 if (n < 0)
3457 3457 throw new IllegalArgumentException("List length = " + n);
3458 3458 return new CopiesList<T>(n, o);
3459 3459 }
3460 3460
3461 3461 /**
3462 3462 * @serial include
3463 3463 */
3464 3464 private static class CopiesList<E>
3465 3465 extends AbstractList<E>
3466 3466 implements RandomAccess, Serializable
3467 3467 {
3468 3468 private static final long serialVersionUID = 2739099268398711800L;
3469 3469
3470 3470 final int n;
3471 3471 final E element;
3472 3472
3473 3473 CopiesList(int n, E e) {
3474 3474 assert n >= 0;
3475 3475 this.n = n;
3476 3476 element = e;
3477 3477 }
3478 3478
3479 3479 public int size() {
3480 3480 return n;
3481 3481 }
3482 3482
3483 3483 public boolean contains(Object obj) {
3484 3484 return n != 0 && eq(obj, element);
3485 3485 }
3486 3486
3487 3487 public int indexOf(Object o) {
3488 3488 return contains(o) ? 0 : -1;
3489 3489 }
3490 3490
3491 3491 public int lastIndexOf(Object o) {
3492 3492 return contains(o) ? n - 1 : -1;
3493 3493 }
3494 3494
3495 3495 public E get(int index) {
3496 3496 if (index < 0 || index >= n)
3497 3497 throw new IndexOutOfBoundsException("Index: "+index+
3498 3498 ", Size: "+n);
3499 3499 return element;
3500 3500 }
3501 3501
3502 3502 public Object[] toArray() {
3503 3503 final Object[] a = new Object[n];
3504 3504 if (element != null)
3505 3505 Arrays.fill(a, 0, n, element);
3506 3506 return a;
3507 3507 }
3508 3508
3509 3509 public <T> T[] toArray(T[] a) {
3510 3510 final int n = this.n;
3511 3511 if (a.length < n) {
3512 3512 a = (T[])java.lang.reflect.Array
3513 3513 .newInstance(a.getClass().getComponentType(), n);
3514 3514 if (element != null)
3515 3515 Arrays.fill(a, 0, n, element);
3516 3516 } else {
3517 3517 Arrays.fill(a, 0, n, element);
3518 3518 if (a.length > n)
3519 3519 a[n] = null;
3520 3520 }
3521 3521 return a;
3522 3522 }
3523 3523
3524 3524 public List<E> subList(int fromIndex, int toIndex) {
3525 3525 if (fromIndex < 0)
3526 3526 throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
3527 3527 if (toIndex > n)
3528 3528 throw new IndexOutOfBoundsException("toIndex = " + toIndex);
3529 3529 if (fromIndex > toIndex)
3530 3530 throw new IllegalArgumentException("fromIndex(" + fromIndex +
3531 3531 ") > toIndex(" + toIndex + ")");
3532 3532 return new CopiesList<E>(toIndex - fromIndex, element);
3533 3533 }
3534 3534 }
3535 3535
3536 3536 /**
3537 3537 * Returns a comparator that imposes the reverse of the <i>natural
3538 3538 * ordering</i> on a collection of objects that implement the
3539 3539 * <tt>Comparable</tt> interface. (The natural ordering is the ordering
3540 3540 * imposed by the objects' own <tt>compareTo</tt> method.) This enables a
3541 3541 * simple idiom for sorting (or maintaining) collections (or arrays) of
3542 3542 * objects that implement the <tt>Comparable</tt> interface in
3543 3543 * reverse-natural-order. For example, suppose a is an array of
3544 3544 * strings. Then: <pre>
3545 3545 * Arrays.sort(a, Collections.reverseOrder());
3546 3546 * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>
3547 3547 *
3548 3548 * The returned comparator is serializable.
3549 3549 *
3550 3550 * @return a comparator that imposes the reverse of the <i>natural
3551 3551 * ordering</i> on a collection of objects that implement
3552 3552 * the <tt>Comparable</tt> interface.
3553 3553 * @see Comparable
3554 3554 */
3555 3555 public static <T> Comparator<T> reverseOrder() {
3556 3556 return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
3557 3557 }
3558 3558
3559 3559 /**
3560 3560 * @serial include
3561 3561 */
3562 3562 private static class ReverseComparator
3563 3563 implements Comparator<Comparable<Object>>, Serializable {
3564 3564
3565 3565 private static final long serialVersionUID = 7207038068494060240L;
3566 3566
3567 3567 static final ReverseComparator REVERSE_ORDER
3568 3568 = new ReverseComparator();
3569 3569
3570 3570 public int compare(Comparable<Object> c1, Comparable<Object> c2) {
3571 3571 return c2.compareTo(c1);
3572 3572 }
3573 3573
3574 3574 private Object readResolve() { return reverseOrder(); }
3575 3575 }
3576 3576
3577 3577 /**
3578 3578 * Returns a comparator that imposes the reverse ordering of the specified
3579 3579 * comparator. If the specified comparator is null, this method is
3580 3580 * equivalent to {@link #reverseOrder()} (in other words, it returns a
3581 3581 * comparator that imposes the reverse of the <i>natural ordering</i> on a
3582 3582 * collection of objects that implement the Comparable interface).
3583 3583 *
3584 3584 * <p>The returned comparator is serializable (assuming the specified
3585 3585 * comparator is also serializable or null).
3586 3586 *
3587 3587 * @return a comparator that imposes the reverse ordering of the
3588 3588 * specified comparator
3589 3589 * @since 1.5
3590 3590 */
3591 3591 public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) {
3592 3592 if (cmp == null)
3593 3593 return reverseOrder();
3594 3594
3595 3595 if (cmp instanceof ReverseComparator2)
3596 3596 return ((ReverseComparator2<T>)cmp).cmp;
3597 3597
3598 3598 return new ReverseComparator2<T>(cmp);
3599 3599 }
3600 3600
3601 3601 /**
3602 3602 * @serial include
3603 3603 */
3604 3604 private static class ReverseComparator2<T> implements Comparator<T>,
3605 3605 Serializable
3606 3606 {
3607 3607 private static final long serialVersionUID = 4374092139857L;
3608 3608
3609 3609 /**
3610 3610 * The comparator specified in the static factory. This will never
3611 3611 * be null, as the static factory returns a ReverseComparator
3612 3612 * instance if its argument is null.
3613 3613 *
3614 3614 * @serial
3615 3615 */
3616 3616 final Comparator<T> cmp;
3617 3617
3618 3618 ReverseComparator2(Comparator<T> cmp) {
3619 3619 assert cmp != null;
3620 3620 this.cmp = cmp;
3621 3621 }
3622 3622
3623 3623 public int compare(T t1, T t2) {
3624 3624 return cmp.compare(t2, t1);
3625 3625 }
3626 3626
3627 3627 public boolean equals(Object o) {
3628 3628 return (o == this) ||
3629 3629 (o instanceof ReverseComparator2 &&
3630 3630 cmp.equals(((ReverseComparator2)o).cmp));
3631 3631 }
3632 3632
3633 3633 public int hashCode() {
3634 3634 return cmp.hashCode() ^ Integer.MIN_VALUE;
3635 3635 }
3636 3636 }
3637 3637
3638 3638 /**
3639 3639 * Returns an enumeration over the specified collection. This provides
3640 3640 * interoperability with legacy APIs that require an enumeration
3641 3641 * as input.
3642 3642 *
3643 3643 * @param c the collection for which an enumeration is to be returned.
3644 3644 * @return an enumeration over the specified collection.
3645 3645 * @see Enumeration
3646 3646 */
3647 3647 public static <T> Enumeration<T> enumeration(final Collection<T> c) {
3648 3648 return new Enumeration<T>() {
3649 3649 private final Iterator<T> i = c.iterator();
3650 3650
3651 3651 public boolean hasMoreElements() {
3652 3652 return i.hasNext();
3653 3653 }
3654 3654
3655 3655 public T nextElement() {
3656 3656 return i.next();
3657 3657 }
3658 3658 };
3659 3659 }
3660 3660
3661 3661 /**
3662 3662 * Returns an array list containing the elements returned by the
3663 3663 * specified enumeration in the order they are returned by the
3664 3664 * enumeration. This method provides interoperability between
3665 3665 * legacy APIs that return enumerations and new APIs that require
3666 3666 * collections.
3667 3667 *
3668 3668 * @param e enumeration providing elements for the returned
3669 3669 * array list
3670 3670 * @return an array list containing the elements returned
3671 3671 * by the specified enumeration.
3672 3672 * @since 1.4
3673 3673 * @see Enumeration
3674 3674 * @see ArrayList
3675 3675 */
3676 3676 public static <T> ArrayList<T> list(Enumeration<T> e) {
3677 3677 ArrayList<T> l = new ArrayList<T>();
3678 3678 while (e.hasMoreElements())
3679 3679 l.add(e.nextElement());
3680 3680 return l;
3681 3681 }
3682 3682
3683 3683 /**
3684 3684 * Returns true if the specified arguments are equal, or both null.
3685 3685 */
3686 3686 static boolean eq(Object o1, Object o2) {
3687 3687 return o1==null ? o2==null : o1.equals(o2);
3688 3688 }
3689 3689
3690 3690 /**
3691 3691 * Returns the number of elements in the specified collection equal to the
3692 3692 * specified object. More formally, returns the number of elements
3693 3693 * <tt>e</tt> in the collection such that
3694 3694 * <tt>(o == null ? e == null : o.equals(e))</tt>.
3695 3695 *
3696 3696 * @param c the collection in which to determine the frequency
3697 3697 * of <tt>o</tt>
3698 3698 * @param o the object whose frequency is to be determined
3699 3699 * @throws NullPointerException if <tt>c</tt> is null
3700 3700 * @since 1.5
3701 3701 */
3702 3702 public static int frequency(Collection<?> c, Object o) {
3703 3703 int result = 0;
3704 3704 if (o == null) {
3705 3705 for (Object e : c)
3706 3706 if (e == null)
3707 3707 result++;
3708 3708 } else {
3709 3709 for (Object e : c)
3710 3710 if (o.equals(e))
3711 3711 result++;
3712 3712 }
3713 3713 return result;
3714 3714 }
3715 3715
3716 3716 /**
3717 3717 * Returns <tt>true</tt> if the two specified collections have no
3718 3718 * elements in common.
3719 3719 *
3720 3720 * <p>Care must be exercised if this method is used on collections that
3721 3721 * do not comply with the general contract for <tt>Collection</tt>.
3722 3722 * Implementations may elect to iterate over either collection and test
3723 3723 * for containment in the other collection (or to perform any equivalent
3724 3724 * computation). If either collection uses a nonstandard equality test
3725 3725 * (as does a {@link SortedSet} whose ordering is not <i>compatible with
3726 3726 * equals</i>, or the key set of an {@link IdentityHashMap}), both
3727 3727 * collections must use the same nonstandard equality test, or the
3728 3728 * result of this method is undefined.
3729 3729 *
3730 3730 * <p>Note that it is permissible to pass the same collection in both
3731 3731 * parameters, in which case the method will return true if and only if
3732 3732 * the collection is empty.
3733 3733 *
3734 3734 * @param c1 a collection
3735 3735 * @param c2 a collection
3736 3736 * @throws NullPointerException if either collection is null
3737 3737 * @since 1.5
3738 3738 */
3739 3739 public static boolean disjoint(Collection<?> c1, Collection<?> c2) {
3740 3740 /*
3741 3741 * We're going to iterate through c1 and test for inclusion in c2.
3742 3742 * If c1 is a Set and c2 isn't, swap the collections. Otherwise,
3743 3743 * place the shorter collection in c1. Hopefully this heuristic
3744 3744 * will minimize the cost of the operation.
3745 3745 */
3746 3746 if ((c1 instanceof Set) && !(c2 instanceof Set) ||
3747 3747 (c1.size() > c2.size())) {
3748 3748 Collection<?> tmp = c1;
3749 3749 c1 = c2;
3750 3750 c2 = tmp;
3751 3751 }
3752 3752
3753 3753 for (Object e : c1)
3754 3754 if (c2.contains(e))
3755 3755 return false;
3756 3756 return true;
3757 3757 }
3758 3758
3759 3759 /**
3760 3760 * Adds all of the specified elements to the specified collection.
3761 3761 * Elements to be added may be specified individually or as an array.
3762 3762 * The behavior of this convenience method is identical to that of
3763 3763 * <tt>c.addAll(Arrays.asList(elements))</tt>, but this method is likely
3764 3764 * to run significantly faster under most implementations.
3765 3765 *
3766 3766 * <p>When elements are specified individually, this method provides a
3767 3767 * convenient way to add a few elements to an existing collection:
3768 3768 * <pre>
3769 3769 * Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");
3770 3770 * </pre>
3771 3771 *
3772 3772 * @param c the collection into which <tt>elements</tt> are to be inserted
3773 3773 * @param elements the elements to insert into <tt>c</tt>
3774 3774 * @return <tt>true</tt> if the collection changed as a result of the call
3775 3775 * @throws UnsupportedOperationException if <tt>c</tt> does not support
3776 3776 * the <tt>add</tt> operation
3777 3777 * @throws NullPointerException if <tt>elements</tt> contains one or more
3778 3778 * null values and <tt>c</tt> does not permit null elements, or
3779 3779 * if <tt>c</tt> or <tt>elements</tt> are <tt>null</tt>
3780 3780 * @throws IllegalArgumentException if some property of a value in
3781 3781 * <tt>elements</tt> prevents it from being added to <tt>c</tt>
3782 3782 * @see Collection#addAll(Collection)
3783 3783 * @since 1.5
3784 3784 */
3785 3785 public static <T> boolean addAll(Collection<? super T> c, T... elements) {
3786 3786 boolean result = false;
3787 3787 for (T element : elements)
3788 3788 result |= c.add(element);
3789 3789 return result;
3790 3790 }
3791 3791
3792 3792 /**
3793 3793 * Returns a set backed by the specified map. The resulting set displays
3794 3794 * the same ordering, concurrency, and performance characteristics as the
3795 3795 * backing map. In essence, this factory method provides a {@link Set}
3796 3796 * implementation corresponding to any {@link Map} implementation. There
3797 3797 * is no need to use this method on a {@link Map} implementation that
3798 3798 * already has a corresponding {@link Set} implementation (such as {@link
3799 3799 * HashMap} or {@link TreeMap}).
3800 3800 *
3801 3801 * <p>Each method invocation on the set returned by this method results in
3802 3802 * exactly one method invocation on the backing map or its <tt>keySet</tt>
3803 3803 * view, with one exception. The <tt>addAll</tt> method is implemented
3804 3804 * as a sequence of <tt>put</tt> invocations on the backing map.
3805 3805 *
3806 3806 * <p>The specified map must be empty at the time this method is invoked,
3807 3807 * and should not be accessed directly after this method returns. These
3808 3808 * conditions are ensured if the map is created empty, passed directly
3809 3809 * to this method, and no reference to the map is retained, as illustrated
3810 3810 * in the following code fragment:
3811 3811 * <pre>
3812 3812 * Set<Object> weakHashSet = Collections.newSetFromMap(
3813 3813 * new WeakHashMap<Object, Boolean>());
3814 3814 * </pre>
3815 3815 *
3816 3816 * @param map the backing map
3817 3817 * @return the set backed by the map
3818 3818 * @throws IllegalArgumentException if <tt>map</tt> is not empty
3819 3819 * @since 1.6
3820 3820 */
3821 3821 public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
3822 3822 return new SetFromMap<E>(map);
3823 3823 }
3824 3824
3825 3825 /**
3826 3826 * @serial include
3827 3827 */
3828 3828 private static class SetFromMap<E> extends AbstractSet<E>
3829 3829 implements Set<E>, Serializable
3830 3830 {
3831 3831 private final Map<E, Boolean> m; // The backing map
3832 3832 private transient Set<E> s; // Its keySet
3833 3833
3834 3834 SetFromMap(Map<E, Boolean> map) {
3835 3835 if (!map.isEmpty())
3836 3836 throw new IllegalArgumentException("Map is non-empty");
3837 3837 m = map;
3838 3838 s = map.keySet();
3839 3839 }
3840 3840
3841 3841 public void clear() { m.clear(); }
3842 3842 public int size() { return m.size(); }
3843 3843 public boolean isEmpty() { return m.isEmpty(); }
3844 3844 public boolean contains(Object o) { return m.containsKey(o); }
3845 3845 public boolean remove(Object o) { return m.remove(o) != null; }
3846 3846 public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; }
3847 3847 public Iterator<E> iterator() { return s.iterator(); }
3848 3848 public Object[] toArray() { return s.toArray(); }
3849 3849 public <T> T[] toArray(T[] a) { return s.toArray(a); }
3850 3850 public String toString() { return s.toString(); }
3851 3851 public int hashCode() { return s.hashCode(); }
3852 3852 public boolean equals(Object o) { return o == this || s.equals(o); }
3853 3853 public boolean containsAll(Collection<?> c) {return s.containsAll(c);}
3854 3854 public boolean removeAll(Collection<?> c) {return s.removeAll(c);}
3855 3855 public boolean retainAll(Collection<?> c) {return s.retainAll(c);}
3856 3856 // addAll is the only inherited implementation
3857 3857
3858 3858 private static final long serialVersionUID = 2454657854757543876L;
3859 3859
3860 3860 private void readObject(java.io.ObjectInputStream stream)
3861 3861 throws IOException, ClassNotFoundException
3862 3862 {
3863 3863 stream.defaultReadObject();
3864 3864 s = m.keySet();
3865 3865 }
3866 3866 }
3867 3867
3868 3868 /**
3869 3869 * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)
3870 3870 * {@link Queue}. Method <tt>add</tt> is mapped to <tt>push</tt>,
3871 3871 * <tt>remove</tt> is mapped to <tt>pop</tt> and so on. This
3872 3872 * view can be useful when you would like to use a method
3873 3873 * requiring a <tt>Queue</tt> but you need Lifo ordering.
3874 3874 *
3875 3875 * <p>Each method invocation on the queue returned by this method
3876 3876 * results in exactly one method invocation on the backing deque, with
3877 3877 * one exception. The {@link Queue#addAll addAll} method is
3878 3878 * implemented as a sequence of {@link Deque#addFirst addFirst}
3879 3879 * invocations on the backing deque.
3880 3880 *
3881 3881 * @param deque the deque
3882 3882 * @return the queue
3883 3883 * @since 1.6
3884 3884 */
3885 3885 public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
3886 3886 return new AsLIFOQueue<T>(deque);
3887 3887 }
3888 3888
3889 3889 /**
3890 3890 * @serial include
3891 3891 */
3892 3892 static class AsLIFOQueue<E> extends AbstractQueue<E>
3893 3893 implements Queue<E>, Serializable {
3894 3894 private static final long serialVersionUID = 1802017725587941708L;
3895 3895 private final Deque<E> q;
3896 3896 AsLIFOQueue(Deque<E> q) { this.q = q; }
3897 3897 public boolean add(E e) { q.addFirst(e); return true; }
3898 3898 public boolean offer(E e) { return q.offerFirst(e); }
3899 3899 public E poll() { return q.pollFirst(); }
3900 3900 public E remove() { return q.removeFirst(); }
3901 3901 public E peek() { return q.peekFirst(); }
3902 3902 public E element() { return q.getFirst(); }
3903 3903 public void clear() { q.clear(); }
3904 3904 public int size() { return q.size(); }
3905 3905 public boolean isEmpty() { return q.isEmpty(); }
3906 3906 public boolean contains(Object o) { return q.contains(o); }
3907 3907 public boolean remove(Object o) { return q.remove(o); }
3908 3908 public Iterator<E> iterator() { return q.iterator(); }
3909 3909 public Object[] toArray() { return q.toArray(); }
3910 3910 public <T> T[] toArray(T[] a) { return q.toArray(a); }
3911 3911 public String toString() { return q.toString(); }
3912 3912 public boolean containsAll(Collection<?> c) {return q.containsAll(c);}
3913 3913 public boolean removeAll(Collection<?> c) {return q.removeAll(c);}
3914 3914 public boolean retainAll(Collection<?> c) {return q.retainAll(c);}
3915 3915 // We use inherited addAll; forwarding addAll would be wrong
3916 3916 }
3917 3917 }
↓ open down ↓ |
456 lines elided |
↑ open up ↑ |
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX