ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Collections.java
Revision: 1.8
Committed: Wed May 25 14:05:06 2005 UTC (18 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.7: +1 -0 lines
Log Message:
Avoid generics warnings

File Contents

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