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 mod