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