ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Collections.java
Revision: 1.19
Committed: Tue Dec 13 23:52:22 2005 UTC (18 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.18: +5 -5 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 Iterator<E> iterator() { return c.iterator(); }
2225     public boolean remove(Object o) { return c.remove(o); }
2226     public boolean containsAll(Collection<?> coll) {
2227     return c.containsAll(coll);
2228     }
2229     public boolean removeAll(Collection<?> coll) {
2230     return c.removeAll(coll);
2231     }
2232     public boolean retainAll(Collection<?> coll) {
2233     return c.retainAll(coll);
2234     }
2235     public void clear() {
2236     c.clear();
2237     }
2238    
2239 jsr166 1.5 public boolean add(E e){
2240     typeCheck(e);
2241     return c.add(e);
2242 dl 1.1 }
2243    
2244     public boolean addAll(Collection<? extends E> coll) {
2245     /*
2246     * Dump coll into an array of the required type. This serves
2247     * three purposes: it insulates us from concurrent changes in
2248     * the contents of coll, it type-checks all of the elements in
2249 jsr166 1.6 * coll, and it provides all-or-nothing semantics (which we
2250 dl 1.1 * wouldn't get if we type-checked each element as we added it).
2251     */
2252     E[] a = null;
2253     try {
2254     a = coll.toArray(zeroLengthElementArray());
2255 jsr166 1.6 } catch (ArrayStoreException e) {
2256 dl 1.1 throw new ClassCastException();
2257     }
2258    
2259     boolean result = false;
2260     for (E e : a)
2261     result |= c.add(e);
2262     return result;
2263     }
2264    
2265     private E[] zeroLengthElementArray = null; // Lazily initialized
2266    
2267     /*
2268 jsr166 1.4 * We don't need locking or volatile, because it's OK if we create
2269 dl 1.1 * several zeroLengthElementArrays, and they're immutable.
2270     */
2271     E[] zeroLengthElementArray() {
2272     if (zeroLengthElementArray == null)
2273     zeroLengthElementArray = (E[]) Array.newInstance(type, 0);
2274     return zeroLengthElementArray;
2275     }
2276     }
2277    
2278     /**
2279     * Returns a dynamically typesafe view of the specified set.
2280     * Any attempt to insert an element of the wrong type will result in
2281     * an immediate <tt>ClassCastException</tt>. Assuming a set contains
2282     * no incorrectly typed elements prior to the time a dynamically typesafe
2283     * view is generated, and that all subsequent access to the set
2284     * takes place through the view, it is <i>guaranteed</i> that the
2285     * set cannot contain an incorrectly typed element.
2286     *
2287     * <p>A discussion of the use of dynamically typesafe views may be
2288     * found in the documentation for the {@link #checkedCollection checkedCollection}
2289     * method.
2290     *
2291     * <p>The returned set will be serializable if the specified set is
2292     * serializable.
2293     *
2294     * @param s the set for which a dynamically typesafe view is to be
2295     * returned
2296     * @param type the type of element that <tt>s</tt> is permitted to hold
2297     * @return a dynamically typesafe view of the specified set
2298     * @since 1.5
2299     */
2300     public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {
2301     return new CheckedSet<E>(s, type);
2302     }
2303 jsr166 1.4
2304 dl 1.1 /**
2305     * @serial include
2306     */
2307     static class CheckedSet<E> extends CheckedCollection<E>
2308     implements Set<E>, Serializable
2309     {
2310     private static final long serialVersionUID = 4694047833775013803L;
2311    
2312     CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); }
2313    
2314     public boolean equals(Object o) { return c.equals(o); }
2315     public int hashCode() { return c.hashCode(); }
2316     }
2317    
2318     /**
2319     * Returns a dynamically typesafe view of the specified sorted set. Any
2320     * attempt to insert an element of the wrong type will result in an
2321     * immediate <tt>ClassCastException</tt>. Assuming a sorted set contains
2322     * no incorrectly typed elements prior to the time a dynamically typesafe
2323     * view is generated, and that all subsequent access to the sorted set
2324     * takes place through the view, it is <i>guaranteed</i> that the sorted
2325     * set cannot contain an incorrectly typed element.
2326     *
2327     * <p>A discussion of the use of dynamically typesafe views may be
2328     * found in the documentation for the {@link #checkedCollection checkedCollection}
2329     * method.
2330     *
2331     * <p>The returned sorted set will be serializable if the specified sorted
2332     * set is serializable.
2333     *
2334     * @param s the sorted set for which a dynamically typesafe view is to be
2335     * returned
2336     * @param type the type of element that <tt>s</tt> is permitted to hold
2337     * @return a dynamically typesafe view of the specified sorted set
2338     * @since 1.5
2339     */
2340     public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
2341     Class<E> type) {
2342     return new CheckedSortedSet<E>(s, type);
2343     }
2344    
2345     /**
2346     * @serial include
2347     */
2348     static class CheckedSortedSet<E> extends CheckedSet<E>
2349     implements SortedSet<E>, Serializable
2350     {
2351     private static final long serialVersionUID = 1599911165492914959L;
2352     private final SortedSet<E> ss;
2353    
2354     CheckedSortedSet(SortedSet<E> s, Class<E> type) {
2355     super(s, type);
2356     ss = s;
2357     }
2358    
2359     public Comparator<? super E> comparator() { return ss.comparator(); }
2360     public E first() { return ss.first(); }
2361     public E last() { return ss.last(); }
2362    
2363     public SortedSet<E> subSet(E fromElement, E toElement) {
2364     return new CheckedSortedSet<E>(ss.subSet(fromElement,toElement),
2365     type);
2366     }
2367     public SortedSet<E> headSet(E toElement) {
2368     return new CheckedSortedSet<E>(ss.headSet(toElement), type);
2369     }
2370     public SortedSet<E> tailSet(E fromElement) {
2371     return new CheckedSortedSet<E>(ss.tailSet(fromElement), type);
2372     }
2373     }
2374    
2375     /**
2376     * Returns a dynamically typesafe view of the specified list.
2377     * Any attempt to insert an element of the wrong type will result in
2378     * an immediate <tt>ClassCastException</tt>. Assuming a list contains
2379     * no incorrectly typed elements prior to the time a dynamically typesafe
2380     * view is generated, and that all subsequent access to the list
2381     * takes place through the view, it is <i>guaranteed</i> that the
2382     * list cannot contain an incorrectly typed element.
2383     *
2384     * <p>A discussion of the use of dynamically typesafe views may be
2385     * found in the documentation for the {@link #checkedCollection checkedCollection}
2386     * method.
2387     *
2388     * <p>The returned list will be serializable if the specified list is
2389     * serializable.
2390     *
2391     * @param list the list for which a dynamically typesafe view is to be
2392     * returned
2393     * @param type the type of element that <tt>list</tt> is permitted to hold
2394     * @return a dynamically typesafe view of the specified list
2395     * @since 1.5
2396     */
2397     public static <E> List<E> checkedList(List<E> list, Class<E> type) {
2398     return (list instanceof RandomAccess ?
2399     new CheckedRandomAccessList<E>(list, type) :
2400     new CheckedList<E>(list, type));
2401     }
2402    
2403     /**
2404     * @serial include
2405     */
2406     static class CheckedList<E> extends CheckedCollection<E>
2407     implements List<E>
2408     {
2409     static final long serialVersionUID = 65247728283967356L;
2410     final List<E> list;
2411    
2412     CheckedList(List<E> list, Class<E> type) {
2413     super(list, type);
2414     this.list = list;
2415     }
2416    
2417     public boolean equals(Object o) { return list.equals(o); }
2418     public int hashCode() { return list.hashCode(); }
2419     public E get(int index) { return list.get(index); }
2420     public E remove(int index) { return list.remove(index); }
2421     public int indexOf(Object o) { return list.indexOf(o); }
2422     public int lastIndexOf(Object o) { return list.lastIndexOf(o); }
2423    
2424     public E set(int index, E element) {
2425     typeCheck(element);
2426     return list.set(index, element);
2427     }
2428    
2429     public void add(int index, E element) {
2430     typeCheck(element);
2431     list.add(index, element);
2432     }
2433    
2434     public boolean addAll(int index, Collection<? extends E> c) {
2435     // See CheckCollection.addAll, above, for an explanation
2436     E[] a = null;
2437     try {
2438     a = c.toArray(zeroLengthElementArray());
2439 jsr166 1.6 } catch (ArrayStoreException e) {
2440 dl 1.1 throw new ClassCastException();
2441     }
2442    
2443     return list.addAll(index, Arrays.asList(a));
2444     }
2445     public ListIterator<E> listIterator() { return listIterator(0); }
2446    
2447     public ListIterator<E> listIterator(final int index) {
2448     return new ListIterator<E>() {
2449     ListIterator<E> i = list.listIterator(index);
2450    
2451     public boolean hasNext() { return i.hasNext(); }
2452     public E next() { return i.next(); }
2453     public boolean hasPrevious() { return i.hasPrevious(); }
2454     public E previous() { return i.previous(); }
2455     public int nextIndex() { return i.nextIndex(); }
2456     public int previousIndex() { return i.previousIndex(); }
2457     public void remove() { i.remove(); }
2458    
2459 jsr166 1.5 public void set(E e) {
2460     typeCheck(e);
2461     i.set(e);
2462 dl 1.1 }
2463    
2464 jsr166 1.5 public void add(E e) {
2465     typeCheck(e);
2466     i.add(e);
2467 dl 1.1 }
2468     };
2469     }
2470    
2471     public List<E> subList(int fromIndex, int toIndex) {
2472     return new CheckedList<E>(list.subList(fromIndex, toIndex), type);
2473     }
2474     }
2475    
2476     /**
2477     * @serial include
2478     */
2479     static class CheckedRandomAccessList<E> extends CheckedList<E>
2480     implements RandomAccess
2481     {
2482     private static final long serialVersionUID = 1638200125423088369L;
2483    
2484     CheckedRandomAccessList(List<E> list, Class<E> type) {
2485     super(list, type);
2486     }
2487    
2488     public List<E> subList(int fromIndex, int toIndex) {
2489     return new CheckedRandomAccessList<E>(
2490     list.subList(fromIndex, toIndex), type);
2491     }
2492     }
2493    
2494     /**
2495     * Returns a dynamically typesafe view of the specified map. Any attempt
2496     * to insert a mapping whose key or value have the wrong type will result
2497     * in an immediate <tt>ClassCastException</tt>. Similarly, any attempt to
2498     * modify the value currently associated with a key will result in an
2499     * immediate <tt>ClassCastException</tt>, whether the modification is
2500     * attempted directly through the map itself, or through a {@link
2501     * Map.Entry} instance obtained from the map's {@link Map#entrySet()
2502     * entry set} view.
2503     *
2504     * <p>Assuming a map contains no incorrectly typed keys or values
2505     * prior to the time a dynamically typesafe view is generated, and
2506     * that all subsequent access to the map takes place through the view
2507     * (or one of its collection views), it is <i>guaranteed</i> that the
2508     * map cannot contain an incorrectly typed key or value.
2509     *
2510     * <p>A discussion of the use of dynamically typesafe views may be
2511     * found in the documentation for the {@link #checkedCollection checkedCollection}
2512     * method.
2513     *
2514     * <p>The returned map will be serializable if the specified map is
2515     * serializable.
2516     *
2517     * @param m the map for which a dynamically typesafe view is to be
2518     * returned
2519     * @param keyType the type of key that <tt>m</tt> is permitted to hold
2520     * @param valueType the type of value that <tt>m</tt> is permitted to hold
2521     * @return a dynamically typesafe view of the specified map
2522     * @since 1.5
2523     */
2524     public static <K, V> Map<K, V> checkedMap(Map<K, V> m, Class<K> keyType,
2525     Class<V> valueType) {
2526     return new CheckedMap<K,V>(m, keyType, valueType);
2527     }
2528    
2529    
2530     /**
2531     * @serial include
2532     */
2533     private static class CheckedMap<K,V> implements Map<K,V>,
2534     Serializable
2535     {
2536     private static final long serialVersionUID = 5742860141034234728L;
2537    
2538     private final Map<K, V> m;
2539     final Class<K> keyType;
2540     final Class<V> valueType;
2541    
2542     private void typeCheck(Object key, Object value) {
2543     if (!keyType.isInstance(key))
2544     throw new ClassCastException("Attempt to insert " +
2545     key.getClass() + " key into collection with key type "
2546     + keyType);
2547    
2548     if (!valueType.isInstance(value))
2549     throw new ClassCastException("Attempt to insert " +
2550     value.getClass() +" value into collection with value type "
2551     + valueType);
2552     }
2553    
2554     CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) {
2555     if (m == null || keyType == null || valueType == null)
2556     throw new NullPointerException();
2557     this.m = m;
2558     this.keyType = keyType;
2559     this.valueType = valueType;
2560     }
2561    
2562     public int size() { return m.size(); }
2563     public boolean isEmpty() { return m.isEmpty(); }
2564     public boolean containsKey(Object key) { return m.containsKey(key); }
2565     public boolean containsValue(Object v) { return m.containsValue(v); }
2566     public V get(Object key) { return m.get(key); }
2567     public V remove(Object key) { return m.remove(key); }
2568     public void clear() { m.clear(); }
2569     public Set<K> keySet() { return m.keySet(); }
2570     public Collection<V> values() { return m.values(); }
2571     public boolean equals(Object o) { return m.equals(o); }
2572     public int hashCode() { return m.hashCode(); }
2573     public String toString() { return m.toString(); }
2574    
2575     public V put(K key, V value) {
2576     typeCheck(key, value);
2577     return m.put(key, value);
2578     }
2579    
2580     public void putAll(Map<? extends K, ? extends V> t) {
2581     // See CheckCollection.addAll, above, for an explanation
2582     K[] keys = null;
2583     try {
2584     keys = t.keySet().toArray(zeroLengthKeyArray());
2585 jsr166 1.6 } catch (ArrayStoreException e) {
2586 dl 1.1 throw new ClassCastException();
2587     }
2588     V[] values = null;
2589     try {
2590     values = t.values().toArray(zeroLengthValueArray());
2591 jsr166 1.6 } catch (ArrayStoreException e) {
2592 dl 1.1 throw new ClassCastException();
2593     }
2594    
2595     if (keys.length != values.length)
2596     throw new ConcurrentModificationException();
2597    
2598     for (int i = 0; i < keys.length; i++)
2599     m.put(keys[i], values[i]);
2600     }
2601    
2602     // Lazily initialized
2603     private K[] zeroLengthKeyArray = null;
2604     private V[] zeroLengthValueArray = null;
2605    
2606     /*
2607 jsr166 1.4 * We don't need locking or volatile, because it's OK if we create
2608 dl 1.1 * several zeroLengthValueArrays, and they're immutable.
2609     */
2610     private K[] zeroLengthKeyArray() {
2611     if (zeroLengthKeyArray == null)
2612     zeroLengthKeyArray = (K[]) Array.newInstance(keyType, 0);
2613     return zeroLengthKeyArray;
2614     }
2615     private V[] zeroLengthValueArray() {
2616     if (zeroLengthValueArray == null)
2617     zeroLengthValueArray = (V[]) Array.newInstance(valueType, 0);
2618     return zeroLengthValueArray;
2619     }
2620    
2621     private transient Set<Map.Entry<K,V>> entrySet = null;
2622    
2623     public Set<Map.Entry<K,V>> entrySet() {
2624     if (entrySet==null)
2625     entrySet = new CheckedEntrySet<K,V>(m.entrySet(), valueType);
2626     return entrySet;
2627     }
2628    
2629     /**
2630     * We need this class in addition to CheckedSet as Map.Entry permits
2631     * modification of the backing Map via the setValue operation. This
2632     * class is subtle: there are many possible attacks that must be
2633     * thwarted.
2634     *
2635     * @serial exclude
2636     */
2637     static class CheckedEntrySet<K,V> implements Set<Map.Entry<K,V>> {
2638     Set<Map.Entry<K,V>> s;
2639     Class<V> valueType;
2640    
2641     CheckedEntrySet(Set<Map.Entry<K, V>> s, Class<V> valueType) {
2642     this.s = s;
2643     this.valueType = valueType;
2644     }
2645    
2646     public int size() { return s.size(); }
2647     public boolean isEmpty() { return s.isEmpty(); }
2648     public String toString() { return s.toString(); }
2649     public int hashCode() { return s.hashCode(); }
2650     public boolean remove(Object o) { return s.remove(o); }
2651     public boolean removeAll(Collection<?> coll) {
2652     return s.removeAll(coll);
2653     }
2654     public boolean retainAll(Collection<?> coll) {
2655     return s.retainAll(coll);
2656     }
2657     public void clear() {
2658     s.clear();
2659     }
2660    
2661 jsr166 1.5 public boolean add(Map.Entry<K, V> e){
2662 dl 1.1 throw new UnsupportedOperationException();
2663     }
2664     public boolean addAll(Collection<? extends Map.Entry<K, V>> coll) {
2665     throw new UnsupportedOperationException();
2666     }
2667    
2668    
2669     public Iterator<Map.Entry<K,V>> iterator() {
2670     return new Iterator<Map.Entry<K,V>>() {
2671     Iterator<Map.Entry<K, V>> i = s.iterator();
2672    
2673     public boolean hasNext() { return i.hasNext(); }
2674     public void remove() { i.remove(); }
2675    
2676     public Map.Entry<K,V> next() {
2677     return new CheckedEntry<K,V>(i.next(), valueType);
2678     }
2679     };
2680     }
2681    
2682     public Object[] toArray() {
2683     Object[] source = s.toArray();
2684    
2685     /*
2686     * Ensure that we don't get an ArrayStoreException even if
2687     * s.toArray returns an array of something other than Object
2688     */
2689     Object[] dest = (CheckedEntry.class.isInstance(
2690     source.getClass().getComponentType()) ? source :
2691     new Object[source.length]);
2692    
2693     for (int i = 0; i < source.length; i++)
2694     dest[i] = new CheckedEntry<K,V>((Map.Entry<K,V>)source[i],
2695     valueType);
2696     return dest;
2697     }
2698    
2699     public <T> T[] toArray(T[] a) {
2700     // We don't pass a to s.toArray, to avoid window of
2701     // vulnerability wherein an unscrupulous multithreaded client
2702     // could get his hands on raw (unwrapped) Entries from s.
2703 jsr166 1.10 Object[] arr = s.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
2704 dl 1.1
2705     for (int i=0; i<arr.length; i++)
2706     arr[i] = new CheckedEntry<K,V>((Map.Entry<K,V>)arr[i],
2707     valueType);
2708     if (arr.length > a.length)
2709     return (T[])arr;
2710    
2711     System.arraycopy(arr, 0, a, 0, arr.length);
2712     if (a.length > arr.length)
2713     a[arr.length] = null;
2714     return a;
2715     }
2716    
2717     /**
2718     * This method is overridden to protect the backing set against
2719     * an object with a nefarious equals function that senses
2720     * that the equality-candidate is Map.Entry and calls its
2721     * setValue method.
2722     */
2723     public boolean contains(Object o) {
2724     if (!(o instanceof Map.Entry))
2725     return false;
2726     return s.contains(
2727     new CheckedEntry<K,V>((Map.Entry<K,V>) o, valueType));
2728     }
2729    
2730     /**
2731     * The next two methods are overridden to protect against
2732     * an unscrupulous collection whose contains(Object o) method
2733     * senses when o is a Map.Entry, and calls o.setValue.
2734     */
2735     public boolean containsAll(Collection<?> coll) {
2736     Iterator<?> e = coll.iterator();
2737     while (e.hasNext())
2738     if (!contains(e.next())) // Invokes safe contains() above
2739     return false;
2740     return true;
2741     }
2742    
2743     public boolean equals(Object o) {
2744     if (o == this)
2745     return true;
2746     if (!(o instanceof Set))
2747     return false;
2748     Set<?> that = (Set<?>) o;
2749     if (that.size() != s.size())
2750     return false;
2751     return containsAll(that); // Invokes safe containsAll() above
2752     }
2753    
2754     /**
2755     * This "wrapper class" serves two purposes: it prevents
2756     * the client from modifying the backing Map, by short-circuiting
2757     * the setValue method, and it protects the backing Map against
2758     * an ill-behaved Map.Entry that attempts to modify another
2759     * Map Entry when asked to perform an equality check.
2760     */
2761     private static class CheckedEntry<K,V> implements Map.Entry<K,V> {
2762     private Map.Entry<K, V> e;
2763     private Class<V> valueType;
2764    
2765     CheckedEntry(Map.Entry<K, V> e, Class<V> valueType) {
2766     this.e = e;
2767     this.valueType = valueType;
2768     }
2769    
2770     public K getKey() { return e.getKey(); }
2771     public V getValue() { return e.getValue(); }
2772     public int hashCode() { return e.hashCode(); }
2773     public String toString() { return e.toString(); }
2774    
2775    
2776     public V setValue(V value) {
2777     if (!valueType.isInstance(value))
2778     throw new ClassCastException("Attempt to insert " +
2779     value.getClass() +
2780     " value into collection with value type " + valueType);
2781     return e.setValue(value);
2782     }
2783    
2784     public boolean equals(Object o) {
2785     if (!(o instanceof Map.Entry))
2786     return false;
2787     Map.Entry t = (Map.Entry)o;
2788     return eq(e.getKey(), t.getKey()) &&
2789     eq(e.getValue(), t.getValue());
2790     }
2791     }
2792     }
2793     }
2794    
2795     /**
2796     * Returns a dynamically typesafe view of the specified sorted map. Any
2797     * attempt to insert a mapping whose key or value have the wrong type will
2798     * result in an immediate <tt>ClassCastException</tt>. Similarly, any
2799     * attempt to modify the value currently associated with a key will result
2800     * in an immediate <tt>ClassCastException</tt>, whether the modification
2801     * is attempted directly through the map itself, or through a {@link
2802     * Map.Entry} instance obtained from the map's {@link Map#entrySet() entry
2803     * set} view.
2804     *
2805     * <p>Assuming a map contains no incorrectly typed keys or values
2806     * prior to the time a dynamically typesafe view is generated, and
2807     * that all subsequent access to the map takes place through the view
2808     * (or one of its collection views), it is <i>guaranteed</i> that the
2809     * map cannot contain an incorrectly typed key or value.
2810     *
2811     * <p>A discussion of the use of dynamically typesafe views may be
2812     * found in the documentation for the {@link #checkedCollection checkedCollection}
2813     * method.
2814     *
2815     * <p>The returned map will be serializable if the specified map is
2816     * serializable.
2817     *
2818     * @param m the map for which a dynamically typesafe view is to be
2819     * returned
2820     * @param keyType the type of key that <tt>m</tt> is permitted to hold
2821     * @param valueType the type of value that <tt>m</tt> is permitted to hold
2822     * @return a dynamically typesafe view of the specified map
2823     * @since 1.5
2824     */
2825     public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,
2826     Class<K> keyType,
2827     Class<V> valueType) {
2828     return new CheckedSortedMap<K,V>(m, keyType, valueType);
2829     }
2830    
2831     /**
2832     * @serial include
2833     */
2834     static class CheckedSortedMap<K,V> extends CheckedMap<K,V>
2835     implements SortedMap<K,V>, Serializable
2836     {
2837     private static final long serialVersionUID = 1599671320688067438L;
2838    
2839     private final SortedMap<K, V> sm;
2840    
2841     CheckedSortedMap(SortedMap<K, V> m,
2842     Class<K> keyType, Class<V> valueType) {
2843     super(m, keyType, valueType);
2844     sm = m;
2845     }
2846    
2847     public Comparator<? super K> comparator() { return sm.comparator(); }
2848     public K firstKey() { return sm.firstKey(); }
2849     public K lastKey() { return sm.lastKey(); }
2850    
2851     public SortedMap<K,V> subMap(K fromKey, K toKey) {
2852     return new CheckedSortedMap<K,V>(sm.subMap(fromKey, toKey),
2853     keyType, valueType);
2854     }
2855    
2856     public SortedMap<K,V> headMap(K toKey) {
2857     return new CheckedSortedMap<K,V>(sm.headMap(toKey),
2858     keyType, valueType);
2859     }
2860    
2861     public SortedMap<K,V> tailMap(K fromKey) {
2862     return new CheckedSortedMap<K,V>(sm.tailMap(fromKey),
2863     keyType, valueType);
2864     }
2865     }
2866    
2867     // Miscellaneous
2868    
2869     /**
2870     * The empty set (immutable). This set is serializable.
2871     *
2872     * @see #emptySet()
2873     */
2874     public static final Set EMPTY_SET = new EmptySet();
2875    
2876     /**
2877     * Returns the empty set (immutable). This set is serializable.
2878     * Unlike the like-named field, this method is parameterized.
2879     *
2880     * <p>This example illustrates the type-safe way to obtain an empty set:
2881     * <pre>
2882     * Set&lt;String&gt; s = Collections.emptySet();
2883     * </pre>
2884     * Implementation note: Implementations of this method need not
2885     * create a separate <tt>Set</tt> object for each call. Using this
2886     * method is likely to have comparable cost to using the like-named
2887     * field. (Unlike this method, the field does not provide type safety.)
2888     *
2889     * @see #EMPTY_SET
2890     * @since 1.5
2891     */
2892     public static final <T> Set<T> emptySet() {
2893     return (Set<T>) EMPTY_SET;
2894     }
2895    
2896     /**
2897     * @serial include
2898     */
2899     private static class EmptySet extends AbstractSet<Object> implements Serializable {
2900     // use serialVersionUID from JDK 1.2.2 for interoperability
2901     private static final long serialVersionUID = 1582296315990362920L;
2902    
2903     public Iterator<Object> iterator() {
2904     return new Iterator<Object>() {
2905     public boolean hasNext() {
2906     return false;
2907     }
2908     public Object next() {
2909     throw new NoSuchElementException();
2910     }
2911     public void remove() {
2912     throw new UnsupportedOperationException();
2913     }
2914     };
2915     }
2916    
2917     public int size() {return 0;}
2918    
2919     public boolean contains(Object obj) {return false;}
2920    
2921     // Preserves singleton property
2922     private Object readResolve() {
2923     return EMPTY_SET;
2924     }
2925     }
2926    
2927     /**
2928     * The empty list (immutable). This list is serializable.
2929     *
2930     * @see #emptyList()
2931     */
2932     public static final List EMPTY_LIST = new EmptyList();
2933    
2934     /**
2935     * Returns the empty list (immutable). This list is serializable.
2936     *
2937     * <p>This example illustrates the type-safe way to obtain an empty list:
2938     * <pre>
2939     * List&lt;String&gt; s = Collections.emptyList();
2940     * </pre>
2941     * Implementation note: Implementations of this method need not
2942     * create a separate <tt>List</tt> object for each call. Using this
2943     * method is likely to have comparable cost to using the like-named
2944     * field. (Unlike this method, the field does not provide type safety.)
2945     *
2946     * @see #EMPTY_LIST
2947     * @since 1.5
2948     */
2949     public static final <T> List<T> emptyList() {
2950     return (List<T>) EMPTY_LIST;
2951     }
2952    
2953     /**
2954     * @serial include
2955     */
2956     private static class EmptyList
2957     extends AbstractList<Object>
2958     implements RandomAccess, Serializable {
2959     // use serialVersionUID from JDK 1.2.2 for interoperability
2960     private static final long serialVersionUID = 8842843931221139166L;
2961    
2962     public int size() {return 0;}
2963    
2964     public boolean contains(Object obj) {return false;}
2965    
2966     public Object get(int index) {
2967     throw new IndexOutOfBoundsException("Index: "+index);
2968     }
2969    
2970     // Preserves singleton property
2971     private Object readResolve() {
2972     return EMPTY_LIST;
2973     }
2974     }
2975    
2976     /**
2977     * The empty map (immutable). This map is serializable.
2978     *
2979     * @see #emptyMap()
2980     * @since 1.3
2981     */
2982     public static final Map EMPTY_MAP = new EmptyMap();
2983    
2984     /**
2985     * Returns the empty map (immutable). This map is serializable.
2986     *
2987     * <p>This example illustrates the type-safe way to obtain an empty set:
2988     * <pre>
2989     * Map&lt;String, Date&gt; s = Collections.emptyMap();
2990     * </pre>
2991     * Implementation note: Implementations of this method need not
2992     * create a separate <tt>Map</tt> object for each call. Using this
2993     * method is likely to have comparable cost to using the like-named
2994     * field. (Unlike this method, the field does not provide type safety.)
2995     *
2996     * @see #EMPTY_MAP
2997     * @since 1.5
2998     */
2999     public static final <K,V> Map<K,V> emptyMap() {
3000     return (Map<K,V>) EMPTY_MAP;
3001     }
3002    
3003     private static class EmptyMap
3004     extends AbstractMap<Object,Object>
3005     implements Serializable {
3006    
3007     private static final long serialVersionUID = 6428348081105594320L;
3008    
3009     public int size() {return 0;}
3010    
3011     public boolean isEmpty() {return true;}
3012    
3013     public boolean containsKey(Object key) {return false;}
3014    
3015     public boolean containsValue(Object value) {return false;}
3016    
3017     public Object get(Object key) {return null;}
3018    
3019     public Set<Object> keySet() {return Collections.<Object>emptySet();}
3020    
3021     public Collection<Object> values() {return Collections.<Object>emptySet();}
3022    
3023     public Set<Map.Entry<Object,Object>> entrySet() {
3024     return Collections.emptySet();
3025     }
3026    
3027     public boolean equals(Object o) {
3028     return (o instanceof Map) && ((Map)o).size()==0;
3029     }
3030    
3031     public int hashCode() {return 0;}
3032    
3033     // Preserves singleton property
3034     private Object readResolve() {
3035     return EMPTY_MAP;
3036     }
3037     }
3038    
3039     /**
3040     * Returns an immutable set containing only the specified object.
3041     * The returned set is serializable.
3042     *
3043     * @param o the sole object to be stored in the returned set.
3044     * @return an immutable set containing only the specified object.
3045     */
3046     public static <T> Set<T> singleton(T o) {
3047     return new SingletonSet<T>(o);
3048     }
3049    
3050     /**
3051     * @serial include
3052     */
3053     private static class SingletonSet<E>
3054     extends AbstractSet<E>
3055     implements Serializable
3056     {
3057     // use serialVersionUID from JDK 1.2.2 for interoperability
3058     private static final long serialVersionUID = 3193687207550431679L;
3059    
3060     final private E element;
3061    
3062 jsr166 1.5 SingletonSet(E e) {element = e;}
3063 dl 1.1
3064     public Iterator<E> iterator() {
3065     return new Iterator<E>() {
3066     private boolean hasNext = true;
3067     public boolean hasNext() {
3068     return hasNext;
3069     }
3070     public E next() {
3071     if (hasNext) {
3072     hasNext = false;
3073     return element;
3074     }
3075     throw new NoSuchElementException();
3076     }
3077     public void remove() {
3078     throw new UnsupportedOperationException();
3079     }
3080     };
3081     }
3082    
3083     public int size() {return 1;}
3084    
3085     public boolean contains(Object o) {return eq(o, element);}
3086     }
3087    
3088     /**
3089     * Returns an immutable list containing only the specified object.
3090     * The returned list is serializable.
3091     *
3092     * @param o the sole object to be stored in the returned list.
3093     * @return an immutable list containing only the specified object.
3094     * @since 1.3
3095     */
3096     public static <T> List<T> singletonList(T o) {
3097     return new SingletonList<T>(o);
3098     }
3099    
3100     private static class SingletonList<E>
3101     extends AbstractList<E>
3102     implements RandomAccess, Serializable {
3103    
3104     static final long serialVersionUID = 3093736618740652951L;
3105    
3106     private final E element;
3107    
3108     SingletonList(E obj) {element = obj;}
3109    
3110     public int size() {return 1;}
3111    
3112     public boolean contains(Object obj) {return eq(obj, element);}
3113    
3114     public E get(int index) {
3115     if (index != 0)
3116     throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");
3117     return element;
3118     }
3119     }
3120    
3121     /**
3122     * Returns an immutable map, mapping only the specified key to the
3123     * specified value. The returned map is serializable.
3124     *
3125     * @param key the sole key to be stored in the returned map.
3126     * @param value the value to which the returned map maps <tt>key</tt>.
3127     * @return an immutable map containing only the specified key-value
3128     * mapping.
3129     * @since 1.3
3130     */
3131     public static <K,V> Map<K,V> singletonMap(K key, V value) {
3132     return new SingletonMap<K,V>(key, value);
3133     }
3134    
3135     private static class SingletonMap<K,V>
3136     extends AbstractMap<K,V>
3137     implements Serializable {
3138     private static final long serialVersionUID = -6979724477215052911L;
3139    
3140     private final K k;
3141     private final V v;
3142    
3143     SingletonMap(K key, V value) {
3144     k = key;
3145     v = value;
3146     }
3147    
3148     public int size() {return 1;}
3149    
3150     public boolean isEmpty() {return false;}
3151    
3152     public boolean containsKey(Object key) {return eq(key, k);}
3153    
3154     public boolean containsValue(Object value) {return eq(value, v);}
3155    
3156     public V get(Object key) {return (eq(key, k) ? v : null);}
3157    
3158     private transient Set<K> keySet = null;
3159     private transient Set<Map.Entry<K,V>> entrySet = null;
3160     private transient Collection<V> values = null;
3161    
3162     public Set<K> keySet() {
3163     if (keySet==null)
3164     keySet = singleton(k);
3165     return keySet;
3166     }
3167    
3168     public Set<Map.Entry<K,V>> entrySet() {
3169     if (entrySet==null)
3170 jsr166 1.4 entrySet = Collections.<Map.Entry<K,V>>singleton(
3171     new SimpleImmutableEntry<K,V>(k, v));
3172 dl 1.1 return entrySet;
3173     }
3174    
3175     public Collection<V> values() {
3176     if (values==null)
3177     values = singleton(v);
3178     return values;
3179     }
3180    
3181     }
3182    
3183     /**
3184     * Returns an immutable list consisting of <tt>n</tt> copies of the
3185     * specified object. The newly allocated data object is tiny (it contains
3186     * a single reference to the data object). This method is useful in
3187     * combination with the <tt>List.addAll</tt> method to grow lists.
3188     * The returned list is serializable.
3189     *
3190     * @param n the number of elements in the returned list.
3191     * @param o the element to appear repeatedly in the returned list.
3192     * @return an immutable list consisting of <tt>n</tt> copies of the
3193     * specified object.
3194     * @throws IllegalArgumentException if n &lt; 0.
3195     * @see List#addAll(Collection)
3196     * @see List#addAll(int, Collection)
3197     */
3198     public static <T> List<T> nCopies(int n, T o) {
3199 jsr166 1.14 if (n < 0)
3200     throw new IllegalArgumentException("List length = " + n);
3201 dl 1.1 return new CopiesList<T>(n, o);
3202     }
3203    
3204     /**
3205     * @serial include
3206     */
3207     private static class CopiesList<E>
3208     extends AbstractList<E>
3209     implements RandomAccess, Serializable
3210     {
3211     static final long serialVersionUID = 2739099268398711800L;
3212    
3213 jsr166 1.14 final int n;
3214     final E element;
3215 dl 1.1
3216 jsr166 1.5 CopiesList(int n, E e) {
3217 jsr166 1.14 assert n >= 0;
3218 dl 1.1 this.n = n;
3219 jsr166 1.5 element = e;
3220 dl 1.1 }
3221    
3222     public int size() {
3223     return n;
3224     }
3225    
3226     public boolean contains(Object obj) {
3227     return n != 0 && eq(obj, element);
3228     }
3229    
3230 jsr166 1.14 public int indexOf(Object o) {
3231     return contains(o) ? 0 : -1;
3232     }
3233    
3234     public int lastIndexOf(Object o) {
3235     return contains(o) ? n - 1 : -1;
3236     }
3237    
3238 dl 1.1 public E get(int index) {
3239 jsr166 1.14 if (index < 0 || index >= n)
3240 dl 1.1 throw new IndexOutOfBoundsException("Index: "+index+
3241     ", Size: "+n);
3242     return element;
3243     }
3244 jsr166 1.14
3245     public Object[] toArray() {
3246     final Object[] a = new Object[n];
3247     if (element != null)
3248     Arrays.fill(a, 0, n, element);
3249     return a;
3250     }
3251    
3252     public <T> T[] toArray(T[] a) {
3253     final int n = this.n;
3254     if (a.length < n) {
3255     a = (T[])java.lang.reflect.Array
3256     .newInstance(a.getClass().getComponentType(), n);
3257     if (element != null)
3258     Arrays.fill(a, 0, n, element);
3259     } else {
3260     Arrays.fill(a, 0, n, element);
3261     if (a.length > n)
3262     a[n] = null;
3263     }
3264     return a;
3265     }
3266    
3267     public List<E> subList(int fromIndex, int toIndex) {
3268     if (fromIndex < 0)
3269     throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
3270     if (toIndex > n)
3271     throw new IndexOutOfBoundsException("toIndex = " + toIndex);
3272     if (fromIndex > toIndex)
3273     throw new IllegalArgumentException("fromIndex(" + fromIndex +
3274     ") > toIndex(" + toIndex + ")");
3275     return new CopiesList(toIndex - fromIndex, element);
3276     }
3277 dl 1.1 }
3278    
3279     /**
3280     * Returns a comparator that imposes the reverse of the <i>natural
3281     * ordering</i> on a collection of objects that implement the
3282     * <tt>Comparable</tt> interface. (The natural ordering is the ordering
3283     * imposed by the objects' own <tt>compareTo</tt> method.) This enables a
3284     * simple idiom for sorting (or maintaining) collections (or arrays) of
3285     * objects that implement the <tt>Comparable</tt> interface in
3286     * reverse-natural-order. For example, suppose a is an array of
3287     * strings. Then: <pre>
3288     * Arrays.sort(a, Collections.reverseOrder());
3289     * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>
3290     *
3291     * The returned comparator is serializable.
3292     *
3293     * @return a comparator that imposes the reverse of the <i>natural
3294     * ordering</i> on a collection of objects that implement
3295     * the <tt>Comparable</tt> interface.
3296     * @see Comparable
3297     */
3298     public static <T> Comparator<T> reverseOrder() {
3299     return (Comparator<T>) REVERSE_ORDER;
3300     }
3301    
3302     private static final Comparator REVERSE_ORDER = new ReverseComparator();
3303    
3304     /**
3305     * @serial include
3306     */
3307     private static class ReverseComparator<T>
3308     implements Comparator<Comparable<Object>>, Serializable {
3309    
3310     // use serialVersionUID from JDK 1.2.2 for interoperability
3311     private static final long serialVersionUID = 7207038068494060240L;
3312    
3313     public int compare(Comparable<Object> c1, Comparable<Object> c2) {
3314     return c2.compareTo(c1);
3315     }
3316     }
3317    
3318     /**
3319     * Returns a comparator that imposes the reverse ordering of the specified
3320     * comparator. If the specified comparator is null, this method is
3321     * equivalent to {@link #reverseOrder()} (in other words, it returns a
3322     * comparator that imposes the reverse of the <i>natural ordering</i> on a
3323     * collection of objects that implement the Comparable interface).
3324     *
3325     * <p>The returned comparator is serializable (assuming the specified
3326     * comparator is also serializable or null).
3327     *
3328     * @return a comparator that imposes the reverse ordering of the
3329     * specified comparator.
3330     * @since 1.5
3331     */
3332     public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) {
3333     if (cmp == null)
3334     return new ReverseComparator(); // Unchecked warning!!
3335 jsr166 1.4
3336 dl 1.1 return new ReverseComparator2<T>(cmp);
3337     }
3338 jsr166 1.4
3339 dl 1.1 /**
3340     * @serial include
3341     */
3342     private static class ReverseComparator2<T> implements Comparator<T>,
3343     Serializable
3344     {
3345     private static final long serialVersionUID = 4374092139857L;
3346 jsr166 1.4
3347 dl 1.1 /**
3348     * The comparator specified in the static factory. This will never
3349     * be null, as the static factory returns a ReverseComparator
3350     * instance if its argument is null.
3351     *
3352     * @serial
3353     */
3354     private Comparator<T> cmp;
3355 jsr166 1.4
3356 dl 1.1 ReverseComparator2(Comparator<T> cmp) {
3357     assert cmp != null;
3358     this.cmp = cmp;
3359     }
3360 jsr166 1.4
3361 dl 1.1 public int compare(T t1, T t2) {
3362     return cmp.compare(t2, t1);
3363     }
3364     }
3365    
3366     /**
3367     * Returns an enumeration over the specified collection. This provides
3368     * interoperability with legacy APIs that require an enumeration
3369     * as input.
3370     *
3371     * @param c the collection for which an enumeration is to be returned.
3372     * @return an enumeration over the specified collection.
3373     * @see Enumeration
3374     */
3375     public static <T> Enumeration<T> enumeration(final Collection<T> c) {
3376     return new Enumeration<T>() {
3377     Iterator<T> i = c.iterator();
3378    
3379     public boolean hasMoreElements() {
3380     return i.hasNext();
3381     }
3382    
3383     public T nextElement() {
3384     return i.next();
3385     }
3386     };
3387     }
3388    
3389     /**
3390     * Returns an array list containing the elements returned by the
3391     * specified enumeration in the order they are returned by the
3392     * enumeration. This method provides interoperability between
3393     * legacy APIs that return enumerations and new APIs that require
3394     * collections.
3395     *
3396     * @param e enumeration providing elements for the returned
3397     * array list
3398     * @return an array list containing the elements returned
3399     * by the specified enumeration.
3400     * @since 1.4
3401     * @see Enumeration
3402     * @see ArrayList
3403     */
3404     public static <T> ArrayList<T> list(Enumeration<T> e) {
3405     ArrayList<T> l = new ArrayList<T>();
3406     while (e.hasMoreElements())
3407     l.add(e.nextElement());
3408     return l;
3409     }
3410    
3411     /**
3412     * Returns true if the specified arguments are equal, or both null.
3413     */
3414     private static boolean eq(Object o1, Object o2) {
3415     return (o1==null ? o2==null : o1.equals(o2));
3416     }
3417    
3418     /**
3419     * Returns the number of elements in the specified collection equal to the
3420     * specified object. More formally, returns the number of elements
3421     * <tt>e</tt> in the collection such that
3422     * <tt>(o == null ? e == null : o.equals(e))</tt>.
3423     *
3424     * @param c the collection in which to determine the frequency
3425     * of <tt>o</tt>
3426     * @param o the object whose frequency is to be determined
3427     * @throws NullPointerException if <tt>c</tt> is null
3428     * @since 1.5
3429     */
3430     public static int frequency(Collection<?> c, Object o) {
3431     int result = 0;
3432     if (o == null) {
3433     for (Object e : c)
3434     if (e == null)
3435     result++;
3436     } else {
3437     for (Object e : c)
3438     if (o.equals(e))
3439     result++;
3440     }
3441     return result;
3442     }
3443    
3444     /**
3445     * Returns <tt>true</tt> if the two specified collections have no
3446     * elements in common.
3447     *
3448     * <p>Care must be exercised if this method is used on collections that
3449     * do not comply with the general contract for <tt>Collection</tt>.
3450     * Implementations may elect to iterate over either collection and test
3451     * for containment in the other collection (or to perform any equivalent
3452     * computation). If either collection uses a nonstandard equality test
3453     * (as does a {@link SortedSet} whose ordering is not <i>compatible with
3454     * equals</i>, or the key set of an {@link IdentityHashMap}), both
3455     * collections must use the same nonstandard equality test, or the
3456     * result of this method is undefined.
3457     *
3458     * <p>Note that it is permissible to pass the same collection in both
3459     * parameters, in which case the method will return true if and only if
3460     * the collection is empty.
3461     *
3462     * @param c1 a collection
3463     * @param c2 a collection
3464     * @throws NullPointerException if either collection is null
3465     * @since 1.5
3466     */
3467     public static boolean disjoint(Collection<?> c1, Collection<?> c2) {
3468     /*
3469     * We're going to iterate through c1 and test for inclusion in c2.
3470     * If c1 is a Set and c2 isn't, swap the collections. Otherwise,
3471     * place the shorter collection in c1. Hopefully this heuristic
3472     * will minimize the cost of the operation.
3473     */
3474     if ((c1 instanceof Set) && !(c2 instanceof Set) ||
3475     (c1.size() > c2.size())) {
3476     Collection<?> tmp = c1;
3477     c1 = c2;
3478     c2 = tmp;
3479     }
3480 jsr166 1.4
3481 dl 1.1 for (Object e : c1)
3482     if (c2.contains(e))
3483     return false;
3484     return true;
3485     }
3486    
3487     /**
3488     * Adds all of the specified elements to the specified collection.
3489     * Elements to be added may be specified individually or as an array.
3490     * The behavior of this convenience method is identical to that of
3491     * <tt>c.addAll(Arrays.asList(elements))</tt>, but this method is likely
3492     * to run significantly faster under most implementations.
3493     *
3494     * <p>When elements are specified individually, this method provides a
3495     * convenient way to add a few elements to an existing collection:
3496     * <pre>
3497     * Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");
3498     * </pre>
3499     *
3500     * @param c the collection into which <tt>elements</tt> are to be inserted
3501 jsr166 1.19 * @param elements the elements to insert into <tt>c</tt>
3502 dl 1.1 * @return <tt>true</tt> if the collection changed as a result of the call
3503     * @throws UnsupportedOperationException if <tt>c</tt> does not support
3504 jsr166 1.19 * the <tt>add</tt> operation
3505 dl 1.1 * @throws NullPointerException if <tt>elements</tt> contains one or more
3506 jsr166 1.6 * null values and <tt>c</tt> does not permit null elements, or
3507 dl 1.1 * if <tt>c</tt> or <tt>elements</tt> are <tt>null</tt>
3508 jsr166 1.6 * @throws IllegalArgumentException if some property of a value in
3509 dl 1.1 * <tt>elements</tt> prevents it from being added to <tt>c</tt>
3510     * @see Collection#addAll(Collection)
3511     * @since 1.5
3512     */
3513 jsr166 1.19 public static <T> boolean addAll(Collection<? super T> c, T... elements) {
3514 dl 1.1 boolean result = false;
3515 jsr166 1.19 for (T element : elements)
3516     result |= c.add(element);
3517 dl 1.1 return result;
3518     }
3519    
3520     /**
3521     * Returns a set backed by the specified map. The resulting set displays
3522     * the same ordering, concurrency, and performance characteristics as the
3523     * backing map. In essence, this factory method provides a {@link Set}
3524     * implementation corresponding to any {@link Map} implementation. There
3525     * is no need to use this method on a {@link Map} implementation that
3526     * already has a corresponding {@link Set} implementation (such as {@link
3527     * HashMap} or {@link TreeMap}).
3528     *
3529     * <p>Each method invocation on the set returned by this method results in
3530     * exactly one method invocation on the backing map or its <tt>keySet</tt>
3531     * view, with one exception. The <tt>addAll</tt> method is implemented
3532     * as a sequence of <tt>put</tt> invocations on the backing map.
3533     *
3534     * <p>The specified map must be empty at the time this method is invoked,
3535     * and should not be accessed directly after this method returns. These
3536     * conditions are ensured if the map is created empty, passed directly
3537     * to this method, and no reference to the map is retained, as illustrated
3538     * in the following code fragment:
3539     * <pre>
3540 jsr166 1.15 * Set&lt;Object&gt; weakHashSet = Collections.newSetFromMap(
3541 dl 1.1 * new WeakHashMap&lt;Object, Boolean&gt;());
3542     * </pre>
3543     *
3544     * @param map the backing map
3545     * @return the set backed by the map
3546     * @throws IllegalArgumentException if <tt>map</tt> is not empty
3547 jsr166 1.12 * @since 1.6
3548 dl 1.1 */
3549 jsr166 1.14 public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
3550     return new SetFromMap<E>(map);
3551 dl 1.1 }
3552    
3553 jsr166 1.14 private static class SetFromMap<E> extends AbstractSet<E>
3554 dl 1.1 implements Set<E>, Serializable
3555     {
3556     private final Map<E, Boolean> m; // The backing map
3557     private transient Set<E> keySet; // Its keySet
3558    
3559 jsr166 1.14 SetFromMap(Map<E, Boolean> map) {
3560 dl 1.1 if (!map.isEmpty())
3561     throw new IllegalArgumentException("Map is non-empty");
3562     m = map;
3563     keySet = map.keySet();
3564     }
3565    
3566     public int size() { return m.size(); }
3567     public boolean isEmpty() { return m.isEmpty(); }
3568     public boolean contains(Object o) { return m.containsKey(o); }
3569     public Iterator<E> iterator() { return keySet.iterator(); }
3570     public Object[] toArray() { return keySet.toArray(); }
3571     public <T> T[] toArray(T[] a) { return keySet.toArray(a); }
3572     public boolean add(E e) {
3573     return m.put(e, Boolean.TRUE) == null;
3574     }
3575     public boolean remove(Object o) { return m.remove(o) != null; }
3576    
3577     public boolean removeAll(Collection<?> c) {
3578     return keySet.removeAll(c);
3579     }
3580     public boolean retainAll(Collection<?> c) {
3581     return keySet.retainAll(c);
3582     }
3583     public void clear() { m.clear(); }
3584     public boolean equals(Object o) { return keySet.equals(o); }
3585     public int hashCode() { return keySet.hashCode(); }
3586    
3587     private static final long serialVersionUID = 2454657854757543876L;
3588    
3589     private void readObject(java.io.ObjectInputStream s)
3590     throws IOException, ClassNotFoundException
3591     {
3592     s.defaultReadObject();
3593     keySet = m.keySet();
3594     }
3595     }
3596    
3597     /**
3598     * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)
3599     * {@link Queue}. Method <tt>add</tt> is mapped to <tt>push</tt>,
3600     * <tt>remove</tt> is mapped to <tt>pop</tt> and so on. This
3601     * view can be useful when you would like to use a method
3602     * requiring a <tt>Queue</tt> but you need Lifo ordering.
3603 jsr166 1.17 *
3604 jsr166 1.13 * @param deque the deque
3605 dl 1.1 * @return the queue
3606     * @since 1.6
3607     */
3608     public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
3609     return new AsLIFOQueue<T>(deque);
3610     }
3611    
3612 jsr166 1.4 static class AsLIFOQueue<E> extends AbstractQueue<E>
3613 dl 1.1 implements Queue<E>, Serializable {
3614 dl 1.8 private static final long serialVersionUID = 1802017725587941708L;
3615 dl 1.1 private final Deque<E> q;
3616     AsLIFOQueue(Deque<E> q) { this.q = q; }
3617 jsr166 1.5 public boolean offer(E e) { return q.offerFirst(e); }
3618 dl 1.1 public E poll() { return q.pollFirst(); }
3619     public E remove() { return q.removeFirst(); }
3620     public E peek() { return q.peekFirst(); }
3621     public E element() { return q.getFirst(); }
3622     public int size() { return q.size(); }
3623     public boolean isEmpty() { return q.isEmpty(); }
3624     public boolean contains(Object o) { return q.contains(o); }
3625     public Iterator<E> iterator() { return q.iterator(); }
3626     public Object[] toArray() { return q.toArray(); }
3627     public <T> T[] toArray(T[] a) { return q.toArray(a); }
3628 jsr166 1.5 public boolean add(E e) { return q.offerFirst(e); }
3629 dl 1.1 public boolean remove(Object o) { return q.remove(o); }
3630     public void clear() { q.clear(); }
3631     }
3632     }