ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Collections.java
Revision: 1.9
Committed: Fri May 27 03:44:18 2005 UTC (18 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.8: +4 -1 lines
Log Message:
sync with Mustang

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