ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Collections.java
Revision: 1.33
Committed: Sun May 18 23:47:55 2008 UTC (16 years ago) by jsr166
Branch: MAIN
Changes since 1.32: +727 -727 lines
Log Message:
Sync with OpenJDK; untabify

File Contents

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