ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Collections.java
Revision: 1.5
Committed: Mon May 2 08:35:49 2005 UTC (19 years ago) by jsr166
Branch: MAIN
Changes since 1.4: +20 -20 lines
Log Message:
E o -> E e

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
1055 public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
1056 return new UnmodifiableSet<T>(s);
1057 }
1058
1059 /**
1060 * @serial include
1061 */
1062 static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
1063 implements Set<E>, Serializable {
1064 private static final long serialVersionUID = -9215047833775013803L;
1065
1066 UnmodifiableSet(Set<? extends E> s) {super(s);}
1067 public boolean equals(Object o) {return c.equals(o);}
1068 public int hashCode() {return c.hashCode();}
1069 }
1070
1071 /**
1072 * Returns an unmodifiable view of the specified sorted set. This method
1073 * allows modules to provide users with "read-only" access to internal
1074 * sorted sets. Query operations on the returned sorted set "read
1075 * through" to the specified sorted set. Attempts to modify the returned
1076 * sorted set, whether direct, via its iterator, or via its
1077 * <tt>subSet</tt>, <tt>headSet</tt>, or <tt>tailSet</tt> views, result in
1078 * an <tt>UnsupportedOperationException</tt>.<p>
1079 *
1080 * The returned sorted set will be serializable if the specified sorted set
1081 * is serializable.
1082 *
1083 * @param s the sorted set for which an unmodifiable view is to be
1084 * returned.
1085 * @return an unmodifiable view of the specified sorted set.
1086 */
1087 public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
1088 return new UnmodifiableSortedSet<T>(s);
1089 }
1090
1091 /**
1092 * @serial include
1093 */
1094 static class UnmodifiableSortedSet<E>
1095 extends UnmodifiableSet<E>
1096 implements SortedSet<E>, Serializable {
1097 private static final long serialVersionUID = -4929149591599911165L;
1098 private final SortedSet<E> ss;
1099
1100 UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}
1101
1102 public Comparator<? super E> comparator() {return ss.comparator();}
1103
1104 public SortedSet<E> subSet(E fromElement, E toElement) {
1105 return new UnmodifiableSortedSet<E>(ss.subSet(fromElement,toElement));
1106 }
1107 public SortedSet<E> headSet(E toElement) {
1108 return new UnmodifiableSortedSet<E>(ss.headSet(toElement));
1109 }
1110 public SortedSet<E> tailSet(E fromElement) {
1111 return new UnmodifiableSortedSet<E>(ss.tailSet(fromElement));
1112 }
1113
1114 public E first() {return ss.first();}
1115 public E last() {return ss.last();}
1116 }
1117
1118 /**
1119 * Returns an unmodifiable view of the specified list. This method allows
1120 * modules to provide users with "read-only" access to internal
1121 * lists. Query operations on the returned list "read through" to the
1122 * specified list, and attempts to modify the returned list, whether
1123 * direct or via its iterator, result in an
1124 * <tt>UnsupportedOperationException</tt>.<p>
1125 *
1126 * The returned list will be serializable if the specified list
1127 * is serializable. Similarly, the returned list will implement
1128 * {@link RandomAccess} if the specified list does.
1129 *
1130 * @param list the list for which an unmodifiable view is to be returned.
1131 * @return an unmodifiable view of the specified list.
1132 */
1133 public static <T> List<T> unmodifiableList(List<? extends T> list) {
1134 return (list instanceof RandomAccess ?
1135 new UnmodifiableRandomAccessList<T>(list) :
1136 new UnmodifiableList<T>(list));
1137 }
1138
1139 /**
1140 * @serial include
1141 */
1142 static class UnmodifiableList<E> extends UnmodifiableCollection<E>
1143 implements List<E> {
1144 static final long serialVersionUID = -283967356065247728L;
1145 final List<? extends E> list;
1146
1147 UnmodifiableList(List<? extends E> list) {
1148 super(list);
1149 this.list = list;
1150 }
1151
1152 public boolean equals(Object o) {return list.equals(o);}
1153 public int hashCode() {return list.hashCode();}
1154
1155 public E get(int index) {return list.get(index);}
1156 public E set(int index, E element) {
1157 throw new UnsupportedOperationException();
1158 }
1159 public void add(int index, E element) {
1160 throw new UnsupportedOperationException();
1161 }
1162 public E remove(int index) {
1163 throw new UnsupportedOperationException();
1164 }
1165 public int indexOf(Object o) {return list.indexOf(o);}
1166 public int lastIndexOf(Object o) {return list.lastIndexOf(o);}
1167 public boolean addAll(int index, Collection<? extends E> c) {
1168 throw new UnsupportedOperationException();
1169 }
1170 public ListIterator<E> listIterator() {return listIterator(0);}
1171
1172 public ListIterator<E> listIterator(final int index) {
1173 return new ListIterator<E>() {
1174 ListIterator<? extends E> i = list.listIterator(index);
1175
1176 public boolean hasNext() {return i.hasNext();}
1177 public E next() {return i.next();}
1178 public boolean hasPrevious() {return i.hasPrevious();}
1179 public E previous() {return i.previous();}
1180 public int nextIndex() {return i.nextIndex();}
1181 public int previousIndex() {return i.previousIndex();}
1182
1183 public void remove() {
1184 throw new UnsupportedOperationException();
1185 }
1186 public void set(E e) {
1187 throw new UnsupportedOperationException();
1188 }
1189 public void add(E e) {
1190 throw new UnsupportedOperationException();
1191 }
1192 };
1193 }
1194
1195 public List<E> subList(int fromIndex, int toIndex) {
1196 return new UnmodifiableList<E>(list.subList(fromIndex, toIndex));
1197 }
1198
1199 /**
1200 * UnmodifiableRandomAccessList instances are serialized as
1201 * UnmodifiableList instances to allow them to be deserialized
1202 * in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList).
1203 * This method inverts the transformation. As a beneficial
1204 * side-effect, it also grafts the RandomAccess marker onto
1205 * UnmodifiableList instances that were serialized in pre-1.4 JREs.
1206 *
1207 * Note: Unfortunately, UnmodifiableRandomAccessList instances
1208 * serialized in 1.4.1 and deserialized in 1.4 will become
1209 * UnmodifiableList instances, as this method was missing in 1.4.
1210 */
1211 private Object readResolve() {
1212 return (list instanceof RandomAccess
1213 ? new UnmodifiableRandomAccessList<E>(list)
1214 : this);
1215 }
1216 }
1217
1218 /**
1219 * @serial include
1220 */
1221 static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E>
1222 implements RandomAccess
1223 {
1224 UnmodifiableRandomAccessList(List<? extends E> list) {
1225 super(list);
1226 }
1227
1228 public List<E> subList(int fromIndex, int toIndex) {
1229 return new UnmodifiableRandomAccessList<E>(
1230 list.subList(fromIndex, toIndex));
1231 }
1232
1233 private static final long serialVersionUID = -2542308836966382001L;
1234
1235 /**
1236 * Allows instances to be deserialized in pre-1.4 JREs (which do
1237 * not have UnmodifiableRandomAccessList). UnmodifiableList has
1238 * a readResolve method that inverts this transformation upon
1239 * deserialization.
1240 */
1241 private Object writeReplace() {
1242 return new UnmodifiableList<E>(list);
1243 }
1244 }
1245
1246 /**
1247 * Returns an unmodifiable view of the specified map. This method
1248 * allows modules to provide users with "read-only" access to internal
1249 * maps. Query operations on the returned map "read through"
1250 * to the specified map, and attempts to modify the returned
1251 * map, whether direct or via its collection views, result in an
1252 * <tt>UnsupportedOperationException</tt>.<p>
1253 *
1254 * The returned map will be serializable if the specified map
1255 * is serializable.
1256 *
1257 * @param m the map for which an unmodifiable view is to be returned.
1258 * @return an unmodifiable view of the specified map.
1259 */
1260 public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
1261 return new UnmodifiableMap<K,V>(m);
1262 }
1263
1264 /**
1265 * @serial include
1266 */
1267 private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {
1268 // use serialVersionUID from JDK 1.2.2 for interoperability
1269 private static final long serialVersionUID = -1034234728574286014L;
1270
1271 private final Map<? extends K, ? extends V> m;
1272
1273 UnmodifiableMap(Map<? extends K, ? extends V> m) {
1274 if (m==null)
1275 throw new NullPointerException();
1276 this.m = m;
1277 }
1278
1279 public int size() {return m.size();}
1280 public boolean isEmpty() {return m.isEmpty();}
1281 public boolean containsKey(Object key) {return m.containsKey(key);}
1282 public boolean containsValue(Object val) {return m.containsValue(val);}
1283 public V get(Object key) {return m.get(key);}
1284
1285 public V put(K key, V value) {
1286 throw new UnsupportedOperationException();
1287 }
1288 public V remove(Object key) {
1289 throw new UnsupportedOperationException();
1290 }
1291 public void putAll(Map<? extends K, ? extends V> t) {
1292 throw new UnsupportedOperationException();
1293 }
1294 public void clear() {
1295 throw new UnsupportedOperationException();
1296 }
1297
1298 private transient Set<K> keySet = null;
1299 private transient Set<Map.Entry<K,V>> entrySet = null;
1300 private transient Collection<V> values = null;
1301
1302 public Set<K> keySet() {
1303 if (keySet==null)
1304 keySet = unmodifiableSet(m.keySet());
1305 return keySet;
1306 }
1307
1308 public Set<Map.Entry<K,V>> entrySet() {
1309 if (entrySet==null)
1310 entrySet = new UnmodifiableEntrySet<K,V>(m.entrySet());
1311 return entrySet;
1312 }
1313
1314 public Collection<V> values() {
1315 if (values==null)
1316 values = unmodifiableCollection(m.values());
1317 return values;
1318 }
1319
1320 public boolean equals(Object o) {return m.equals(o);}
1321 public int hashCode() {return m.hashCode();}
1322 public String toString() {return m.toString();}
1323
1324 /**
1325 * We need this class in addition to UnmodifiableSet as
1326 * Map.Entries themselves permit modification of the backing Map
1327 * via their setValue operation. This class is subtle: there are
1328 * many possible attacks that must be thwarted.
1329 *
1330 * @serial include
1331 */
1332 static class UnmodifiableEntrySet<K,V>
1333 extends UnmodifiableSet<Map.Entry<K,V>> {
1334 private static final long serialVersionUID = 7854390611657943733L;
1335
1336 UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) {
1337 super((Set)s);
1338 }
1339 public Iterator<Map.Entry<K,V>> iterator() {
1340 return new Iterator<Map.Entry<K,V>>() {
1341 Iterator<? extends Map.Entry<? extends K, ? extends V>> i = c.iterator();
1342
1343 public boolean hasNext() {
1344 return i.hasNext();
1345 }
1346 public Map.Entry<K,V> next() {
1347 return new UnmodifiableEntry<K,V>(i.next());
1348 }
1349 public void remove() {
1350 throw new UnsupportedOperationException();
1351 }
1352 };
1353 }
1354
1355 public Object[] toArray() {
1356 Object[] a = c.toArray();
1357 for (int i=0; i<a.length; i++)
1358 a[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)a[i]);
1359 return a;
1360 }
1361
1362 public <T> T[] toArray(T[] a) {
1363 // We don't pass a to c.toArray, to avoid window of
1364 // vulnerability wherein an unscrupulous multithreaded client
1365 // could get his hands on raw (unwrapped) Entries from c.
1366 Object[] arr =
1367 c.toArray(
1368 a.length==0 ? a :
1369 (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), 0));
1370
1371 for (int i=0; i<arr.length; i++)
1372 arr[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)arr[i]);
1373
1374 if (arr.length > a.length)
1375 return (T[])arr;
1376
1377 System.arraycopy(arr, 0, a, 0, arr.length);
1378 if (a.length > arr.length)
1379 a[arr.length] = null;
1380 return a;
1381 }
1382
1383 /**
1384 * This method is overridden to protect the backing set against
1385 * an object with a nefarious equals function that senses
1386 * that the equality-candidate is Map.Entry and calls its
1387 * setValue method.
1388 */
1389 public boolean contains(Object o) {
1390 if (!(o instanceof Map.Entry))
1391 return false;
1392 return c.contains(new UnmodifiableEntry<K,V>((Map.Entry<K,V>) o));
1393 }
1394
1395 /**
1396 * The next two methods are overridden to protect against
1397 * an unscrupulous List whose contains(Object o) method senses
1398 * when o is a Map.Entry, and calls o.setValue.
1399 */
1400 public boolean containsAll(Collection<?> coll) {
1401 Iterator<?> e = coll.iterator();
1402 while (e.hasNext())
1403 if (!contains(e.next())) // Invokes safe contains() above
1404 return false;
1405 return true;
1406 }
1407 public boolean equals(Object o) {
1408 if (o == this)
1409 return true;
1410
1411 if (!(o instanceof Set))
1412 return false;
1413 Set s = (Set) o;
1414 if (s.size() != c.size())
1415 return false;
1416 return containsAll(s); // Invokes safe containsAll() above
1417 }
1418
1419 /**
1420 * This "wrapper class" serves two purposes: it prevents
1421 * the client from modifying the backing Map, by short-circuiting
1422 * the setValue method, and it protects the backing Map against
1423 * an ill-behaved Map.Entry that attempts to modify another
1424 * Map Entry when asked to perform an equality check.
1425 */
1426 private static class UnmodifiableEntry<K,V> implements Map.Entry<K,V> {
1427 private Map.Entry<? extends K, ? extends V> e;
1428
1429 UnmodifiableEntry(Map.Entry<? extends K, ? extends V> e) {this.e = e;}
1430
1431 public K getKey() {return e.getKey();}
1432 public V getValue() {return e.getValue();}
1433 public V setValue(V value) {
1434 throw new UnsupportedOperationException();
1435 }
1436 public int hashCode() {return e.hashCode();}
1437 public boolean equals(Object o) {
1438 if (!(o instanceof Map.Entry))
1439 return false;
1440 Map.Entry t = (Map.Entry)o;
1441 return eq(e.getKey(), t.getKey()) &&
1442 eq(e.getValue(), t.getValue());
1443 }
1444 public String toString() {return e.toString();}
1445 }
1446 }
1447 }
1448
1449 /**
1450 * Returns an unmodifiable view of the specified sorted map. This method
1451 * allows modules to provide users with "read-only" access to internal
1452 * sorted maps. Query operations on the returned sorted map "read through"
1453 * to the specified sorted map. Attempts to modify the returned
1454 * sorted map, whether direct, via its collection views, or via its
1455 * <tt>subMap</tt>, <tt>headMap</tt>, or <tt>tailMap</tt> views, result in
1456 * an <tt>UnsupportedOperationException</tt>.<p>
1457 *
1458 * The returned sorted map will be serializable if the specified sorted map
1459 * is serializable.
1460 *
1461 * @param m the sorted map for which an unmodifiable view is to be
1462 * returned.
1463 * @return an unmodifiable view of the specified sorted map.
1464 */
1465 public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {
1466 return new UnmodifiableSortedMap<K,V>(m);
1467 }
1468
1469 /**
1470 * @serial include
1471 */
1472 static class UnmodifiableSortedMap<K,V>
1473 extends UnmodifiableMap<K,V>
1474 implements SortedMap<K,V>, Serializable {
1475 private static final long serialVersionUID = -8806743815996713206L;
1476
1477 private final SortedMap<K, ? extends V> sm;
1478
1479 UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m;}
1480
1481 public Comparator<? super K> comparator() {return sm.comparator();}
1482
1483 public SortedMap<K,V> subMap(K fromKey, K toKey) {
1484 return new UnmodifiableSortedMap<K,V>(sm.subMap(fromKey, toKey));
1485 }
1486 public SortedMap<K,V> headMap(K toKey) {
1487 return new UnmodifiableSortedMap<K,V>(sm.headMap(toKey));
1488 }
1489 public SortedMap<K,V> tailMap(K fromKey) {
1490 return new UnmodifiableSortedMap<K,V>(sm.tailMap(fromKey));
1491 }
1492
1493 public K firstKey() {return sm.firstKey();}
1494 public K lastKey() {return sm.lastKey();}
1495 }
1496
1497
1498 // Synch Wrappers
1499
1500 /**
1501 * Returns a synchronized (thread-safe) collection backed by the specified
1502 * collection. In order to guarantee serial access, it is critical that
1503 * <strong>all</strong> access to the backing collection is accomplished
1504 * through the returned collection.<p>
1505 *
1506 * It is imperative that the user manually synchronize on the returned
1507 * collection when iterating over it:
1508 * <pre>
1509 * Collection c = Collections.synchronizedCollection(myCollection);
1510 * ...
1511 * synchronized(c) {
1512 * Iterator i = c.iterator(); // Must be in the synchronized block
1513 * while (i.hasNext())
1514 * foo(i.next());
1515 * }
1516 * </pre>
1517 * Failure to follow this advice may result in non-deterministic behavior.
1518 *
1519 * <p>The returned collection does <i>not</i> pass the <tt>hashCode</tt>
1520 * and <tt>equals</tt> operations through to the backing collection, but
1521 * relies on <tt>Object</tt>'s equals and hashCode methods. This is
1522 * necessary to preserve the contracts of these operations in the case
1523 * that the backing collection is a set or a list.<p>
1524 *
1525 * The returned collection will be serializable if the specified collection
1526 * is serializable.
1527 *
1528 * @param c the collection to be "wrapped" in a synchronized collection.
1529 * @return a synchronized view of the specified collection.
1530 */
1531 public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
1532 return new SynchronizedCollection<T>(c);
1533 }
1534
1535 static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {
1536 return new SynchronizedCollection<T>(c, mutex);
1537 }
1538
1539 /**
1540 * @serial include
1541 */
1542 static class SynchronizedCollection<E> implements Collection<E>, Serializable {
1543 // use serialVersionUID from JDK 1.2.2 for interoperability
1544 private static final long serialVersionUID = 3053995032091335093L;
1545
1546 final Collection<E> c; // Backing Collection
1547 final Object mutex; // Object on which to synchronize
1548
1549 SynchronizedCollection(Collection<E> c) {
1550 if (c==null)
1551 throw new NullPointerException();
1552 this.c = c;
1553 mutex = this;
1554 }
1555 SynchronizedCollection(Collection<E> c, Object mutex) {
1556 this.c = c;
1557 this.mutex = mutex;
1558 }
1559
1560 public int size() {
1561 synchronized(mutex) {return c.size();}
1562 }
1563 public boolean isEmpty() {
1564 synchronized(mutex) {return c.isEmpty();}
1565 }
1566 public boolean contains(Object o) {
1567 synchronized(mutex) {return c.contains(o);}
1568 }
1569 public Object[] toArray() {
1570 synchronized(mutex) {return c.toArray();}
1571 }
1572 public <T> T[] toArray(T[] a) {
1573 synchronized(mutex) {return c.toArray(a);}
1574 }
1575
1576 public Iterator<E> iterator() {
1577 return c.iterator(); // Must be manually synched by user!
1578 }
1579
1580 public boolean add(E e) {
1581 synchronized(mutex) {return c.add(e);}
1582 }
1583 public boolean remove(Object o) {
1584 synchronized(mutex) {return c.remove(o);}
1585 }
1586
1587 public boolean containsAll(Collection<?> coll) {
1588 synchronized(mutex) {return c.containsAll(coll);}
1589 }
1590 public boolean addAll(Collection<? extends E> coll) {
1591 synchronized(mutex) {return c.addAll(coll);}
1592 }
1593 public boolean removeAll(Collection<?> coll) {
1594 synchronized(mutex) {return c.removeAll(coll);}
1595 }
1596 public boolean retainAll(Collection<?> coll) {
1597 synchronized(mutex) {return c.retainAll(coll);}
1598 }
1599 public void clear() {
1600 synchronized(mutex) {c.clear();}
1601 }
1602 public String toString() {
1603 synchronized(mutex) {return c.toString();}
1604 }
1605 private void writeObject(ObjectOutputStream s) throws IOException {
1606 synchronized(mutex) {s.defaultWriteObject();}
1607 }
1608 }
1609
1610 /**
1611 * Returns a synchronized (thread-safe) set backed by the specified
1612 * set. In order to guarantee serial access, it is critical that
1613 * <strong>all</strong> access to the backing set is accomplished
1614 * through the returned set.<p>
1615 *
1616 * It is imperative that the user manually synchronize on the returned
1617 * set when iterating over it:
1618 * <pre>
1619 * Set s = Collections.synchronizedSet(new HashSet());
1620 * ...
1621 * synchronized(s) {
1622 * Iterator i = s.iterator(); // Must be in the synchronized block
1623 * while (i.hasNext())
1624 * foo(i.next());
1625 * }
1626 * </pre>
1627 * Failure to follow this advice may result in non-deterministic behavior.
1628 *
1629 * <p>The returned set will be serializable if the specified set is
1630 * serializable.
1631 *
1632 * @param s the set to be "wrapped" in a synchronized set.
1633 * @return a synchronized view of the specified set.
1634 */
1635 public static <T> Set<T> synchronizedSet(Set<T> s) {
1636 return new SynchronizedSet<T>(s);
1637 }
1638
1639 static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {
1640 return new SynchronizedSet<T>(s, mutex);
1641 }
1642
1643 /**
1644 * @serial include
1645 */
1646 static class SynchronizedSet<E>
1647 extends SynchronizedCollection<E>
1648 implements Set<E> {
1649 private static final long serialVersionUID = 487447009682186044L;
1650
1651 SynchronizedSet(Set<E> s) {
1652 super(s);
1653 }
1654 SynchronizedSet(Set<E> s, Object mutex) {
1655 super(s, mutex);
1656 }
1657
1658 public boolean equals(Object o) {
1659 synchronized(mutex) {return c.equals(o);}
1660 }
1661 public int hashCode() {
1662 synchronized(mutex) {return c.hashCode();}
1663 }
1664 }
1665
1666 /**
1667 * Returns a synchronized (thread-safe) sorted set backed by the specified
1668 * sorted set. In order to guarantee serial access, it is critical that
1669 * <strong>all</strong> access to the backing sorted set is accomplished
1670 * through the returned sorted set (or its views).<p>
1671 *
1672 * It is imperative that the user manually synchronize on the returned
1673 * sorted set when iterating over it or any of its <tt>subSet</tt>,
1674 * <tt>headSet</tt>, or <tt>tailSet</tt> views.
1675 * <pre>
1676 * SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
1677 * ...
1678 * synchronized(s) {
1679 * Iterator i = s.iterator(); // Must be in the synchronized block
1680 * while (i.hasNext())
1681 * foo(i.next());
1682 * }
1683 * </pre>
1684 * or:
1685 * <pre>
1686 * SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
1687 * SortedSet s2 = s.headSet(foo);
1688 * ...
1689 * synchronized(s) { // Note: s, not s2!!!
1690 * Iterator i = s2.iterator(); // Must be in the synchronized block
1691 * while (i.hasNext())
1692 * foo(i.next());
1693 * }
1694 * </pre>
1695 * Failure to follow this advice may result in non-deterministic behavior.
1696 *
1697 * <p>The returned sorted set will be serializable if the specified
1698 * sorted set is serializable.
1699 *
1700 * @param s the sorted set to be "wrapped" in a synchronized sorted set.
1701 * @return a synchronized view of the specified sorted set.
1702 */
1703 public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) {
1704 return new SynchronizedSortedSet<T>(s);
1705 }
1706
1707 /**
1708 * @serial include
1709 */
1710 static class SynchronizedSortedSet<E>
1711 extends SynchronizedSet<E>
1712 implements SortedSet<E>
1713 {
1714 private static final long serialVersionUID = 8695801310862127406L;
1715
1716 final private SortedSet<E> ss;
1717
1718 SynchronizedSortedSet(SortedSet<E> s) {
1719 super(s);
1720 ss = s;
1721 }
1722 SynchronizedSortedSet(SortedSet<E> s, Object mutex) {
1723 super(s, mutex);
1724 ss = s;
1725 }
1726
1727 public Comparator<? super E> comparator() {
1728 synchronized(mutex) {return ss.comparator();}
1729 }
1730
1731 public SortedSet<E> subSet(E fromElement, E toElement) {
1732 synchronized(mutex) {
1733 return new SynchronizedSortedSet<E>(
1734 ss.subSet(fromElement, toElement), mutex);
1735 }
1736 }
1737 public SortedSet<E> headSet(E toElement) {
1738 synchronized(mutex) {
1739 return new SynchronizedSortedSet<E>(ss.headSet(toElement), mutex);
1740 }
1741 }
1742 public SortedSet<E> tailSet(E fromElement) {
1743 synchronized(mutex) {
1744 return new SynchronizedSortedSet<E>(ss.tailSet(fromElement),mutex);
1745 }
1746 }
1747
1748 public E first() {
1749 synchronized(mutex) {return ss.first();}
1750 }
1751 public E last() {
1752 synchronized(mutex) {return ss.last();}
1753 }
1754 }
1755
1756 /**
1757 * Returns a synchronized (thread-safe) list backed by the specified
1758 * list. In order to guarantee serial access, it is critical that
1759 * <strong>all</strong> access to the backing list is accomplished
1760 * through the returned list.<p>
1761 *
1762 * It is imperative that the user manually synchronize on the returned
1763 * list when iterating over it:
1764 * <pre>
1765 * List list = Collections.synchronizedList(new ArrayList());
1766 * ...
1767 * synchronized(list) {
1768 * Iterator i = list.iterator(); // Must be in synchronized block
1769 * while (i.hasNext())
1770 * foo(i.next());
1771 * }
1772 * </pre>
1773 * Failure to follow this advice may result in non-deterministic behavior.
1774 *
1775 * <p>The returned list will be serializable if the specified list is
1776 * serializable.
1777 *
1778 * @param list the list to be "wrapped" in a synchronized list.
1779 * @return a synchronized view of the specified list.
1780 */
1781 public static <T> List<T> synchronizedList(List<T> list) {
1782 return (list instanceof RandomAccess ?
1783 new SynchronizedRandomAccessList<T>(list) :
1784 new SynchronizedList<T>(list));
1785 }
1786
1787 static <T> List<T> synchronizedList(List<T> list, Object mutex) {
1788 return (list instanceof RandomAccess ?
1789 new SynchronizedRandomAccessList<T>(list, mutex) :
1790 new SynchronizedList<T>(list, mutex));
1791 }
1792
1793 /**
1794 * @serial include
1795 */
1796 static class SynchronizedList<E>
1797 extends SynchronizedCollection<E>
1798 implements List<E> {
1799 static final long serialVersionUID = -7754090372962971524L;
1800
1801 final List<E> list;
1802
1803 SynchronizedList(List<E> list) {
1804 super(list);
1805 this.list = list;
1806 }
1807 SynchronizedList(List<E> list, Object mutex) {
1808 super(list, mutex);
1809 this.list = list;
1810 }
1811
1812 public boolean equals(Object o) {
1813 synchronized(mutex) {return list.equals(o);}
1814 }
1815 public int hashCode() {
1816 synchronized(mutex) {return list.hashCode();}
1817 }
1818
1819 public E get(int index) {
1820 synchronized(mutex) {return list.get(index);}
1821 }
1822 public E set(int index, E element) {
1823 synchronized(mutex) {return list.set(index, element);}
1824 }
1825 public void add(int index, E element) {
1826 synchronized(mutex) {list.add(index, element);}
1827 }
1828 public E remove(int index) {
1829 synchronized(mutex) {return list.remove(index);}
1830 }
1831
1832 public int indexOf(Object o) {
1833 synchronized(mutex) {return list.indexOf(o);}
1834 }
1835 public int lastIndexOf(Object o) {
1836 synchronized(mutex) {return list.lastIndexOf(o);}
1837 }
1838
1839 public boolean addAll(int index, Collection<? extends E> c) {
1840 synchronized(mutex) {return list.addAll(index, c);}
1841 }
1842
1843 public ListIterator<E> listIterator() {
1844 return list.listIterator(); // Must be manually synched by user
1845 }
1846
1847 public ListIterator<E> listIterator(int index) {
1848 return list.listIterator(index); // Must be manually synched by user
1849 }
1850
1851 public List<E> subList(int fromIndex, int toIndex) {
1852 synchronized(mutex) {
1853 return new SynchronizedList<E>(list.subList(fromIndex, toIndex),
1854 mutex);
1855 }
1856 }
1857
1858 /**
1859 * SynchronizedRandomAccessList instances are serialized as
1860 * SynchronizedList instances to allow them to be deserialized
1861 * in pre-1.4 JREs (which do not have SynchronizedRandomAccessList).
1862 * This method inverts the transformation. As a beneficial
1863 * side-effect, it also grafts the RandomAccess marker onto
1864 * SynchronizedList instances that were serialized in pre-1.4 JREs.
1865 *
1866 * Note: Unfortunately, SynchronizedRandomAccessList instances
1867 * serialized in 1.4.1 and deserialized in 1.4 will become
1868 * SynchronizedList instances, as this method was missing in 1.4.
1869 */
1870 private Object readResolve() {
1871 return (list instanceof RandomAccess
1872 ? new SynchronizedRandomAccessList<E>(list)
1873 : this);
1874 }
1875 }
1876
1877 /**
1878 * @serial include
1879 */
1880 static class SynchronizedRandomAccessList<E>
1881 extends SynchronizedList<E>
1882 implements RandomAccess {
1883
1884 SynchronizedRandomAccessList(List<E> list) {
1885 super(list);
1886 }
1887
1888 SynchronizedRandomAccessList(List<E> list, Object mutex) {
1889 super(list, mutex);
1890 }
1891
1892 public List<E> subList(int fromIndex, int toIndex) {
1893 synchronized(mutex) {
1894 return new SynchronizedRandomAccessList<E>(
1895 list.subList(fromIndex, toIndex), mutex);
1896 }
1897 }
1898
1899 static final long serialVersionUID = 1530674583602358482L;
1900
1901 /**
1902 * Allows instances to be deserialized in pre-1.4 JREs (which do
1903 * not have SynchronizedRandomAccessList). SynchronizedList has
1904 * a readResolve method that inverts this transformation upon
1905 * deserialization.
1906 */
1907 private Object writeReplace() {
1908 return new SynchronizedList<E>(list);
1909 }
1910 }
1911
1912 /**
1913 * Returns a synchronized (thread-safe) map backed by the specified
1914 * map. In order to guarantee serial access, it is critical that
1915 * <strong>all</strong> access to the backing map is accomplished
1916 * through the returned map.<p>
1917 *
1918 * It is imperative that the user manually synchronize on the returned
1919 * map when iterating over any of its collection views:
1920 * <pre>
1921 * Map m = Collections.synchronizedMap(new HashMap());
1922 * ...
1923 * Set s = m.keySet(); // Needn't be in synchronized block
1924 * ...
1925 * synchronized(m) { // Synchronizing on m, not s!
1926 * Iterator i = s.iterator(); // Must be in synchronized block
1927 * while (i.hasNext())
1928 * foo(i.next());
1929 * }
1930 * </pre>
1931 * Failure to follow this advice may result in non-deterministic behavior.
1932 *
1933 * <p>The returned map will be serializable if the specified map is
1934 * serializable.
1935 *
1936 * @param m the map to be "wrapped" in a synchronized map.
1937 * @return a synchronized view of the specified map.
1938 */
1939 public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
1940 return new SynchronizedMap<K,V>(m);
1941 }
1942
1943 /**
1944 * @serial include
1945 */
1946 private static class SynchronizedMap<K,V>
1947 implements Map<K,V>, Serializable {
1948 // use serialVersionUID from JDK 1.2.2 for interoperability
1949 private static final long serialVersionUID = 1978198479659022715L;
1950
1951 private final Map<K,V> m; // Backing Map
1952 final Object mutex; // Object on which to synchronize
1953
1954 SynchronizedMap(Map<K,V> m) {
1955 if (m==null)
1956 throw new NullPointerException();
1957 this.m = m;
1958 mutex = this;
1959 }
1960
1961 SynchronizedMap(Map<K,V> m, Object mutex) {
1962 this.m = m;
1963 this.mutex = mutex;
1964 }
1965
1966 public int size() {
1967 synchronized(mutex) {return m.size();}
1968 }
1969 public boolean isEmpty(){
1970 synchronized(mutex) {return m.isEmpty();}
1971 }
1972 public boolean containsKey(Object key) {
1973 synchronized(mutex) {return m.containsKey(key);}
1974 }
1975 public boolean containsValue(Object value){
1976 synchronized(mutex) {return m.containsValue(value);}
1977 }
1978 public V get(Object key) {
1979 synchronized(mutex) {return m.get(key);}
1980 }
1981
1982 public V put(K key, V value) {
1983 synchronized(mutex) {return m.put(key, value);}
1984 }
1985 public V remove(Object key) {
1986 synchronized(mutex) {return m.remove(key);}
1987 }
1988 public void putAll(Map<? extends K, ? extends V> map) {
1989 synchronized(mutex) {m.putAll(map);}
1990 }
1991 public void clear() {
1992 synchronized(mutex) {m.clear();}
1993 }
1994
1995 private transient Set<K> keySet = null;
1996 private transient Set<Map.Entry<K,V>> entrySet = null;
1997 private transient Collection<V> values = null;
1998
1999 public Set<K> keySet() {
2000 synchronized(mutex) {
2001 if (keySet==null)
2002 keySet = new SynchronizedSet<K>(m.keySet(), mutex);
2003 return keySet;
2004 }
2005 }
2006
2007 public Set<Map.Entry<K,V>> entrySet() {
2008 synchronized(mutex) {
2009 if (entrySet==null)
2010 entrySet = new SynchronizedSet<Map.Entry<K,V>>(m.entrySet(), mutex);
2011 return entrySet;
2012 }
2013 }
2014
2015 public Collection<V> values() {
2016 synchronized(mutex) {
2017 if (values==null)
2018 values = new SynchronizedCollection<V>(m.values(), mutex);
2019 return values;
2020 }
2021 }
2022
2023 public boolean equals(Object o) {
2024 synchronized(mutex) {return m.equals(o);}
2025 }
2026 public int hashCode() {
2027 synchronized(mutex) {return m.hashCode();}
2028 }
2029 public String toString() {
2030 synchronized(mutex) {return m.toString();}
2031 }
2032 private void writeObject(ObjectOutputStream s) throws IOException {
2033 synchronized(mutex) {s.defaultWriteObject();}
2034 }
2035 }
2036
2037 /**
2038 * Returns a synchronized (thread-safe) sorted map backed by the specified
2039 * sorted map. In order to guarantee serial access, it is critical that
2040 * <strong>all</strong> access to the backing sorted map is accomplished
2041 * through the returned sorted map (or its views).<p>
2042 *
2043 * It is imperative that the user manually synchronize on the returned
2044 * sorted map when iterating over any of its collection views, or the
2045 * collections views of any of its <tt>subMap</tt>, <tt>headMap</tt> or
2046 * <tt>tailMap</tt> views.
2047 * <pre>
2048 * SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2049 * ...
2050 * Set s = m.keySet(); // Needn't be in synchronized block
2051 * ...
2052 * synchronized(m) { // Synchronizing on m, not s!
2053 * Iterator i = s.iterator(); // Must be in synchronized block
2054 * while (i.hasNext())
2055 * foo(i.next());
2056 * }
2057 * </pre>
2058 * or:
2059 * <pre>
2060 * SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2061 * SortedMap m2 = m.subMap(foo, bar);
2062 * ...
2063 * Set s2 = m2.keySet(); // Needn't be in synchronized block
2064 * ...
2065 * synchronized(m) { // Synchronizing on m, not m2 or s2!
2066 * Iterator i = s.iterator(); // Must be in synchronized block
2067 * while (i.hasNext())
2068 * foo(i.next());
2069 * }
2070 * </pre>
2071 * Failure to follow this advice may result in non-deterministic behavior.
2072 *
2073 * <p>The returned sorted map will be serializable if the specified
2074 * sorted map is serializable.
2075 *
2076 * @param m the sorted map to be "wrapped" in a synchronized sorted map.
2077 * @return a synchronized view of the specified sorted map.
2078 */
2079 public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {
2080 return new SynchronizedSortedMap<K,V>(m);
2081 }
2082
2083
2084 /**
2085 * @serial include
2086 */
2087 static class SynchronizedSortedMap<K,V>
2088 extends SynchronizedMap<K,V>
2089 implements SortedMap<K,V>
2090 {
2091 private static final long serialVersionUID = -8798146769416483793L;
2092
2093 private final SortedMap<K,V> sm;
2094
2095 SynchronizedSortedMap(SortedMap<K,V> m) {
2096 super(m);
2097 sm = m;
2098 }
2099 SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) {
2100 super(m, mutex);
2101 sm = m;
2102 }
2103
2104 public Comparator<? super K> comparator() {
2105 synchronized(mutex) {return sm.comparator();}
2106 }
2107
2108 public SortedMap<K,V> subMap(K fromKey, K toKey) {
2109 synchronized(mutex) {
2110 return new SynchronizedSortedMap<K,V>(
2111 sm.subMap(fromKey, toKey), mutex);
2112 }
2113 }
2114 public SortedMap<K,V> headMap(K toKey) {
2115 synchronized(mutex) {
2116 return new SynchronizedSortedMap<K,V>(sm.headMap(toKey), mutex);
2117 }
2118 }
2119 public SortedMap<K,V> tailMap(K fromKey) {
2120 synchronized(mutex) {
2121 return new SynchronizedSortedMap<K,V>(sm.tailMap(fromKey),mutex);
2122 }
2123 }
2124
2125 public K firstKey() {
2126 synchronized(mutex) {return sm.firstKey();}
2127 }
2128 public K lastKey() {
2129 synchronized(mutex) {return sm.lastKey();}
2130 }
2131 }
2132
2133 // Dynamically typesafe collection wrappers
2134
2135 /**
2136 * Returns a dynamically typesafe view of the specified collection. Any
2137 * attempt to insert an element of the wrong type will result in an
2138 * immediate <tt>ClassCastException</tt>. Assuming a collection contains
2139 * no incorrectly typed elements prior to the time a dynamically typesafe
2140 * view is generated, and that all subsequent access to the collection
2141 * takes place through the view, it is <i>guaranteed</i> that the
2142 * collection cannot contain an incorrectly typed element.
2143 *
2144 * <p>The generics mechanism in the language provides compile-time
2145 * (static) type checking, but it is possible to defeat this mechanism
2146 * with unchecked casts. Usually this is not a problem, as the compiler
2147 * issues warnings on all such unchecked operations. There are, however,
2148 * times when static type checking alone is not sufficient. For example,
2149 * suppose a collection is passed to a third-party library and it is
2150 * imperative that the library code not corrupt the collection by
2151 * inserting an element of the wrong type.
2152 *
2153 * <p>Another use of dynamically typesafe views is debugging. Suppose a
2154 * program fails with a <tt>ClassCastException</tt>, indicating that an
2155 * incorrectly typed element was put into a parameterized collection.
2156 * Unfortunately, the exception can occur at any time after the erroneous
2157 * element is inserted, so it typically provides little or no information
2158 * as to the real source of the problem. If the problem is reproducible,
2159 * one can quickly determine its source by temporarily modifying the
2160 * program to wrap the collection with a dynamically typesafe view.
2161 * For example, this declaration:
2162 * <pre>
2163 * Collection&lt;String&gt; c = new HashSet&lt;String&gt;();
2164 * </pre>
2165 * may be replaced temporarily by this one:
2166 * <pre>
2167 * Collection&lt;String&gt; c = Collections.checkedCollection(
2168 * new HashSet&lt;String&gt;(), String.class);
2169 * </pre>
2170 * Running the program again will cause it to fail at the point where
2171 * an incorrectly typed element is inserted into the collection, clearly
2172 * identifying the source of the problem. Once the problem is fixed, the
2173 * modified declaration may be reverted back to the original.
2174 *
2175 * <p>The returned collection does <i>not</i> pass the hashCode and equals
2176 * operations through to the backing collection, but relies on
2177 * <tt>Object</tt>'s <tt>equals</tt> and <tt>hashCode</tt> methods. This
2178 * is necessary to preserve the contracts of these operations in the case
2179 * that the backing collection is a set or a list.
2180 *
2181 * <p>The returned collection will be serializable if the specified
2182 * collection is serializable.
2183 *
2184 * @param c the collection for which a dynamically typesafe view is to be
2185 * returned
2186 * @param type the type of element that <tt>c</tt> is permitted to hold
2187 * @return a dynamically typesafe view of the specified collection
2188 * @since 1.5
2189 */
2190 public static <E> Collection<E> checkedCollection(Collection<E> c,
2191 Class<E> type) {
2192 return new CheckedCollection<E>(c, type);
2193 }
2194
2195 /**
2196 * @serial include
2197 */
2198 static class CheckedCollection<E> implements Collection<E>, Serializable {
2199 private static final long serialVersionUID = 1578914078182001775L;
2200
2201 final Collection<E> c;
2202 final Class<E> type;
2203
2204 void typeCheck(Object o) {
2205 if (!type.isInstance(o))
2206 throw new ClassCastException("Attempt to insert " +
2207 o.getClass() + " element into collection with element type "
2208 + type);
2209 }
2210
2211 CheckedCollection(Collection<E> c, Class<E> type) {
2212 if (c==null || type == null)
2213 throw new NullPointerException();
2214 this.c = c;
2215 this.type = type;
2216 }
2217
2218 public int size() { return c.size(); }
2219 public boolean isEmpty() { return c.isEmpty(); }
2220 public boolean contains(Object o) { return c.contains(o); }
2221 public Object[] toArray() { return c.toArray(); }
2222 public <T> T[] toArray(T[] a) { return c.toArray(a); }
2223 public String toString() { return c.toString(); }
2224 public Iterator<E> iterator() { return c.iterator(); }
2225 public boolean remove(Object o) { return c.remove(o); }
2226 public boolean containsAll(Collection<?> coll) {
2227 return c.containsAll(coll);
2228 }
2229 public boolean removeAll(Collection<?> coll) {
2230 return c.removeAll(coll);
2231 }
2232 public boolean retainAll(Collection<?> coll) {
2233 return c.retainAll(coll);
2234 }
2235 public void clear() {
2236 c.clear();
2237 }
2238
2239 public boolean add(E e){
2240 typeCheck(e);
2241 return c.add(e);
2242 }
2243
2244 public boolean addAll(Collection<? extends E> coll) {
2245 /*
2246 * Dump coll into an array of the required type. This serves
2247 * three purposes: it insulates us from concurrent changes in
2248 * the contents of coll, it type-checks all of the elements in
2249 * coll, and it provides all-or-nothing semantics(which we
2250 * wouldn't get if we type-checked each element as we added it).
2251 */
2252 E[] a = null;
2253 try {
2254 a = coll.toArray(zeroLengthElementArray());
2255 } catch(ArrayStoreException e) {
2256 throw new ClassCastException();
2257 }
2258
2259 boolean result = false;
2260 for (E e : a)
2261 result |= c.add(e);
2262 return result;
2263 }
2264
2265 private E[] zeroLengthElementArray = null; // Lazily initialized
2266
2267 /*
2268 * We don't need locking or volatile, because it's OK if we create
2269 * several zeroLengthElementArrays, and they're immutable.
2270 */
2271 E[] zeroLengthElementArray() {
2272 if (zeroLengthElementArray == null)
2273 zeroLengthElementArray = (E[]) Array.newInstance(type, 0);
2274 return zeroLengthElementArray;
2275 }
2276 }
2277
2278 /**
2279 * Returns a dynamically typesafe view of the specified set.
2280 * Any attempt to insert an element of the wrong type will result in
2281 * an immediate <tt>ClassCastException</tt>. Assuming a set contains
2282 * no incorrectly typed elements prior to the time a dynamically typesafe
2283 * view is generated, and that all subsequent access to the set
2284 * takes place through the view, it is <i>guaranteed</i> that the
2285 * set cannot contain an incorrectly typed element.
2286 *
2287 * <p>A discussion of the use of dynamically typesafe views may be
2288 * found in the documentation for the {@link #checkedCollection checkedCollection}
2289 * method.
2290 *
2291 * <p>The returned set will be serializable if the specified set is
2292 * serializable.
2293 *
2294 * @param s the set for which a dynamically typesafe view is to be
2295 * returned
2296 * @param type the type of element that <tt>s</tt> is permitted to hold
2297 * @return a dynamically typesafe view of the specified set
2298 * @since 1.5
2299 */
2300 public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {
2301 return new CheckedSet<E>(s, type);
2302 }
2303
2304 /**
2305 * @serial include
2306 */
2307 static class CheckedSet<E> extends CheckedCollection<E>
2308 implements Set<E>, Serializable
2309 {
2310 private static final long serialVersionUID = 4694047833775013803L;
2311
2312 CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); }
2313
2314 public boolean equals(Object o) { return c.equals(o); }
2315 public int hashCode() { return c.hashCode(); }
2316 }
2317
2318 /**
2319 * Returns a dynamically typesafe view of the specified sorted set. Any
2320 * attempt to insert an element of the wrong type will result in an
2321 * immediate <tt>ClassCastException</tt>. Assuming a sorted set contains
2322 * no incorrectly typed elements prior to the time a dynamically typesafe
2323 * view is generated, and that all subsequent access to the sorted set
2324 * takes place through the view, it is <i>guaranteed</i> that the sorted
2325 * set cannot contain an incorrectly typed element.
2326 *
2327 * <p>A discussion of the use of dynamically typesafe views may be
2328 * found in the documentation for the {@link #checkedCollection checkedCollection}
2329 * method.
2330 *
2331 * <p>The returned sorted set will be serializable if the specified sorted
2332 * set is serializable.
2333 *
2334 * @param s the sorted set for which a dynamically typesafe view is to be
2335 * returned
2336 * @param type the type of element that <tt>s</tt> is permitted to hold
2337 * @return a dynamically typesafe view of the specified sorted set
2338 * @since 1.5
2339 */
2340 public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
2341 Class<E> type) {
2342 return new CheckedSortedSet<E>(s, type);
2343 }
2344
2345 /**
2346 * @serial include
2347 */
2348 static class CheckedSortedSet<E> extends CheckedSet<E>
2349 implements SortedSet<E>, Serializable
2350 {
2351 private static final long serialVersionUID = 1599911165492914959L;
2352 private final SortedSet<E> ss;
2353
2354 CheckedSortedSet(SortedSet<E> s, Class<E> type) {
2355 super(s, type);
2356 ss = s;
2357 }
2358
2359 public Comparator<? super E> comparator() { return ss.comparator(); }
2360 public E first() { return ss.first(); }
2361 public E last() { return ss.last(); }
2362
2363 public SortedSet<E> subSet(E fromElement, E toElement) {
2364 return new CheckedSortedSet<E>(ss.subSet(fromElement,toElement),
2365 type);
2366 }
2367 public SortedSet<E> headSet(E toElement) {
2368 return new CheckedSortedSet<E>(ss.headSet(toElement), type);
2369 }
2370 public SortedSet<E> tailSet(E fromElement) {
2371 return new CheckedSortedSet<E>(ss.tailSet(fromElement), type);
2372 }
2373 }
2374
2375 /**
2376 * Returns a dynamically typesafe view of the specified list.
2377 * Any attempt to insert an element of the wrong type will result in
2378 * an immediate <tt>ClassCastException</tt>. Assuming a list contains
2379 * no incorrectly typed elements prior to the time a dynamically typesafe
2380 * view is generated, and that all subsequent access to the list
2381 * takes place through the view, it is <i>guaranteed</i> that the
2382 * list cannot contain an incorrectly typed element.
2383 *
2384 * <p>A discussion of the use of dynamically typesafe views may be
2385 * found in the documentation for the {@link #checkedCollection checkedCollection}
2386 * method.
2387 *
2388 * <p>The returned list will be serializable if the specified list is
2389 * serializable.
2390 *
2391 * @param list the list for which a dynamically typesafe view is to be
2392 * returned
2393 * @param type the type of element that <tt>list</tt> is permitted to hold
2394 * @return a dynamically typesafe view of the specified list
2395 * @since 1.5
2396 */
2397 public static <E> List<E> checkedList(List<E> list, Class<E> type) {
2398 return (list instanceof RandomAccess ?
2399 new CheckedRandomAccessList<E>(list, type) :
2400 new CheckedList<E>(list, type));
2401 }
2402
2403 /**
2404 * @serial include
2405 */
2406 static class CheckedList<E> extends CheckedCollection<E>
2407 implements List<E>
2408 {
2409 static final long serialVersionUID = 65247728283967356L;
2410 final List<E> list;
2411
2412 CheckedList(List<E> list, Class<E> type) {
2413 super(list, type);
2414 this.list = list;
2415 }
2416
2417 public boolean equals(Object o) { return list.equals(o); }
2418 public int hashCode() { return list.hashCode(); }
2419 public E get(int index) { return list.get(index); }
2420 public E remove(int index) { return list.remove(index); }
2421 public int indexOf(Object o) { return list.indexOf(o); }
2422 public int lastIndexOf(Object o) { return list.lastIndexOf(o); }
2423
2424 public E set(int index, E element) {
2425 typeCheck(element);
2426 return list.set(index, element);
2427 }
2428
2429 public void add(int index, E element) {
2430 typeCheck(element);
2431 list.add(index, element);
2432 }
2433
2434 public boolean addAll(int index, Collection<? extends E> c) {
2435 // See CheckCollection.addAll, above, for an explanation
2436 E[] a = null;
2437 try {
2438 a = c.toArray(zeroLengthElementArray());
2439 } catch(ArrayStoreException e) {
2440 throw new ClassCastException();
2441 }
2442
2443 return list.addAll(index, Arrays.asList(a));
2444 }
2445 public ListIterator<E> listIterator() { return listIterator(0); }
2446
2447 public ListIterator<E> listIterator(final int index) {
2448 return new ListIterator<E>() {
2449 ListIterator<E> i = list.listIterator(index);
2450
2451 public boolean hasNext() { return i.hasNext(); }
2452 public E next() { return i.next(); }
2453 public boolean hasPrevious() { return i.hasPrevious(); }
2454 public E previous() { return i.previous(); }
2455 public int nextIndex() { return i.nextIndex(); }
2456 public int previousIndex() { return i.previousIndex(); }
2457 public void remove() { i.remove(); }
2458
2459 public void set(E e) {
2460 typeCheck(e);
2461 i.set(e);
2462 }
2463
2464 public void add(E e) {
2465 typeCheck(e);
2466 i.add(e);
2467 }
2468 };
2469 }
2470
2471 public List<E> subList(int fromIndex, int toIndex) {
2472 return new CheckedList<E>(list.subList(fromIndex, toIndex), type);
2473 }
2474 }
2475
2476 /**
2477 * @serial include
2478 */
2479 static class CheckedRandomAccessList<E> extends CheckedList<E>
2480 implements RandomAccess
2481 {
2482 private static final long serialVersionUID = 1638200125423088369L;
2483
2484 CheckedRandomAccessList(List<E> list, Class<E> type) {
2485 super(list, type);
2486 }
2487
2488 public List<E> subList(int fromIndex, int toIndex) {
2489 return new CheckedRandomAccessList<E>(
2490 list.subList(fromIndex, toIndex), type);
2491 }
2492 }
2493
2494 /**
2495 * Returns a dynamically typesafe view of the specified map. Any attempt
2496 * to insert a mapping whose key or value have the wrong type will result
2497 * in an immediate <tt>ClassCastException</tt>. Similarly, any attempt to
2498 * modify the value currently associated with a key will result in an
2499 * immediate <tt>ClassCastException</tt>, whether the modification is
2500 * attempted directly through the map itself, or through a {@link
2501 * Map.Entry} instance obtained from the map's {@link Map#entrySet()
2502 * entry set} view.
2503 *
2504 * <p>Assuming a map contains no incorrectly typed keys or values
2505 * prior to the time a dynamically typesafe view is generated, and
2506 * that all subsequent access to the map takes place through the view
2507 * (or one of its collection views), it is <i>guaranteed</i> that the
2508 * map cannot contain an incorrectly typed key or value.
2509 *
2510 * <p>A discussion of the use of dynamically typesafe views may be
2511 * found in the documentation for the {@link #checkedCollection checkedCollection}
2512 * method.
2513 *
2514 * <p>The returned map will be serializable if the specified map is
2515 * serializable.
2516 *
2517 * @param m the map for which a dynamically typesafe view is to be
2518 * returned
2519 * @param keyType the type of key that <tt>m</tt> is permitted to hold
2520 * @param valueType the type of value that <tt>m</tt> is permitted to hold
2521 * @return a dynamically typesafe view of the specified map
2522 * @since 1.5
2523 */
2524 public static <K, V> Map<K, V> checkedMap(Map<K, V> m, Class<K> keyType,
2525 Class<V> valueType) {
2526 return new CheckedMap<K,V>(m, keyType, valueType);
2527 }
2528
2529
2530 /**
2531 * @serial include
2532 */
2533 private static class CheckedMap<K,V> implements Map<K,V>,
2534 Serializable
2535 {
2536 private static final long serialVersionUID = 5742860141034234728L;
2537
2538 private final Map<K, V> m;
2539 final Class<K> keyType;
2540 final Class<V> valueType;
2541
2542 private void typeCheck(Object key, Object value) {
2543 if (!keyType.isInstance(key))
2544 throw new ClassCastException("Attempt to insert " +
2545 key.getClass() + " key into collection with key type "
2546 + keyType);
2547
2548 if (!valueType.isInstance(value))
2549 throw new ClassCastException("Attempt to insert " +
2550 value.getClass() +" value into collection with value type "
2551 + valueType);
2552 }
2553
2554 CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) {
2555 if (m == null || keyType == null || valueType == null)
2556 throw new NullPointerException();
2557 this.m = m;
2558 this.keyType = keyType;
2559 this.valueType = valueType;
2560 }
2561
2562 public int size() { return m.size(); }
2563 public boolean isEmpty() { return m.isEmpty(); }
2564 public boolean containsKey(Object key) { return m.containsKey(key); }
2565 public boolean containsValue(Object v) { return m.containsValue(v); }
2566 public V get(Object key) { return m.get(key); }
2567 public V remove(Object key) { return m.remove(key); }
2568 public void clear() { m.clear(); }
2569 public Set<K> keySet() { return m.keySet(); }
2570 public Collection<V> values() { return m.values(); }
2571 public boolean equals(Object o) { return m.equals(o); }
2572 public int hashCode() { return m.hashCode(); }
2573 public String toString() { return m.toString(); }
2574
2575 public V put(K key, V value) {
2576 typeCheck(key, value);
2577 return m.put(key, value);
2578 }
2579
2580 public void putAll(Map<? extends K, ? extends V> t) {
2581 // See CheckCollection.addAll, above, for an explanation
2582 K[] keys = null;
2583 try {
2584 keys = t.keySet().toArray(zeroLengthKeyArray());
2585 } catch(ArrayStoreException e) {
2586 throw new ClassCastException();
2587 }
2588 V[] values = null;
2589 try {
2590 values = t.values().toArray(zeroLengthValueArray());
2591 } catch(ArrayStoreException e) {
2592 throw new ClassCastException();
2593 }
2594
2595 if (keys.length != values.length)
2596 throw new ConcurrentModificationException();
2597
2598 for (int i = 0; i < keys.length; i++)
2599 m.put(keys[i], values[i]);
2600 }
2601
2602 // Lazily initialized
2603 private K[] zeroLengthKeyArray = null;
2604 private V[] zeroLengthValueArray = null;
2605
2606 /*
2607 * We don't need locking or volatile, because it's OK if we create
2608 * several zeroLengthValueArrays, and they're immutable.
2609 */
2610 private K[] zeroLengthKeyArray() {
2611 if (zeroLengthKeyArray == null)
2612 zeroLengthKeyArray = (K[]) Array.newInstance(keyType, 0);
2613 return zeroLengthKeyArray;
2614 }
2615 private V[] zeroLengthValueArray() {
2616 if (zeroLengthValueArray == null)
2617 zeroLengthValueArray = (V[]) Array.newInstance(valueType, 0);
2618 return zeroLengthValueArray;
2619 }
2620
2621 private transient Set<Map.Entry<K,V>> entrySet = null;
2622
2623 public Set<Map.Entry<K,V>> entrySet() {
2624 if (entrySet==null)
2625 entrySet = new CheckedEntrySet<K,V>(m.entrySet(), valueType);
2626 return entrySet;
2627 }
2628
2629 /**
2630 * We need this class in addition to CheckedSet as Map.Entry permits
2631 * modification of the backing Map via the setValue operation. This
2632 * class is subtle: there are many possible attacks that must be
2633 * thwarted.
2634 *
2635 * @serial exclude
2636 */
2637 static class CheckedEntrySet<K,V> implements Set<Map.Entry<K,V>> {
2638 Set<Map.Entry<K,V>> s;
2639 Class<V> valueType;
2640
2641 CheckedEntrySet(Set<Map.Entry<K, V>> s, Class<V> valueType) {
2642 this.s = s;
2643 this.valueType = valueType;
2644 }
2645
2646 public int size() { return s.size(); }
2647 public boolean isEmpty() { return s.isEmpty(); }
2648 public String toString() { return s.toString(); }
2649 public int hashCode() { return s.hashCode(); }
2650 public boolean remove(Object o) { return s.remove(o); }
2651 public boolean removeAll(Collection<?> coll) {
2652 return s.removeAll(coll);
2653 }
2654 public boolean retainAll(Collection<?> coll) {
2655 return s.retainAll(coll);
2656 }
2657 public void clear() {
2658 s.clear();
2659 }
2660
2661 public boolean add(Map.Entry<K, V> e){
2662 throw new UnsupportedOperationException();
2663 }
2664 public boolean addAll(Collection<? extends Map.Entry<K, V>> coll) {
2665 throw new UnsupportedOperationException();
2666 }
2667
2668
2669 public Iterator<Map.Entry<K,V>> iterator() {
2670 return new Iterator<Map.Entry<K,V>>() {
2671 Iterator<Map.Entry<K, V>> i = s.iterator();
2672
2673 public boolean hasNext() { return i.hasNext(); }
2674 public void remove() { i.remove(); }
2675
2676 public Map.Entry<K,V> next() {
2677 return new CheckedEntry<K,V>(i.next(), valueType);
2678 }
2679 };
2680 }
2681
2682 public Object[] toArray() {
2683 Object[] source = s.toArray();
2684
2685 /*
2686 * Ensure that we don't get an ArrayStoreException even if
2687 * s.toArray returns an array of something other than Object
2688 */
2689 Object[] dest = (CheckedEntry.class.isInstance(
2690 source.getClass().getComponentType()) ? source :
2691 new Object[source.length]);
2692
2693 for (int i = 0; i < source.length; i++)
2694 dest[i] = new CheckedEntry<K,V>((Map.Entry<K,V>)source[i],
2695 valueType);
2696 return dest;
2697 }
2698
2699 public <T> T[] toArray(T[] a) {
2700 // We don't pass a to s.toArray, to avoid window of
2701 // vulnerability wherein an unscrupulous multithreaded client
2702 // could get his hands on raw (unwrapped) Entries from s.
2703 Object[] arr = s.toArray(a.length==0 ? a :
2704 (T[])Array.newInstance(a.getClass().getComponentType(), 0));
2705
2706 for (int i=0; i<arr.length; i++)
2707 arr[i] = new CheckedEntry<K,V>((Map.Entry<K,V>)arr[i],
2708 valueType);
2709 if (arr.length > a.length)
2710 return (T[])arr;
2711
2712 System.arraycopy(arr, 0, a, 0, arr.length);
2713 if (a.length > arr.length)
2714 a[arr.length] = null;
2715 return a;
2716 }
2717
2718 /**
2719 * This method is overridden to protect the backing set against
2720 * an object with a nefarious equals function that senses
2721 * that the equality-candidate is Map.Entry and calls its
2722 * setValue method.
2723 */
2724 public boolean contains(Object o) {
2725 if (!(o instanceof Map.Entry))
2726 return false;
2727 return s.contains(
2728 new CheckedEntry<K,V>((Map.Entry<K,V>) o, valueType));
2729 }
2730
2731 /**
2732 * The next two methods are overridden to protect against
2733 * an unscrupulous collection whose contains(Object o) method
2734 * senses when o is a Map.Entry, and calls o.setValue.
2735 */
2736 public boolean containsAll(Collection<?> coll) {
2737 Iterator<?> e = coll.iterator();
2738 while (e.hasNext())
2739 if (!contains(e.next())) // Invokes safe contains() above
2740 return false;
2741 return true;
2742 }
2743
2744 public boolean equals(Object o) {
2745 if (o == this)
2746 return true;
2747 if (!(o instanceof Set))
2748 return false;
2749 Set<?> that = (Set<?>) o;
2750 if (that.size() != s.size())
2751 return false;
2752 return containsAll(that); // Invokes safe containsAll() above
2753 }
2754
2755 /**
2756 * This "wrapper class" serves two purposes: it prevents
2757 * the client from modifying the backing Map, by short-circuiting
2758 * the setValue method, and it protects the backing Map against
2759 * an ill-behaved Map.Entry that attempts to modify another
2760 * Map Entry when asked to perform an equality check.
2761 */
2762 private static class CheckedEntry<K,V> implements Map.Entry<K,V> {
2763 private Map.Entry<K, V> e;
2764 private Class<V> valueType;
2765
2766 CheckedEntry(Map.Entry<K, V> e, Class<V> valueType) {
2767 this.e = e;
2768 this.valueType = valueType;
2769 }
2770
2771 public K getKey() { return e.getKey(); }
2772 public V getValue() { return e.getValue(); }
2773 public int hashCode() { return e.hashCode(); }
2774 public String toString() { return e.toString(); }
2775
2776
2777 public V setValue(V value) {
2778 if (!valueType.isInstance(value))
2779 throw new ClassCastException("Attempt to insert " +
2780 value.getClass() +
2781 " value into collection with value type " + valueType);
2782 return e.setValue(value);
2783 }
2784
2785 public boolean equals(Object o) {
2786 if (!(o instanceof Map.Entry))
2787 return false;
2788 Map.Entry t = (Map.Entry)o;
2789 return eq(e.getKey(), t.getKey()) &&
2790 eq(e.getValue(), t.getValue());
2791 }
2792 }
2793 }
2794 }
2795
2796 /**
2797 * Returns a dynamically typesafe view of the specified sorted map. Any
2798 * attempt to insert a mapping whose key or value have the wrong type will
2799 * result in an immediate <tt>ClassCastException</tt>. Similarly, any
2800 * attempt to modify the value currently associated with a key will result
2801 * in an immediate <tt>ClassCastException</tt>, whether the modification
2802 * is attempted directly through the map itself, or through a {@link
2803 * Map.Entry} instance obtained from the map's {@link Map#entrySet() entry
2804 * set} view.
2805 *
2806 * <p>Assuming a map contains no incorrectly typed keys or values
2807 * prior to the time a dynamically typesafe view is generated, and
2808 * that all subsequent access to the map takes place through the view
2809 * (or one of its collection views), it is <i>guaranteed</i> that the
2810 * map cannot contain an incorrectly typed key or value.
2811 *
2812 * <p>A discussion of the use of dynamically typesafe views may be
2813 * found in the documentation for the {@link #checkedCollection checkedCollection}
2814 * method.
2815 *
2816 * <p>The returned map will be serializable if the specified map is
2817 * serializable.
2818 *
2819 * @param m the map for which a dynamically typesafe view is to be
2820 * returned
2821 * @param keyType the type of key that <tt>m</tt> is permitted to hold
2822 * @param valueType the type of value that <tt>m</tt> is permitted to hold
2823 * @return a dynamically typesafe view of the specified map
2824 * @since 1.5
2825 */
2826 public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,
2827 Class<K> keyType,
2828 Class<V> valueType) {
2829 return new CheckedSortedMap<K,V>(m, keyType, valueType);
2830 }
2831
2832 /**
2833 * @serial include
2834 */
2835 static class CheckedSortedMap<K,V> extends CheckedMap<K,V>
2836 implements SortedMap<K,V>, Serializable
2837 {
2838 private static final long serialVersionUID = 1599671320688067438L;
2839
2840 private final SortedMap<K, V> sm;
2841
2842 CheckedSortedMap(SortedMap<K, V> m,
2843 Class<K> keyType, Class<V> valueType) {
2844 super(m, keyType, valueType);
2845 sm = m;
2846 }
2847
2848 public Comparator<? super K> comparator() { return sm.comparator(); }
2849 public K firstKey() { return sm.firstKey(); }
2850 public K lastKey() { return sm.lastKey(); }
2851
2852 public SortedMap<K,V> subMap(K fromKey, K toKey) {
2853 return new CheckedSortedMap<K,V>(sm.subMap(fromKey, toKey),
2854 keyType, valueType);
2855 }
2856
2857 public SortedMap<K,V> headMap(K toKey) {
2858 return new CheckedSortedMap<K,V>(sm.headMap(toKey),
2859 keyType, valueType);
2860 }
2861
2862 public SortedMap<K,V> tailMap(K fromKey) {
2863 return new CheckedSortedMap<K,V>(sm.tailMap(fromKey),
2864 keyType, valueType);
2865 }
2866 }
2867
2868 // Miscellaneous
2869
2870 /**
2871 * The empty set (immutable). This set is serializable.
2872 *
2873 * @see #emptySet()
2874 */
2875 public static final Set EMPTY_SET = new EmptySet();
2876
2877 /**
2878 * Returns the empty set (immutable). This set is serializable.
2879 * Unlike the like-named field, this method is parameterized.
2880 *
2881 * <p>This example illustrates the type-safe way to obtain an empty set:
2882 * <pre>
2883 * Set&lt;String&gt; s = Collections.emptySet();
2884 * </pre>
2885 * Implementation note: Implementations of this method need not
2886 * create a separate <tt>Set</tt> object for each call. Using this
2887 * method is likely to have comparable cost to using the like-named
2888 * field. (Unlike this method, the field does not provide type safety.)
2889 *
2890 * @see #EMPTY_SET
2891 * @since 1.5
2892 */
2893 public static final <T> Set<T> emptySet() {
2894 return (Set<T>) EMPTY_SET;
2895 }
2896
2897 /**
2898 * @serial include
2899 */
2900 private static class EmptySet extends AbstractSet<Object> implements Serializable {
2901 // use serialVersionUID from JDK 1.2.2 for interoperability
2902 private static final long serialVersionUID = 1582296315990362920L;
2903
2904 public Iterator<Object> iterator() {
2905 return new Iterator<Object>() {
2906 public boolean hasNext() {
2907 return false;
2908 }
2909 public Object next() {
2910 throw new NoSuchElementException();
2911 }
2912 public void remove() {
2913 throw new UnsupportedOperationException();
2914 }
2915 };
2916 }
2917
2918 public int size() {return 0;}
2919
2920 public boolean contains(Object obj) {return false;}
2921
2922 // Preserves singleton property
2923 private Object readResolve() {
2924 return EMPTY_SET;
2925 }
2926 }
2927
2928 /**
2929 * The empty list (immutable). This list is serializable.
2930 *
2931 * @see #emptyList()
2932 */
2933 public static final List EMPTY_LIST = new EmptyList();
2934
2935 /**
2936 * Returns the empty list (immutable). This list is serializable.
2937 *
2938 * <p>This example illustrates the type-safe way to obtain an empty list:
2939 * <pre>
2940 * List&lt;String&gt; s = Collections.emptyList();
2941 * </pre>
2942 * Implementation note: Implementations of this method need not
2943 * create a separate <tt>List</tt> object for each call. Using this
2944 * method is likely to have comparable cost to using the like-named
2945 * field. (Unlike this method, the field does not provide type safety.)
2946 *
2947 * @see #EMPTY_LIST
2948 * @since 1.5
2949 */
2950 public static final <T> List<T> emptyList() {
2951 return (List<T>) EMPTY_LIST;
2952 }
2953
2954 /**
2955 * @serial include
2956 */
2957 private static class EmptyList
2958 extends AbstractList<Object>
2959 implements RandomAccess, Serializable {
2960 // use serialVersionUID from JDK 1.2.2 for interoperability
2961 private static final long serialVersionUID = 8842843931221139166L;
2962
2963 public int size() {return 0;}
2964
2965 public boolean contains(Object obj) {return false;}
2966
2967 public Object get(int index) {
2968 throw new IndexOutOfBoundsException("Index: "+index);
2969 }
2970
2971 // Preserves singleton property
2972 private Object readResolve() {
2973 return EMPTY_LIST;
2974 }
2975 }
2976
2977 /**
2978 * The empty map (immutable). This map is serializable.
2979 *
2980 * @see #emptyMap()
2981 * @since 1.3
2982 */
2983 public static final Map EMPTY_MAP = new EmptyMap();
2984
2985 /**
2986 * Returns the empty map (immutable). This map is serializable.
2987 *
2988 * <p>This example illustrates the type-safe way to obtain an empty set:
2989 * <pre>
2990 * Map&lt;String, Date&gt; s = Collections.emptyMap();
2991 * </pre>
2992 * Implementation note: Implementations of this method need not
2993 * create a separate <tt>Map</tt> object for each call. Using this
2994 * method is likely to have comparable cost to using the like-named
2995 * field. (Unlike this method, the field does not provide type safety.)
2996 *
2997 * @see #EMPTY_MAP
2998 * @since 1.5
2999 */
3000 public static final <K,V> Map<K,V> emptyMap() {
3001 return (Map<K,V>) EMPTY_MAP;
3002 }
3003
3004 private static class EmptyMap
3005 extends AbstractMap<Object,Object>
3006 implements Serializable {
3007
3008 private static final long serialVersionUID = 6428348081105594320L;
3009
3010 public int size() {return 0;}
3011
3012 public boolean isEmpty() {return true;}
3013
3014 public boolean containsKey(Object key) {return false;}
3015
3016 public boolean containsValue(Object value) {return false;}
3017
3018 public Object get(Object key) {return null;}
3019
3020 public Set<Object> keySet() {return Collections.<Object>emptySet();}
3021
3022 public Collection<Object> values() {return Collections.<Object>emptySet();}
3023
3024 public Set<Map.Entry<Object,Object>> entrySet() {
3025 return Collections.emptySet();
3026 }
3027
3028 public boolean equals(Object o) {
3029 return (o instanceof Map) && ((Map)o).size()==0;
3030 }
3031
3032 public int hashCode() {return 0;}
3033
3034 // Preserves singleton property
3035 private Object readResolve() {
3036 return EMPTY_MAP;
3037 }
3038 }
3039
3040 /**
3041 * Returns an immutable set containing only the specified object.
3042 * The returned set is serializable.
3043 *
3044 * @param o the sole object to be stored in the returned set.
3045 * @return an immutable set containing only the specified object.
3046 */
3047 public static <T> Set<T> singleton(T o) {
3048 return new SingletonSet<T>(o);
3049 }
3050
3051 /**
3052 * @serial include
3053 */
3054 private static class SingletonSet<E>
3055 extends AbstractSet<E>
3056 implements Serializable
3057 {
3058 // use serialVersionUID from JDK 1.2.2 for interoperability
3059 private static final long serialVersionUID = 3193687207550431679L;
3060
3061 final private E element;
3062
3063 SingletonSet(E e) {element = e;}
3064
3065 public Iterator<E> iterator() {
3066 return new Iterator<E>() {
3067 private boolean hasNext = true;
3068 public boolean hasNext() {
3069 return hasNext;
3070 }
3071 public E next() {
3072 if (hasNext) {
3073 hasNext = false;
3074 return element;
3075 }
3076 throw new NoSuchElementException();
3077 }
3078 public void remove() {
3079 throw new UnsupportedOperationException();
3080 }
3081 };
3082 }
3083
3084 public int size() {return 1;}
3085
3086 public boolean contains(Object o) {return eq(o, element);}
3087 }
3088
3089 /**
3090 * Returns an immutable list containing only the specified object.
3091 * The returned list is serializable.
3092 *
3093 * @param o the sole object to be stored in the returned list.
3094 * @return an immutable list containing only the specified object.
3095 * @since 1.3
3096 */
3097 public static <T> List<T> singletonList(T o) {
3098 return new SingletonList<T>(o);
3099 }
3100
3101 private static class SingletonList<E>
3102 extends AbstractList<E>
3103 implements RandomAccess, Serializable {
3104
3105 static final long serialVersionUID = 3093736618740652951L;
3106
3107 private final E element;
3108
3109 SingletonList(E obj) {element = obj;}
3110
3111 public int size() {return 1;}
3112
3113 public boolean contains(Object obj) {return eq(obj, element);}
3114
3115 public E get(int index) {
3116 if (index != 0)
3117 throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");
3118 return element;
3119 }
3120 }
3121
3122 /**
3123 * Returns an immutable map, mapping only the specified key to the
3124 * specified value. The returned map is serializable.
3125 *
3126 * @param key the sole key to be stored in the returned map.
3127 * @param value the value to which the returned map maps <tt>key</tt>.
3128 * @return an immutable map containing only the specified key-value
3129 * mapping.
3130 * @since 1.3
3131 */
3132 public static <K,V> Map<K,V> singletonMap(K key, V value) {
3133 return new SingletonMap<K,V>(key, value);
3134 }
3135
3136 private static class SingletonMap<K,V>
3137 extends AbstractMap<K,V>
3138 implements Serializable {
3139 private static final long serialVersionUID = -6979724477215052911L;
3140
3141 private final K k;
3142 private final V v;
3143
3144 SingletonMap(K key, V value) {
3145 k = key;
3146 v = value;
3147 }
3148
3149 public int size() {return 1;}
3150
3151 public boolean isEmpty() {return false;}
3152
3153 public boolean containsKey(Object key) {return eq(key, k);}
3154
3155 public boolean containsValue(Object value) {return eq(value, v);}
3156
3157 public V get(Object key) {return (eq(key, k) ? v : null);}
3158
3159 private transient Set<K> keySet = null;
3160 private transient Set<Map.Entry<K,V>> entrySet = null;
3161 private transient Collection<V> values = null;
3162
3163 public Set<K> keySet() {
3164 if (keySet==null)
3165 keySet = singleton(k);
3166 return keySet;
3167 }
3168
3169 public Set<Map.Entry<K,V>> entrySet() {
3170 if (entrySet==null)
3171 entrySet = Collections.<Map.Entry<K,V>>singleton(
3172 new SimpleImmutableEntry<K,V>(k, v));
3173 return entrySet;
3174 }
3175
3176 public Collection<V> values() {
3177 if (values==null)
3178 values = singleton(v);
3179 return values;
3180 }
3181
3182 }
3183
3184 /**
3185 * Returns an immutable list consisting of <tt>n</tt> copies of the
3186 * specified object. The newly allocated data object is tiny (it contains
3187 * a single reference to the data object). This method is useful in
3188 * combination with the <tt>List.addAll</tt> method to grow lists.
3189 * The returned list is serializable.
3190 *
3191 * @param n the number of elements in the returned list.
3192 * @param o the element to appear repeatedly in the returned list.
3193 * @return an immutable list consisting of <tt>n</tt> copies of the
3194 * specified object.
3195 * @throws IllegalArgumentException if n &lt; 0.
3196 * @see List#addAll(Collection)
3197 * @see List#addAll(int, Collection)
3198 */
3199 public static <T> List<T> nCopies(int n, T o) {
3200 return new CopiesList<T>(n, o);
3201 }
3202
3203 /**
3204 * @serial include
3205 */
3206 private static class CopiesList<E>
3207 extends AbstractList<E>
3208 implements RandomAccess, Serializable
3209 {
3210 static final long serialVersionUID = 2739099268398711800L;
3211
3212 int n;
3213 E element;
3214
3215 CopiesList(int n, E e) {
3216 if (n < 0)
3217 throw new IllegalArgumentException("List length = " + n);
3218 this.n = n;
3219 element = e;
3220 }
3221
3222 public int size() {
3223 return n;
3224 }
3225
3226 public boolean contains(Object obj) {
3227 return n != 0 && eq(obj, element);
3228 }
3229
3230 public E get(int index) {
3231 if (index<0 || index>=n)
3232 throw new IndexOutOfBoundsException("Index: "+index+
3233 ", Size: "+n);
3234 return element;
3235 }
3236 }
3237
3238 /**
3239 * Returns a comparator that imposes the reverse of the <i>natural
3240 * ordering</i> on a collection of objects that implement the
3241 * <tt>Comparable</tt> interface. (The natural ordering is the ordering
3242 * imposed by the objects' own <tt>compareTo</tt> method.) This enables a
3243 * simple idiom for sorting (or maintaining) collections (or arrays) of
3244 * objects that implement the <tt>Comparable</tt> interface in
3245 * reverse-natural-order. For example, suppose a is an array of
3246 * strings. Then: <pre>
3247 * Arrays.sort(a, Collections.reverseOrder());
3248 * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>
3249 *
3250 * The returned comparator is serializable.
3251 *
3252 * @return a comparator that imposes the reverse of the <i>natural
3253 * ordering</i> on a collection of objects that implement
3254 * the <tt>Comparable</tt> interface.
3255 * @see Comparable
3256 */
3257 public static <T> Comparator<T> reverseOrder() {
3258 return (Comparator<T>) REVERSE_ORDER;
3259 }
3260
3261 private static final Comparator REVERSE_ORDER = new ReverseComparator();
3262
3263 /**
3264 * @serial include
3265 */
3266 private static class ReverseComparator<T>
3267 implements Comparator<Comparable<Object>>, Serializable {
3268
3269 // use serialVersionUID from JDK 1.2.2 for interoperability
3270 private static final long serialVersionUID = 7207038068494060240L;
3271
3272 public int compare(Comparable<Object> c1, Comparable<Object> c2) {
3273 return c2.compareTo(c1);
3274 }
3275 }
3276
3277 /**
3278 * Returns a comparator that imposes the reverse ordering of the specified
3279 * comparator. If the specified comparator is null, this method is
3280 * equivalent to {@link #reverseOrder()} (in other words, it returns a
3281 * comparator that imposes the reverse of the <i>natural ordering</i> on a
3282 * collection of objects that implement the Comparable interface).
3283 *
3284 * <p>The returned comparator is serializable (assuming the specified
3285 * comparator is also serializable or null).
3286 *
3287 * @return a comparator that imposes the reverse ordering of the
3288 * specified comparator.
3289 * @since 1.5
3290 */
3291 public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) {
3292 if (cmp == null)
3293 return new ReverseComparator(); // Unchecked warning!!
3294
3295 return new ReverseComparator2<T>(cmp);
3296 }
3297
3298 /**
3299 * @serial include
3300 */
3301 private static class ReverseComparator2<T> implements Comparator<T>,
3302 Serializable
3303 {
3304 private static final long serialVersionUID = 4374092139857L;
3305
3306 /**
3307 * The comparator specified in the static factory. This will never
3308 * be null, as the static factory returns a ReverseComparator
3309 * instance if its argument is null.
3310 *
3311 * @serial
3312 */
3313 private Comparator<T> cmp;
3314
3315 ReverseComparator2(Comparator<T> cmp) {
3316 assert cmp != null;
3317 this.cmp = cmp;
3318 }
3319
3320 public int compare(T t1, T t2) {
3321 return cmp.compare(t2, t1);
3322 }
3323 }
3324
3325 /**
3326 * Returns an enumeration over the specified collection. This provides
3327 * interoperability with legacy APIs that require an enumeration
3328 * as input.
3329 *
3330 * @param c the collection for which an enumeration is to be returned.
3331 * @return an enumeration over the specified collection.
3332 * @see Enumeration
3333 */
3334 public static <T> Enumeration<T> enumeration(final Collection<T> c) {
3335 return new Enumeration<T>() {
3336 Iterator<T> i = c.iterator();
3337
3338 public boolean hasMoreElements() {
3339 return i.hasNext();
3340 }
3341
3342 public T nextElement() {
3343 return i.next();
3344 }
3345 };
3346 }
3347
3348 /**
3349 * Returns an array list containing the elements returned by the
3350 * specified enumeration in the order they are returned by the
3351 * enumeration. This method provides interoperability between
3352 * legacy APIs that return enumerations and new APIs that require
3353 * collections.
3354 *
3355 * @param e enumeration providing elements for the returned
3356 * array list
3357 * @return an array list containing the elements returned
3358 * by the specified enumeration.
3359 * @since 1.4
3360 * @see Enumeration
3361 * @see ArrayList
3362 */
3363 public static <T> ArrayList<T> list(Enumeration<T> e) {
3364 ArrayList<T> l = new ArrayList<T>();
3365 while (e.hasMoreElements())
3366 l.add(e.nextElement());
3367 return l;
3368 }
3369
3370 /**
3371 * Returns true if the specified arguments are equal, or both null.
3372 */
3373 private static boolean eq(Object o1, Object o2) {
3374 return (o1==null ? o2==null : o1.equals(o2));
3375 }
3376
3377 /**
3378 * Returns the number of elements in the specified collection equal to the
3379 * specified object. More formally, returns the number of elements
3380 * <tt>e</tt> in the collection such that
3381 * <tt>(o == null ? e == null : o.equals(e))</tt>.
3382 *
3383 * @param c the collection in which to determine the frequency
3384 * of <tt>o</tt>
3385 * @param o the object whose frequency is to be determined
3386 * @throws NullPointerException if <tt>c</tt> is null
3387 * @since 1.5
3388 */
3389 public static int frequency(Collection<?> c, Object o) {
3390 int result = 0;
3391 if (o == null) {
3392 for (Object e : c)
3393 if (e == null)
3394 result++;
3395 } else {
3396 for (Object e : c)
3397 if (o.equals(e))
3398 result++;
3399 }
3400 return result;
3401 }
3402
3403 /**
3404 * Returns <tt>true</tt> if the two specified collections have no
3405 * elements in common.
3406 *
3407 * <p>Care must be exercised if this method is used on collections that
3408 * do not comply with the general contract for <tt>Collection</tt>.
3409 * Implementations may elect to iterate over either collection and test
3410 * for containment in the other collection (or to perform any equivalent
3411 * computation). If either collection uses a nonstandard equality test
3412 * (as does a {@link SortedSet} whose ordering is not <i>compatible with
3413 * equals</i>, or the key set of an {@link IdentityHashMap}), both
3414 * collections must use the same nonstandard equality test, or the
3415 * result of this method is undefined.
3416 *
3417 * <p>Note that it is permissible to pass the same collection in both
3418 * parameters, in which case the method will return true if and only if
3419 * the collection is empty.
3420 *
3421 * @param c1 a collection
3422 * @param c2 a collection
3423 * @throws NullPointerException if either collection is null
3424 * @since 1.5
3425 */
3426 public static boolean disjoint(Collection<?> c1, Collection<?> c2) {
3427 /*
3428 * We're going to iterate through c1 and test for inclusion in c2.
3429 * If c1 is a Set and c2 isn't, swap the collections. Otherwise,
3430 * place the shorter collection in c1. Hopefully this heuristic
3431 * will minimize the cost of the operation.
3432 */
3433 if ((c1 instanceof Set) && !(c2 instanceof Set) ||
3434 (c1.size() > c2.size())) {
3435 Collection<?> tmp = c1;
3436 c1 = c2;
3437 c2 = tmp;
3438 }
3439
3440 for (Object e : c1)
3441 if (c2.contains(e))
3442 return false;
3443 return true;
3444 }
3445
3446 /**
3447 * Adds all of the specified elements to the specified collection.
3448 * Elements to be added may be specified individually or as an array.
3449 * The behavior of this convenience method is identical to that of
3450 * <tt>c.addAll(Arrays.asList(elements))</tt>, but this method is likely
3451 * to run significantly faster under most implementations.
3452 *
3453 * <p>When elements are specified individually, this method provides a
3454 * convenient way to add a few elements to an existing collection:
3455 * <pre>
3456 * Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");
3457 * </pre>
3458 *
3459 * @param c the collection into which <tt>elements</tt> are to be inserted
3460 * @param a the elements to insert into <tt>c</tt>
3461 * @return <tt>true</tt> if the collection changed as a result of the call
3462 * @throws UnsupportedOperationException if <tt>c</tt> does not support
3463 * the <tt>add</tt> operation.
3464 * @throws NullPointerException if <tt>elements</tt> contains one or more
3465 * null values and <tt>c</tt> does not support null elements, or
3466 * if <tt>c</tt> or <tt>elements</tt> are <tt>null</tt>
3467 * @throws IllegalArgumentException if some aspect of a value in
3468 * <tt>elements</tt> prevents it from being added to <tt>c</tt>
3469 * @see Collection#addAll(Collection)
3470 * @since 1.5
3471 */
3472 public static <T> boolean addAll(Collection<? super T> c, T... a) {
3473 boolean result = false;
3474 for (T e : a)
3475 result |= c.add(e);
3476 return result;
3477 }
3478
3479 /**
3480 * Returns a set backed by the specified map. The resulting set displays
3481 * the same ordering, concurrency, and performance characteristics as the
3482 * backing map. In essence, this factory method provides a {@link Set}
3483 * implementation corresponding to any {@link Map} implementation. There
3484 * is no need to use this method on a {@link Map} implementation that
3485 * already has a corresponding {@link Set} implementation (such as {@link
3486 * HashMap} or {@link TreeMap}).
3487 *
3488 * <p>Each method invocation on the set returned by this method results in
3489 * exactly one method invocation on the backing map or its <tt>keySet</tt>
3490 * view, with one exception. The <tt>addAll</tt> method is implemented
3491 * as a sequence of <tt>put</tt> invocations on the backing map.
3492 *
3493 * <p>The specified map must be empty at the time this method is invoked,
3494 * and should not be accessed directly after this method returns. These
3495 * conditions are ensured if the map is created empty, passed directly
3496 * to this method, and no reference to the map is retained, as illustrated
3497 * in the following code fragment:
3498 * <pre>
3499 * Set&lt;Object&gt; weakHashSet = Collections.asSet(
3500 * new WeakHashMap&lt;Object, Boolean&gt;());
3501 * </pre>
3502 *
3503 * @param map the backing map
3504 * @return the set backed by the map
3505 * @throws IllegalArgumentException if <tt>map</tt> is not empty
3506 */
3507 public static <E> Set<E> asSet(Map<E, Boolean> map) {
3508 return new MapAsSet<E>(map);
3509 }
3510
3511 private static class MapAsSet<E> extends AbstractSet<E>
3512 implements Set<E>, Serializable
3513 {
3514 private final Map<E, Boolean> m; // The backing map
3515 private transient Set<E> keySet; // Its keySet
3516
3517 MapAsSet(Map<E, Boolean> map) {
3518 if (!map.isEmpty())
3519 throw new IllegalArgumentException("Map is non-empty");
3520 m = map;
3521 keySet = map.keySet();
3522 }
3523
3524 public int size() { return m.size(); }
3525 public boolean isEmpty() { return m.isEmpty(); }
3526 public boolean contains(Object o) { return m.containsKey(o); }
3527 public Iterator<E> iterator() { return keySet.iterator(); }
3528 public Object[] toArray() { return keySet.toArray(); }
3529 public <T> T[] toArray(T[] a) { return keySet.toArray(a); }
3530 public boolean add(E e) {
3531 return m.put(e, Boolean.TRUE) == null;
3532 }
3533 public boolean remove(Object o) { return m.remove(o) != null; }
3534
3535 public boolean removeAll(Collection<?> c) {
3536 return keySet.removeAll(c);
3537 }
3538 public boolean retainAll(Collection<?> c) {
3539 return keySet.retainAll(c);
3540 }
3541 public void clear() { m.clear(); }
3542 public boolean equals(Object o) { return keySet.equals(o); }
3543 public int hashCode() { return keySet.hashCode(); }
3544
3545 private static final long serialVersionUID = 2454657854757543876L;
3546
3547 private void readObject(java.io.ObjectInputStream s)
3548 throws IOException, ClassNotFoundException
3549 {
3550 s.defaultReadObject();
3551 keySet = m.keySet();
3552 }
3553 }
3554
3555 /**
3556 * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)
3557 * {@link Queue}. Method <tt>add</tt> is mapped to <tt>push</tt>,
3558 * <tt>remove</tt> is mapped to <tt>pop</tt> and so on. This
3559 * view can be useful when you would like to use a method
3560 * requiring a <tt>Queue</tt> but you need Lifo ordering.
3561 * @param deque the Deque
3562 * @return the queue
3563 * @since 1.6
3564 */
3565 public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
3566 return new AsLIFOQueue<T>(deque);
3567 }
3568
3569 static class AsLIFOQueue<E> extends AbstractQueue<E>
3570 implements Queue<E>, Serializable {
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 }