ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Collections.java
Revision: 1.20
Committed: Wed Jan 11 00:57:12 2006 UTC (18 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.19: +10 -3 lines
Log Message:
sync with mustang

File Contents

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