27 import java.io.Serializable;
28 import java.io.ObjectOutputStream;
29 import java.io.IOException;
30 import java.lang.reflect.Array;
31 import java.util.function.BiConsumer;
32 import java.util.function.BiFunction;
33 import java.util.function.Consumer;
34 import java.util.function.Function;
35 import java.util.function.Predicate;
36 import java.util.function.UnaryOperator;
37 import java.util.stream.IntStream;
38 import java.util.stream.Stream;
39 import java.util.stream.StreamSupport;
40
41 /**
42 * This class consists exclusively of static methods that operate on or return
43 * collections. It contains polymorphic algorithms that operate on
44 * collections, "wrappers", which return a new collection backed by a
45 * specified collection, and a few other odds and ends.
46 *
47 * <p>The methods of this class all throw a <tt>NullPointerException</tt>
48 * if the collections or class objects provided to them are null.
49 *
50 * <p>The documentation for the polymorphic algorithms contained in this class
51 * generally includes a brief description of the <i>implementation</i>. Such
52 * descriptions should be regarded as <i>implementation notes</i>, rather than
53 * parts of the <i>specification</i>. Implementors should feel free to
54 * substitute other algorithms, so long as the specification itself is adhered
55 * to. (For example, the algorithm used by <tt>sort</tt> does not have to be
56 * a mergesort, but it does have to be <i>stable</i>.)
57 *
58 * <p>The "destructive" algorithms contained in this class, that is, the
59 * algorithms that modify the collection on which they operate, are specified
60 * to throw <tt>UnsupportedOperationException</tt> if the collection does not
61 * support the appropriate mutation primitive(s), such as the <tt>set</tt>
62 * method. These algorithms may, but are not required to, throw this
63 * exception if an invocation would have no effect on the collection. For
64 * example, invoking the <tt>sort</tt> method on an unmodifiable list that is
65 * already sorted may or may not throw <tt>UnsupportedOperationException</tt>.
66 *
67 * <p>This class is a member of the
68 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
69 * Java Collections Framework</a>.
70 *
71 * @author Josh Bloch
72 * @author Neal Gafter
73 * @see Collection
74 * @see Set
75 * @see List
76 * @see Map
77 * @since 1.2
78 */
79
80 public class Collections {
81 // Suppresses default constructor, ensuring non-instantiability.
82 private Collections() {
83 }
84
85 // Algorithms
178
179 /**
180 * Searches the specified list for the specified object using the binary
181 * search algorithm. The list must be sorted into ascending order
182 * according to the {@linkplain Comparable natural ordering} of its
183 * elements (as by the {@link #sort(List)} method) prior to making this
184 * call. If it is not sorted, the results are undefined. If the list
185 * contains multiple elements equal to the specified object, there is no
186 * guarantee which one will be found.
187 *
188 * <p>This method runs in log(n) time for a "random access" list (which
189 * provides near-constant-time positional access). If the specified list
190 * does not implement the {@link RandomAccess} interface and is large,
191 * this method will do an iterator-based binary search that performs
192 * O(n) link traversals and O(log n) element comparisons.
193 *
194 * @param <T> the class of the objects in the list
195 * @param list the list to be searched.
196 * @param key the key to be searched for.
197 * @return the index of the search key, if it is contained in the list;
198 * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
199 * <i>insertion point</i> is defined as the point at which the
200 * key would be inserted into the list: the index of the first
201 * element greater than the key, or <tt>list.size()</tt> if all
202 * elements in the list are less than the specified key. Note
203 * that this guarantees that the return value will be >= 0 if
204 * and only if the key is found.
205 * @throws ClassCastException if the list contains elements that are not
206 * <i>mutually comparable</i> (for example, strings and
207 * integers), or the search key is not mutually comparable
208 * with the elements of the list.
209 */
210 public static <T>
211 int binarySearch(List<? extends Comparable<? super T>> list, T key) {
212 if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
213 return Collections.indexedBinarySearch(list, key);
214 else
215 return Collections.iteratorBinarySearch(list, key);
216 }
217
218 private static <T>
219 int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key) {
220 int low = 0;
221 int high = list.size()-1;
279 /**
280 * Searches the specified list for the specified object using the binary
281 * search algorithm. The list must be sorted into ascending order
282 * according to the specified comparator (as by the
283 * {@link #sort(List, Comparator) sort(List, Comparator)}
284 * method), prior to making this call. If it is
285 * not sorted, the results are undefined. If the list contains multiple
286 * elements equal to the specified object, there is no guarantee which one
287 * will be found.
288 *
289 * <p>This method runs in log(n) time for a "random access" list (which
290 * provides near-constant-time positional access). If the specified list
291 * does not implement the {@link RandomAccess} interface and is large,
292 * this method will do an iterator-based binary search that performs
293 * O(n) link traversals and O(log n) element comparisons.
294 *
295 * @param <T> the class of the objects in the list
296 * @param list the list to be searched.
297 * @param key the key to be searched for.
298 * @param c the comparator by which the list is ordered.
299 * A <tt>null</tt> value indicates that the elements'
300 * {@linkplain Comparable natural ordering} should be used.
301 * @return the index of the search key, if it is contained in the list;
302 * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
303 * <i>insertion point</i> is defined as the point at which the
304 * key would be inserted into the list: the index of the first
305 * element greater than the key, or <tt>list.size()</tt> if all
306 * elements in the list are less than the specified key. Note
307 * that this guarantees that the return value will be >= 0 if
308 * and only if the key is found.
309 * @throws ClassCastException if the list contains elements that are not
310 * <i>mutually comparable</i> using the specified comparator,
311 * or the search key is not mutually comparable with the
312 * elements of the list using this comparator.
313 */
314 @SuppressWarnings("unchecked")
315 public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) {
316 if (c==null)
317 return binarySearch((List<? extends Comparable<? super T>>) list, key);
318
319 if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
320 return Collections.indexedBinarySearch(list, key, c);
321 else
322 return Collections.iteratorBinarySearch(list, key, c);
323 }
324
325 private static <T> int indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {
351 T midVal = get(i, mid);
352 int cmp = c.compare(midVal, key);
353
354 if (cmp < 0)
355 low = mid + 1;
356 else if (cmp > 0)
357 high = mid - 1;
358 else
359 return mid; // key found
360 }
361 return -(low + 1); // key not found
362 }
363
364 /**
365 * Reverses the order of the elements in the specified list.<p>
366 *
367 * This method runs in linear time.
368 *
369 * @param list the list whose elements are to be reversed.
370 * @throws UnsupportedOperationException if the specified list or
371 * its list-iterator does not support the <tt>set</tt> operation.
372 */
373 @SuppressWarnings({"rawtypes", "unchecked"})
374 public static void reverse(List<?> list) {
375 int size = list.size();
376 if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
377 for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
378 swap(list, i, j);
379 } else {
380 // instead of using a raw type here, it's possible to capture
381 // the wildcard but it will require a call to a supplementary
382 // private method
383 ListIterator fwd = list.listIterator();
384 ListIterator rev = list.listIterator(size);
385 for (int i=0, mid=list.size()>>1; i<mid; i++) {
386 Object tmp = fwd.next();
387 fwd.set(rev.previous());
388 rev.set(tmp);
389 }
390 }
391 }
399 * default source of randomness is only approximately an unbiased source
400 * of independently chosen bits. If it were a perfect source of randomly
401 * chosen bits, then the algorithm would choose permutations with perfect
402 * uniformity.
403 *
404 * <p>This implementation traverses the list backwards, from the last
405 * element up to the second, repeatedly swapping a randomly selected element
406 * into the "current position". Elements are randomly selected from the
407 * portion of the list that runs from the first element to the current
408 * position, inclusive.
409 *
410 * <p>This method runs in linear time. If the specified list does not
411 * implement the {@link RandomAccess} interface and is large, this
412 * implementation dumps the specified list into an array before shuffling
413 * it, and dumps the shuffled array back into the list. This avoids the
414 * quadratic behavior that would result from shuffling a "sequential
415 * access" list in place.
416 *
417 * @param list the list to be shuffled.
418 * @throws UnsupportedOperationException if the specified list or
419 * its list-iterator does not support the <tt>set</tt> operation.
420 */
421 public static void shuffle(List<?> list) {
422 Random rnd = r;
423 if (rnd == null)
424 r = rnd = new Random(); // harmless race.
425 shuffle(list, rnd);
426 }
427
428 private static Random r;
429
430 /**
431 * Randomly permute the specified list using the specified source of
432 * randomness. All permutations occur with equal likelihood
433 * assuming that the source of randomness is fair.<p>
434 *
435 * This implementation traverses the list backwards, from the last element
436 * up to the second, repeatedly swapping a randomly selected element into
437 * the "current position". Elements are randomly selected from the
438 * portion of the list that runs from the first element to the current
439 * position, inclusive.<p>
440 *
441 * This method runs in linear time. If the specified list does not
442 * implement the {@link RandomAccess} interface and is large, this
443 * implementation dumps the specified list into an array before shuffling
444 * it, and dumps the shuffled array back into the list. This avoids the
445 * quadratic behavior that would result from shuffling a "sequential
446 * access" list in place.
447 *
448 * @param list the list to be shuffled.
449 * @param rnd the source of randomness to use to shuffle the list.
450 * @throws UnsupportedOperationException if the specified list or its
451 * list-iterator does not support the <tt>set</tt> operation.
452 */
453 @SuppressWarnings({"rawtypes", "unchecked"})
454 public static void shuffle(List<?> list, Random rnd) {
455 int size = list.size();
456 if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
457 for (int i=size; i>1; i--)
458 swap(list, i-1, rnd.nextInt(i));
459 } else {
460 Object arr[] = list.toArray();
461
462 // Shuffle array
463 for (int i=size; i>1; i--)
464 swap(arr, i-1, rnd.nextInt(i));
465
466 // Dump array back into list
467 // instead of using a raw type here, it's possible to capture
468 // the wildcard but it will require a call to a supplementary
469 // private method
470 ListIterator it = list.listIterator();
471 for (Object e : arr) {
472 it.next();
473 it.set(e);
474 }
475 }
476 }
477
478 /**
479 * Swaps the elements at the specified positions in the specified list.
480 * (If the specified positions are equal, invoking this method leaves
481 * the list unchanged.)
482 *
483 * @param list The list in which to swap elements.
484 * @param i the index of one element to be swapped.
485 * @param j the index of the other element to be swapped.
486 * @throws IndexOutOfBoundsException if either <tt>i</tt> or <tt>j</tt>
487 * is out of range (i < 0 || i >= list.size()
488 * || j < 0 || j >= list.size()).
489 * @since 1.4
490 */
491 @SuppressWarnings({"rawtypes", "unchecked"})
492 public static void swap(List<?> list, int i, int j) {
493 // instead of using a raw type here, it's possible to capture
494 // the wildcard but it will require a call to a supplementary
495 // private method
496 final List l = list;
497 l.set(i, l.set(j, l.get(i)));
498 }
499
500 /**
501 * Swaps the two specified elements in the specified array.
502 */
503 private static void swap(Object[] arr, int i, int j) {
504 Object tmp = arr[i];
505 arr[i] = arr[j];
506 arr[j] = tmp;
507 }
508
509 /**
510 * Replaces all of the elements of the specified list with the specified
511 * element. <p>
512 *
513 * This method runs in linear time.
514 *
515 * @param <T> the class of the objects in the list
516 * @param list the list to be filled with the specified element.
517 * @param obj The element with which to fill the specified list.
518 * @throws UnsupportedOperationException if the specified list or its
519 * list-iterator does not support the <tt>set</tt> operation.
520 */
521 public static <T> void fill(List<? super T> list, T obj) {
522 int size = list.size();
523
524 if (size < FILL_THRESHOLD || list instanceof RandomAccess) {
525 for (int i=0; i<size; i++)
526 list.set(i, obj);
527 } else {
528 ListIterator<? super T> itr = list.listIterator();
529 for (int i=0; i<size; i++) {
530 itr.next();
531 itr.set(obj);
532 }
533 }
534 }
535
536 /**
537 * Copies all of the elements from one list into another. After the
538 * operation, the index of each copied element in the destination list
539 * will be identical to its index in the source list. The destination
540 * list must be at least as long as the source list. If it is longer, the
541 * remaining elements in the destination list are unaffected. <p>
542 *
543 * This method runs in linear time.
544 *
545 * @param <T> the class of the objects in the lists
546 * @param dest The destination list.
547 * @param src The source list.
548 * @throws IndexOutOfBoundsException if the destination list is too small
549 * to contain the entire source List.
550 * @throws UnsupportedOperationException if the destination list's
551 * list-iterator does not support the <tt>set</tt> operation.
552 */
553 public static <T> void copy(List<? super T> dest, List<? extends T> src) {
554 int srcSize = src.size();
555 if (srcSize > dest.size())
556 throw new IndexOutOfBoundsException("Source does not fit in dest");
557
558 if (srcSize < COPY_THRESHOLD ||
559 (src instanceof RandomAccess && dest instanceof RandomAccess)) {
560 for (int i=0; i<srcSize; i++)
561 dest.set(i, src.get(i));
562 } else {
563 ListIterator<? super T> di=dest.listIterator();
564 ListIterator<? extends T> si=src.listIterator();
565 for (int i=0; i<srcSize; i++) {
566 di.next();
567 di.set(si.next());
568 }
569 }
570 }
571
572 /**
573 * Returns the minimum element of the given collection, according to the
574 * <i>natural ordering</i> of its elements. All elements in the
575 * collection must implement the <tt>Comparable</tt> interface.
576 * Furthermore, all elements in the collection must be <i>mutually
577 * comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a
578 * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
579 * <tt>e2</tt> in the collection).<p>
580 *
581 * This method iterates over the entire collection, hence it requires
582 * time proportional to the size of the collection.
583 *
584 * @param <T> the class of the objects in the collection
585 * @param coll the collection whose minimum element is to be determined.
586 * @return the minimum element of the given collection, according
587 * to the <i>natural ordering</i> of its elements.
588 * @throws ClassCastException if the collection contains elements that are
589 * not <i>mutually comparable</i> (for example, strings and
590 * integers).
591 * @throws NoSuchElementException if the collection is empty.
592 * @see Comparable
593 */
594 public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
595 Iterator<? extends T> i = coll.iterator();
596 T candidate = i.next();
597
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 /**
607 * Returns the minimum element of the given collection, according to the
608 * order induced by the specified comparator. All elements in the
609 * collection must be <i>mutually comparable</i> by the specified
610 * comparator (that is, <tt>comp.compare(e1, e2)</tt> must not throw a
611 * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
612 * <tt>e2</tt> in the collection).<p>
613 *
614 * This method iterates over the entire collection, hence it requires
615 * time proportional to the size of the collection.
616 *
617 * @param <T> the class of the objects in the collection
618 * @param coll the collection whose minimum element is to be determined.
619 * @param comp the comparator with which to determine the minimum element.
620 * A <tt>null</tt> value indicates that the elements' <i>natural
621 * ordering</i> should be used.
622 * @return the minimum element of the given collection, according
623 * to the specified comparator.
624 * @throws ClassCastException if the collection contains elements that are
625 * not <i>mutually comparable</i> using the specified comparator.
626 * @throws NoSuchElementException if the collection is empty.
627 * @see Comparable
628 */
629 @SuppressWarnings({"unchecked", "rawtypes"})
630 public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {
631 if (comp==null)
632 return (T)min((Collection) coll);
633
634 Iterator<? extends T> i = coll.iterator();
635 T candidate = i.next();
636
637 while (i.hasNext()) {
638 T next = i.next();
639 if (comp.compare(next, candidate) < 0)
640 candidate = next;
641 }
642 return candidate;
643 }
644
645 /**
646 * Returns the maximum element of the given collection, according to the
647 * <i>natural ordering</i> of its elements. All elements in the
648 * collection must implement the <tt>Comparable</tt> interface.
649 * Furthermore, all elements in the collection must be <i>mutually
650 * comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a
651 * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
652 * <tt>e2</tt> in the collection).<p>
653 *
654 * This method iterates over the entire collection, hence it requires
655 * time proportional to the size of the collection.
656 *
657 * @param <T> the class of the objects in the collection
658 * @param coll the collection whose maximum element is to be determined.
659 * @return the maximum element of the given collection, according
660 * to the <i>natural ordering</i> of its elements.
661 * @throws ClassCastException if the collection contains elements that are
662 * not <i>mutually comparable</i> (for example, strings and
663 * integers).
664 * @throws NoSuchElementException if the collection is empty.
665 * @see Comparable
666 */
667 public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
668 Iterator<? extends T> i = coll.iterator();
669 T candidate = i.next();
670
671 while (i.hasNext()) {
672 T next = i.next();
673 if (next.compareTo(candidate) > 0)
674 candidate = next;
675 }
676 return candidate;
677 }
678
679 /**
680 * Returns the maximum element of the given collection, according to the
681 * order induced by the specified comparator. All elements in the
682 * collection must be <i>mutually comparable</i> by the specified
683 * comparator (that is, <tt>comp.compare(e1, e2)</tt> must not throw a
684 * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
685 * <tt>e2</tt> in the collection).<p>
686 *
687 * This method iterates over the entire collection, hence it requires
688 * time proportional to the size of the collection.
689 *
690 * @param <T> the class of the objects in the collection
691 * @param coll the collection whose maximum element is to be determined.
692 * @param comp the comparator with which to determine the maximum element.
693 * A <tt>null</tt> value indicates that the elements' <i>natural
694 * ordering</i> should be used.
695 * @return the maximum element of the given collection, according
696 * to the specified comparator.
697 * @throws ClassCastException if the collection contains elements that are
698 * not <i>mutually comparable</i> using the specified comparator.
699 * @throws NoSuchElementException if the collection is empty.
700 * @see Comparable
701 */
702 @SuppressWarnings({"unchecked", "rawtypes"})
703 public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {
704 if (comp==null)
705 return (T)max((Collection) coll);
706
707 Iterator<? extends T> i = coll.iterator();
708 T candidate = i.next();
709
710 while (i.hasNext()) {
711 T next = i.next();
712 if (comp.compare(next, candidate) > 0)
713 candidate = next;
714 }
715 return candidate;
716 }
717
718 /**
719 * Rotates the elements in the specified list by the specified distance.
720 * After calling this method, the element at index <tt>i</tt> will be
721 * the element previously at index <tt>(i - distance)</tt> mod
722 * <tt>list.size()</tt>, for all values of <tt>i</tt> between <tt>0</tt>
723 * and <tt>list.size()-1</tt>, inclusive. (This method has no effect on
724 * the size of the list.)
725 *
726 * <p>For example, suppose <tt>list</tt> comprises<tt> [t, a, n, k, s]</tt>.
727 * After invoking <tt>Collections.rotate(list, 1)</tt> (or
728 * <tt>Collections.rotate(list, -4)</tt>), <tt>list</tt> will comprise
729 * <tt>[s, t, a, n, k]</tt>.
730 *
731 * <p>Note that this method can usefully be applied to sublists to
732 * move one or more elements within a list while preserving the
733 * order of the remaining elements. For example, the following idiom
734 * moves the element at index <tt>j</tt> forward to position
735 * <tt>k</tt> (which must be greater than or equal to <tt>j</tt>):
736 * <pre>
737 * Collections.rotate(list.subList(j, k+1), -1);
738 * </pre>
739 * To make this concrete, suppose <tt>list</tt> comprises
740 * <tt>[a, b, c, d, e]</tt>. To move the element at index <tt>1</tt>
741 * (<tt>b</tt>) forward two positions, perform the following invocation:
742 * <pre>
743 * Collections.rotate(l.subList(1, 4), -1);
744 * </pre>
745 * The resulting list is <tt>[a, c, d, b, e]</tt>.
746 *
747 * <p>To move more than one element forward, increase the absolute value
748 * of the rotation distance. To move elements backward, use a positive
749 * shift distance.
750 *
751 * <p>If the specified list is small or implements the {@link
752 * RandomAccess} interface, this implementation exchanges the first
753 * element into the location it should go, and then repeatedly exchanges
754 * the displaced element into the location it should go until a displaced
755 * element is swapped into the first element. If necessary, the process
756 * is repeated on the second and successive elements, until the rotation
757 * is complete. If the specified list is large and doesn't implement the
758 * <tt>RandomAccess</tt> interface, this implementation breaks the
759 * list into two sublist views around index <tt>-distance mod size</tt>.
760 * Then the {@link #reverse(List)} method is invoked on each sublist view,
761 * and finally it is invoked on the entire list. For a more complete
762 * description of both algorithms, see Section 2.3 of Jon Bentley's
763 * <i>Programming Pearls</i> (Addison-Wesley, 1986).
764 *
765 * @param list the list to be rotated.
766 * @param distance the distance to rotate the list. There are no
767 * constraints on this value; it may be zero, negative, or
768 * greater than <tt>list.size()</tt>.
769 * @throws UnsupportedOperationException if the specified list or
770 * its list-iterator does not support the <tt>set</tt> operation.
771 * @since 1.4
772 */
773 public static void rotate(List<?> list, int distance) {
774 if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD)
775 rotate1(list, distance);
776 else
777 rotate2(list, distance);
778 }
779
780 private static <T> void rotate1(List<T> list, int distance) {
781 int size = list.size();
782 if (size == 0)
783 return;
784 distance = distance % size;
785 if (distance < 0)
786 distance += size;
787 if (distance == 0)
788 return;
789
790 for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) {
800 }
801 }
802
803 private static void rotate2(List<?> list, int distance) {
804 int size = list.size();
805 if (size == 0)
806 return;
807 int mid = -distance % size;
808 if (mid < 0)
809 mid += size;
810 if (mid == 0)
811 return;
812
813 reverse(list.subList(0, mid));
814 reverse(list.subList(mid, size));
815 reverse(list);
816 }
817
818 /**
819 * Replaces all occurrences of one specified value in a list with another.
820 * More formally, replaces with <tt>newVal</tt> each element <tt>e</tt>
821 * in <tt>list</tt> such that
822 * <tt>(oldVal==null ? e==null : oldVal.equals(e))</tt>.
823 * (This method has no effect on the size of the list.)
824 *
825 * @param <T> the class of the objects in the list
826 * @param list the list in which replacement is to occur.
827 * @param oldVal the old value to be replaced.
828 * @param newVal the new value with which <tt>oldVal</tt> is to be
829 * replaced.
830 * @return <tt>true</tt> if <tt>list</tt> contained one or more elements
831 * <tt>e</tt> such that
832 * <tt>(oldVal==null ? e==null : oldVal.equals(e))</tt>.
833 * @throws UnsupportedOperationException if the specified list or
834 * its list-iterator does not support the <tt>set</tt> operation.
835 * @since 1.4
836 */
837 public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) {
838 boolean result = false;
839 int size = list.size();
840 if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) {
841 if (oldVal==null) {
842 for (int i=0; i<size; i++) {
843 if (list.get(i)==null) {
844 list.set(i, newVal);
845 result = true;
846 }
847 }
848 } else {
849 for (int i=0; i<size; i++) {
850 if (oldVal.equals(list.get(i))) {
851 list.set(i, newVal);
852 result = true;
853 }
854 }
860 if (itr.next()==null) {
861 itr.set(newVal);
862 result = true;
863 }
864 }
865 } else {
866 for (int i=0; i<size; i++) {
867 if (oldVal.equals(itr.next())) {
868 itr.set(newVal);
869 result = true;
870 }
871 }
872 }
873 }
874 return result;
875 }
876
877 /**
878 * Returns the starting position of the first occurrence of the specified
879 * target list within the specified source list, or -1 if there is no
880 * such occurrence. More formally, returns the lowest index <tt>i</tt>
881 * such that {@code source.subList(i, i+target.size()).equals(target)},
882 * or -1 if there is no such index. (Returns -1 if
883 * {@code target.size() > source.size()})
884 *
885 * <p>This implementation uses the "brute force" technique of scanning
886 * over the source list, looking for a match with the target at each
887 * location in turn.
888 *
889 * @param source the list in which to search for the first occurrence
890 * of <tt>target</tt>.
891 * @param target the list to search for as a subList of <tt>source</tt>.
892 * @return the starting position of the first occurrence of the specified
893 * target list within the specified source list, or -1 if there
894 * is no such occurrence.
895 * @since 1.4
896 */
897 public static int indexOfSubList(List<?> source, List<?> target) {
898 int sourceSize = source.size();
899 int targetSize = target.size();
900 int maxCandidate = sourceSize - targetSize;
901
902 if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
903 (source instanceof RandomAccess&&target instanceof RandomAccess)) {
904 nextCand:
905 for (int candidate = 0; candidate <= maxCandidate; candidate++) {
906 for (int i=0, j=candidate; i<targetSize; i++, j++)
907 if (!eq(target.get(i), source.get(j)))
908 continue nextCand; // Element mismatch, try next cand
909 return candidate; // All elements of candidate matched target
910 }
911 } else { // Iterator version of above algorithm
913 nextCand:
914 for (int candidate = 0; candidate <= maxCandidate; candidate++) {
915 ListIterator<?> ti = target.listIterator();
916 for (int i=0; i<targetSize; i++) {
917 if (!eq(ti.next(), si.next())) {
918 // Back up source iterator to next candidate
919 for (int j=0; j<i; j++)
920 si.previous();
921 continue nextCand;
922 }
923 }
924 return candidate;
925 }
926 }
927 return -1; // No candidate matched the target
928 }
929
930 /**
931 * Returns the starting position of the last occurrence of the specified
932 * target list within the specified source list, or -1 if there is no such
933 * occurrence. More formally, returns the highest index <tt>i</tt>
934 * such that {@code source.subList(i, i+target.size()).equals(target)},
935 * or -1 if there is no such index. (Returns -1 if
936 * {@code target.size() > source.size()})
937 *
938 * <p>This implementation uses the "brute force" technique of iterating
939 * over the source list, looking for a match with the target at each
940 * location in turn.
941 *
942 * @param source the list in which to search for the last occurrence
943 * of <tt>target</tt>.
944 * @param target the list to search for as a subList of <tt>source</tt>.
945 * @return the starting position of the last occurrence of the specified
946 * target list within the specified source list, or -1 if there
947 * is no such occurrence.
948 * @since 1.4
949 */
950 public static int lastIndexOfSubList(List<?> source, List<?> target) {
951 int sourceSize = source.size();
952 int targetSize = target.size();
953 int maxCandidate = sourceSize - targetSize;
954
955 if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
956 source instanceof RandomAccess) { // Index access version
957 nextCand:
958 for (int candidate = maxCandidate; candidate >= 0; candidate--) {
959 for (int i=0, j=candidate; i<targetSize; i++, j++)
960 if (!eq(target.get(i), source.get(j)))
961 continue nextCand; // Element mismatch, try next cand
962 return candidate; // All elements of candidate matched target
963 }
964 } else { // Iterator version of above algorithm
976 si.previous();
977 }
978 continue nextCand;
979 }
980 }
981 return candidate;
982 }
983 }
984 return -1; // No candidate matched the target
985 }
986
987
988 // Unmodifiable Wrappers
989
990 /**
991 * Returns an unmodifiable view of the specified collection. This method
992 * allows modules to provide users with "read-only" access to internal
993 * collections. Query operations on the returned collection "read through"
994 * to the specified collection, and attempts to modify the returned
995 * collection, whether direct or via its iterator, result in an
996 * <tt>UnsupportedOperationException</tt>.<p>
997 *
998 * The returned collection does <i>not</i> pass the hashCode and equals
999 * operations through to the backing collection, but relies on
1000 * <tt>Object</tt>'s <tt>equals</tt> and <tt>hashCode</tt> methods. This
1001 * is necessary to preserve the contracts of these operations in the case
1002 * that the backing collection is a set or a list.<p>
1003 *
1004 * The returned collection will be serializable if the specified collection
1005 * is serializable.
1006 *
1007 * @param <T> the class of the objects in the collection
1008 * @param c the collection for which an unmodifiable view is to be
1009 * returned.
1010 * @return an unmodifiable view of the specified collection.
1011 */
1012 public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
1013 return new UnmodifiableCollection<>(c);
1014 }
1015
1016 /**
1017 * @serial include
1018 */
1019 static class UnmodifiableCollection<E> implements Collection<E>, Serializable {
1020 private static final long serialVersionUID = 1820017752578914078L;
1088 public Spliterator<E> spliterator() {
1089 return (Spliterator<E>)c.spliterator();
1090 }
1091 @SuppressWarnings("unchecked")
1092 @Override
1093 public Stream<E> stream() {
1094 return (Stream<E>)c.stream();
1095 }
1096 @SuppressWarnings("unchecked")
1097 @Override
1098 public Stream<E> parallelStream() {
1099 return (Stream<E>)c.parallelStream();
1100 }
1101 }
1102
1103 /**
1104 * Returns an unmodifiable view of the specified set. This method allows
1105 * modules to provide users with "read-only" access to internal sets.
1106 * Query operations on the returned set "read through" to the specified
1107 * set, and attempts to modify the returned set, whether direct or via its
1108 * iterator, result in an <tt>UnsupportedOperationException</tt>.<p>
1109 *
1110 * The returned set will be serializable if the specified set
1111 * is serializable.
1112 *
1113 * @param <T> the class of the objects in the set
1114 * @param s the set for which an unmodifiable view is to be returned.
1115 * @return an unmodifiable view of the specified set.
1116 */
1117 public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
1118 return new UnmodifiableSet<>(s);
1119 }
1120
1121 /**
1122 * @serial include
1123 */
1124 static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
1125 implements Set<E>, Serializable {
1126 private static final long serialVersionUID = -9215047833775013803L;
1127
1128 UnmodifiableSet(Set<? extends E> s) {super(s);}
1129 public boolean equals(Object o) {return o == this || c.equals(o);}
1130 public int hashCode() {return c.hashCode();}
1131 }
1132
1133 /**
1134 * Returns an unmodifiable view of the specified sorted set. This method
1135 * allows modules to provide users with "read-only" access to internal
1136 * sorted sets. Query operations on the returned sorted set "read
1137 * through" to the specified sorted set. Attempts to modify the returned
1138 * sorted set, whether direct, via its iterator, or via its
1139 * <tt>subSet</tt>, <tt>headSet</tt>, or <tt>tailSet</tt> views, result in
1140 * an <tt>UnsupportedOperationException</tt>.<p>
1141 *
1142 * The returned sorted set will be serializable if the specified sorted set
1143 * is serializable.
1144 *
1145 * @param <T> the class of the objects in the set
1146 * @param s the sorted set for which an unmodifiable view is to be
1147 * returned.
1148 * @return an unmodifiable view of the specified sorted set.
1149 */
1150 public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
1151 return new UnmodifiableSortedSet<>(s);
1152 }
1153
1154 /**
1155 * @serial include
1156 */
1157 static class UnmodifiableSortedSet<E>
1158 extends UnmodifiableSet<E>
1159 implements SortedSet<E>, Serializable {
1160 private static final long serialVersionUID = -4929149591599911165L;
1256 ns.subSet(fromElement, fromInclusive, toElement, toInclusive));
1257 }
1258
1259 public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1260 return new UnmodifiableNavigableSet<>(
1261 ns.headSet(toElement, inclusive));
1262 }
1263
1264 public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1265 return new UnmodifiableNavigableSet<>(
1266 ns.tailSet(fromElement, inclusive));
1267 }
1268 }
1269
1270 /**
1271 * Returns an unmodifiable view of the specified list. This method allows
1272 * modules to provide users with "read-only" access to internal
1273 * lists. Query operations on the returned list "read through" to the
1274 * specified list, and attempts to modify the returned list, whether
1275 * direct or via its iterator, result in an
1276 * <tt>UnsupportedOperationException</tt>.<p>
1277 *
1278 * The returned list will be serializable if the specified list
1279 * is serializable. Similarly, the returned list will implement
1280 * {@link RandomAccess} if the specified list does.
1281 *
1282 * @param <T> the class of the objects in the list
1283 * @param list the list for which an unmodifiable view is to be returned.
1284 * @return an unmodifiable view of the specified list.
1285 */
1286 public static <T> List<T> unmodifiableList(List<? extends T> list) {
1287 return (list instanceof RandomAccess ?
1288 new UnmodifiableRandomAccessList<>(list) :
1289 new UnmodifiableList<>(list));
1290 }
1291
1292 /**
1293 * @serial include
1294 */
1295 static class UnmodifiableList<E> extends UnmodifiableCollection<E>
1296 implements List<E> {
1402
1403 private static final long serialVersionUID = -2542308836966382001L;
1404
1405 /**
1406 * Allows instances to be deserialized in pre-1.4 JREs (which do
1407 * not have UnmodifiableRandomAccessList). UnmodifiableList has
1408 * a readResolve method that inverts this transformation upon
1409 * deserialization.
1410 */
1411 private Object writeReplace() {
1412 return new UnmodifiableList<>(list);
1413 }
1414 }
1415
1416 /**
1417 * Returns an unmodifiable view of the specified map. This method
1418 * allows modules to provide users with "read-only" access to internal
1419 * maps. Query operations on the returned map "read through"
1420 * to the specified map, and attempts to modify the returned
1421 * map, whether direct or via its collection views, result in an
1422 * <tt>UnsupportedOperationException</tt>.<p>
1423 *
1424 * The returned map will be serializable if the specified map
1425 * is serializable.
1426 *
1427 * @param <K> the class of the map keys
1428 * @param <V> the class of the map values
1429 * @param m the map for which an unmodifiable view is to be returned.
1430 * @return an unmodifiable view of the specified map.
1431 */
1432 public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
1433 return new UnmodifiableMap<>(m);
1434 }
1435
1436 /**
1437 * @serial include
1438 */
1439 private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {
1440 private static final long serialVersionUID = -1034234728574286014L;
1441
1442 private final Map<? extends K, ? extends V> m;
1752 public boolean equals(Object o) {
1753 if (this == o)
1754 return true;
1755 if (!(o instanceof Map.Entry))
1756 return false;
1757 Map.Entry<?,?> t = (Map.Entry<?,?>)o;
1758 return eq(e.getKey(), t.getKey()) &&
1759 eq(e.getValue(), t.getValue());
1760 }
1761 public String toString() {return e.toString();}
1762 }
1763 }
1764 }
1765
1766 /**
1767 * Returns an unmodifiable view of the specified sorted map. This method
1768 * allows modules to provide users with "read-only" access to internal
1769 * sorted maps. Query operations on the returned sorted map "read through"
1770 * to the specified sorted map. Attempts to modify the returned
1771 * sorted map, whether direct, via its collection views, or via its
1772 * <tt>subMap</tt>, <tt>headMap</tt>, or <tt>tailMap</tt> views, result in
1773 * an <tt>UnsupportedOperationException</tt>.<p>
1774 *
1775 * The returned sorted map will be serializable if the specified sorted map
1776 * is serializable.
1777 *
1778 * @param <K> the class of the map keys
1779 * @param <V> the class of the map values
1780 * @param m the sorted map for which an unmodifiable view is to be
1781 * returned.
1782 * @return an unmodifiable view of the specified sorted map.
1783 */
1784 public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {
1785 return new UnmodifiableSortedMap<>(m);
1786 }
1787
1788 /**
1789 * @serial include
1790 */
1791 static class UnmodifiableSortedMap<K,V>
1792 extends UnmodifiableMap<K,V>
1793 implements SortedMap<K,V>, Serializable {
2131 super(s, mutex);
2132 }
2133
2134 public boolean equals(Object o) {
2135 if (this == o)
2136 return true;
2137 synchronized (mutex) {return c.equals(o);}
2138 }
2139 public int hashCode() {
2140 synchronized (mutex) {return c.hashCode();}
2141 }
2142 }
2143
2144 /**
2145 * Returns a synchronized (thread-safe) sorted set backed by the specified
2146 * sorted set. In order to guarantee serial access, it is critical that
2147 * <strong>all</strong> access to the backing sorted set is accomplished
2148 * through the returned sorted set (or its views).<p>
2149 *
2150 * It is imperative that the user manually synchronize on the returned
2151 * sorted set when iterating over it or any of its <tt>subSet</tt>,
2152 * <tt>headSet</tt>, or <tt>tailSet</tt> views.
2153 * <pre>
2154 * SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
2155 * ...
2156 * synchronized (s) {
2157 * Iterator i = s.iterator(); // Must be in the synchronized block
2158 * while (i.hasNext())
2159 * foo(i.next());
2160 * }
2161 * </pre>
2162 * or:
2163 * <pre>
2164 * SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
2165 * SortedSet s2 = s.headSet(foo);
2166 * ...
2167 * synchronized (s) { // Note: s, not s2!!!
2168 * Iterator i = s2.iterator(); // Must be in the synchronized block
2169 * while (i.hasNext())
2170 * foo(i.next());
2171 * }
2172 * </pre>
2683 }
2684 @Override
2685 public V merge(K key, V value,
2686 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2687 synchronized (mutex) {return m.merge(key, value, remappingFunction);}
2688 }
2689
2690 private void writeObject(ObjectOutputStream s) throws IOException {
2691 synchronized (mutex) {s.defaultWriteObject();}
2692 }
2693 }
2694
2695 /**
2696 * Returns a synchronized (thread-safe) sorted map backed by the specified
2697 * sorted map. In order to guarantee serial access, it is critical that
2698 * <strong>all</strong> access to the backing sorted map is accomplished
2699 * through the returned sorted map (or its views).<p>
2700 *
2701 * It is imperative that the user manually synchronize on the returned
2702 * sorted map when iterating over any of its collection views, or the
2703 * collections views of any of its <tt>subMap</tt>, <tt>headMap</tt> or
2704 * <tt>tailMap</tt> views.
2705 * <pre>
2706 * SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2707 * ...
2708 * Set s = m.keySet(); // Needn't be in synchronized block
2709 * ...
2710 * synchronized (m) { // Synchronizing on m, not s!
2711 * Iterator i = s.iterator(); // Must be in synchronized block
2712 * while (i.hasNext())
2713 * foo(i.next());
2714 * }
2715 * </pre>
2716 * or:
2717 * <pre>
2718 * SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2719 * SortedMap m2 = m.subMap(foo, bar);
2720 * ...
2721 * Set s2 = m2.keySet(); // Needn't be in synchronized block
2722 * ...
2723 * synchronized (m) { // Synchronizing on m, not m2 or s2!
2724 * Iterator i = s.iterator(); // Must be in synchronized block
4389 return (NavigableSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET;
4390 }
4391
4392 /**
4393 * The empty list (immutable). This list is serializable.
4394 *
4395 * @see #emptyList()
4396 */
4397 @SuppressWarnings("rawtypes")
4398 public static final List EMPTY_LIST = new EmptyList<>();
4399
4400 /**
4401 * Returns an empty list (immutable). This list is serializable.
4402 *
4403 * <p>This example illustrates the type-safe way to obtain an empty list:
4404 * <pre>
4405 * List<String> s = Collections.emptyList();
4406 * </pre>
4407 *
4408 * @implNote
4409 * Implementations of this method need not create a separate <tt>List</tt>
4410 * object for each call. Using this method is likely to have comparable
4411 * cost to using the like-named field. (Unlike this method, the field does
4412 * not provide type safety.)
4413 *
4414 * @param <T> type of elements, if there were any, in the list
4415 * @return an empty immutable list
4416 *
4417 * @see #EMPTY_LIST
4418 * @since 1.5
4419 */
4420 @SuppressWarnings("unchecked")
4421 public static final <T> List<T> emptyList() {
4422 return (List<T>) EMPTY_LIST;
4423 }
4424
4425 /**
4426 * @serial include
4427 */
4428 private static class EmptyList<E>
4429 extends AbstractList<E>
4829 @Override
4830 public void replaceAll(UnaryOperator<E> operator) {
4831 throw new UnsupportedOperationException();
4832 }
4833 @Override
4834 public void sort(Comparator<? super E> c) {
4835 }
4836 @Override
4837 public Spliterator<E> spliterator() {
4838 return singletonSpliterator(element);
4839 }
4840 }
4841
4842 /**
4843 * Returns an immutable map, mapping only the specified key to the
4844 * specified value. The returned map is serializable.
4845 *
4846 * @param <K> the class of the map keys
4847 * @param <V> the class of the map values
4848 * @param key the sole key to be stored in the returned map.
4849 * @param value the value to which the returned map maps <tt>key</tt>.
4850 * @return an immutable map containing only the specified key-value
4851 * mapping.
4852 * @since 1.3
4853 */
4854 public static <K,V> Map<K,V> singletonMap(K key, V value) {
4855 return new SingletonMap<>(key, value);
4856 }
4857
4858 /**
4859 * @serial include
4860 */
4861 private static class SingletonMap<K,V>
4862 extends AbstractMap<K,V>
4863 implements Serializable {
4864 private static final long serialVersionUID = -6979724477215052911L;
4865
4866 private final K k;
4867 private final V v;
4868
4869 SingletonMap(K key, V value) {
4947 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
4948 throw new UnsupportedOperationException();
4949 }
4950
4951 @Override
4952 public V compute(K key,
4953 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
4954 throw new UnsupportedOperationException();
4955 }
4956
4957 @Override
4958 public V merge(K key, V value,
4959 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
4960 throw new UnsupportedOperationException();
4961 }
4962 }
4963
4964 // Miscellaneous
4965
4966 /**
4967 * Returns an immutable list consisting of <tt>n</tt> copies of the
4968 * specified object. The newly allocated data object is tiny (it contains
4969 * a single reference to the data object). This method is useful in
4970 * combination with the <tt>List.addAll</tt> method to grow lists.
4971 * The returned list is serializable.
4972 *
4973 * @param <T> the class of the object to copy and of the objects
4974 * in the returned list.
4975 * @param n the number of elements in the returned list.
4976 * @param o the element to appear repeatedly in the returned list.
4977 * @return an immutable list consisting of <tt>n</tt> copies of the
4978 * specified object.
4979 * @throws IllegalArgumentException if {@code n < 0}
4980 * @see List#addAll(Collection)
4981 * @see List#addAll(int, Collection)
4982 */
4983 public static <T> List<T> nCopies(int n, T o) {
4984 if (n < 0)
4985 throw new IllegalArgumentException("List length = " + n);
4986 return new CopiesList<>(n, o);
4987 }
4988
4989 /**
4990 * @serial include
4991 */
4992 private static class CopiesList<E>
4993 extends AbstractList<E>
4994 implements RandomAccess, Serializable
4995 {
4996 private static final long serialVersionUID = 2739099268398711800L;
4997
5078 }
5079 }
5080
5081 /**
5082 * Returns a comparator that imposes the reverse of the <em>natural
5083 * ordering</em> on a collection of objects that implement the
5084 * {@code Comparable} interface. (The natural ordering is the ordering
5085 * imposed by the objects' own {@code compareTo} method.) This enables a
5086 * simple idiom for sorting (or maintaining) collections (or arrays) of
5087 * objects that implement the {@code Comparable} interface in
5088 * reverse-natural-order. For example, suppose {@code a} is an array of
5089 * strings. Then: <pre>
5090 * Arrays.sort(a, Collections.reverseOrder());
5091 * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>
5092 *
5093 * The returned comparator is serializable.
5094 *
5095 * @param <T> the class of the objects compared by the comparator
5096 * @return A comparator that imposes the reverse of the <i>natural
5097 * ordering</i> on a collection of objects that implement
5098 * the <tt>Comparable</tt> interface.
5099 * @see Comparable
5100 */
5101 @SuppressWarnings("unchecked")
5102 public static <T> Comparator<T> reverseOrder() {
5103 return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
5104 }
5105
5106 /**
5107 * @serial include
5108 */
5109 private static class ReverseComparator
5110 implements Comparator<Comparable<Object>>, Serializable {
5111
5112 private static final long serialVersionUID = 7207038068494060240L;
5113
5114 static final ReverseComparator REVERSE_ORDER
5115 = new ReverseComparator();
5116
5117 public int compare(Comparable<Object> c1, Comparable<Object> c2) {
5118 return c2.compareTo(c1);
5242 */
5243 public static <T> ArrayList<T> list(Enumeration<T> e) {
5244 ArrayList<T> l = new ArrayList<>();
5245 while (e.hasMoreElements())
5246 l.add(e.nextElement());
5247 return l;
5248 }
5249
5250 /**
5251 * Returns true if the specified arguments are equal, or both null.
5252 *
5253 * NB: Do not replace with Object.equals until JDK-8015417 is resolved.
5254 */
5255 static boolean eq(Object o1, Object o2) {
5256 return o1==null ? o2==null : o1.equals(o2);
5257 }
5258
5259 /**
5260 * Returns the number of elements in the specified collection equal to the
5261 * specified object. More formally, returns the number of elements
5262 * <tt>e</tt> in the collection such that
5263 * <tt>(o == null ? e == null : o.equals(e))</tt>.
5264 *
5265 * @param c the collection in which to determine the frequency
5266 * of <tt>o</tt>
5267 * @param o the object whose frequency is to be determined
5268 * @return the number of elements in {@code c} equal to {@code o}
5269 * @throws NullPointerException if <tt>c</tt> is null
5270 * @since 1.5
5271 */
5272 public static int frequency(Collection<?> c, Object o) {
5273 int result = 0;
5274 if (o == null) {
5275 for (Object e : c)
5276 if (e == null)
5277 result++;
5278 } else {
5279 for (Object e : c)
5280 if (o.equals(e))
5281 result++;
5282 }
5283 return result;
5284 }
5285
5286 /**
5287 * Returns {@code true} if the two specified collections have no
5288 * elements in common.
5289 *
5360 iterate = c2;
5361 contains = c1;
5362 }
5363 }
5364
5365 for (Object e : iterate) {
5366 if (contains.contains(e)) {
5367 // Found a common element. Collections are not disjoint.
5368 return false;
5369 }
5370 }
5371
5372 // No common elements were found.
5373 return true;
5374 }
5375
5376 /**
5377 * Adds all of the specified elements to the specified collection.
5378 * Elements to be added may be specified individually or as an array.
5379 * The behavior of this convenience method is identical to that of
5380 * <tt>c.addAll(Arrays.asList(elements))</tt>, but this method is likely
5381 * to run significantly faster under most implementations.
5382 *
5383 * <p>When elements are specified individually, this method provides a
5384 * convenient way to add a few elements to an existing collection:
5385 * <pre>
5386 * Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");
5387 * </pre>
5388 *
5389 * @param <T> the class of the elements to add and of the collection
5390 * @param c the collection into which <tt>elements</tt> are to be inserted
5391 * @param elements the elements to insert into <tt>c</tt>
5392 * @return <tt>true</tt> if the collection changed as a result of the call
5393 * @throws UnsupportedOperationException if <tt>c</tt> does not support
5394 * the <tt>add</tt> operation
5395 * @throws NullPointerException if <tt>elements</tt> contains one or more
5396 * null values and <tt>c</tt> does not permit null elements, or
5397 * if <tt>c</tt> or <tt>elements</tt> are <tt>null</tt>
5398 * @throws IllegalArgumentException if some property of a value in
5399 * <tt>elements</tt> prevents it from being added to <tt>c</tt>
5400 * @see Collection#addAll(Collection)
5401 * @since 1.5
5402 */
5403 @SafeVarargs
5404 public static <T> boolean addAll(Collection<? super T> c, T... elements) {
5405 boolean result = false;
5406 for (T element : elements)
5407 result |= c.add(element);
5408 return result;
5409 }
5410
5411 /**
5412 * Returns a set backed by the specified map. The resulting set displays
5413 * the same ordering, concurrency, and performance characteristics as the
5414 * backing map. In essence, this factory method provides a {@link Set}
5415 * implementation corresponding to any {@link Map} implementation. There
5416 * is no need to use this method on a {@link Map} implementation that
5417 * already has a corresponding {@link Set} implementation (such as {@link
5418 * HashMap} or {@link TreeMap}).
5419 *
5420 * <p>Each method invocation on the set returned by this method results in
5421 * exactly one method invocation on the backing map or its <tt>keySet</tt>
5422 * view, with one exception. The <tt>addAll</tt> method is implemented
5423 * as a sequence of <tt>put</tt> invocations on the backing map.
5424 *
5425 * <p>The specified map must be empty at the time this method is invoked,
5426 * and should not be accessed directly after this method returns. These
5427 * conditions are ensured if the map is created empty, passed directly
5428 * to this method, and no reference to the map is retained, as illustrated
5429 * in the following code fragment:
5430 * <pre>
5431 * Set<Object> weakHashSet = Collections.newSetFromMap(
5432 * new WeakHashMap<Object, Boolean>());
5433 * </pre>
5434 *
5435 * @param <E> the class of the map keys and of the objects in the
5436 * returned set
5437 * @param map the backing map
5438 * @return the set backed by the map
5439 * @throws IllegalArgumentException if <tt>map</tt> is not empty
5440 * @since 1.6
5441 */
5442 public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
5443 return new SetFromMap<>(map);
5444 }
5445
5446 /**
5447 * @serial include
5448 */
5449 private static class SetFromMap<E> extends AbstractSet<E>
5450 implements Set<E>, Serializable
5451 {
5452 private final Map<E, Boolean> m; // The backing map
5453 private transient Set<E> s; // Its keySet
5454
5455 SetFromMap(Map<E, Boolean> map) {
5456 if (!map.isEmpty())
5457 throw new IllegalArgumentException("Map is non-empty");
5458 m = map;
5459 s = map.keySet();
5488
5489 @Override
5490 public Spliterator<E> spliterator() {return s.spliterator();}
5491 @Override
5492 public Stream<E> stream() {return s.stream();}
5493 @Override
5494 public Stream<E> parallelStream() {return s.parallelStream();}
5495
5496 private static final long serialVersionUID = 2454657854757543876L;
5497
5498 private void readObject(java.io.ObjectInputStream stream)
5499 throws IOException, ClassNotFoundException
5500 {
5501 stream.defaultReadObject();
5502 s = m.keySet();
5503 }
5504 }
5505
5506 /**
5507 * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)
5508 * {@link Queue}. Method <tt>add</tt> is mapped to <tt>push</tt>,
5509 * <tt>remove</tt> is mapped to <tt>pop</tt> and so on. This
5510 * view can be useful when you would like to use a method
5511 * requiring a <tt>Queue</tt> but you need Lifo ordering.
5512 *
5513 * <p>Each method invocation on the queue returned by this method
5514 * results in exactly one method invocation on the backing deque, with
5515 * one exception. The {@link Queue#addAll addAll} method is
5516 * implemented as a sequence of {@link Deque#addFirst addFirst}
5517 * invocations on the backing deque.
5518 *
5519 * @param <T> the class of the objects in the deque
5520 * @param deque the deque
5521 * @return the queue
5522 * @since 1.6
5523 */
5524 public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
5525 return new AsLIFOQueue<>(deque);
5526 }
5527
5528 /**
5529 * @serial include
5530 */
5531 static class AsLIFOQueue<E> extends AbstractQueue<E>
|
27 import java.io.Serializable;
28 import java.io.ObjectOutputStream;
29 import java.io.IOException;
30 import java.lang.reflect.Array;
31 import java.util.function.BiConsumer;
32 import java.util.function.BiFunction;
33 import java.util.function.Consumer;
34 import java.util.function.Function;
35 import java.util.function.Predicate;
36 import java.util.function.UnaryOperator;
37 import java.util.stream.IntStream;
38 import java.util.stream.Stream;
39 import java.util.stream.StreamSupport;
40
41 /**
42 * This class consists exclusively of static methods that operate on or return
43 * collections. It contains polymorphic algorithms that operate on
44 * collections, "wrappers", which return a new collection backed by a
45 * specified collection, and a few other odds and ends.
46 *
47 * <p>The methods of this class all throw a {@code NullPointerException}
48 * if the collections or class objects provided to them are null.
49 *
50 * <p>The documentation for the polymorphic algorithms contained in this class
51 * generally includes a brief description of the <i>implementation</i>. Such
52 * descriptions should be regarded as <i>implementation notes</i>, rather than
53 * parts of the <i>specification</i>. Implementors should feel free to
54 * substitute other algorithms, so long as the specification itself is adhered
55 * to. (For example, the algorithm used by {@code sort} does not have to be
56 * a mergesort, but it does have to be <i>stable</i>.)
57 *
58 * <p>The "destructive" algorithms contained in this class, that is, the
59 * algorithms that modify the collection on which they operate, are specified
60 * to throw {@code UnsupportedOperationException} if the collection does not
61 * support the appropriate mutation primitive(s), such as the {@code set}
62 * method. These algorithms may, but are not required to, throw this
63 * exception if an invocation would have no effect on the collection. For
64 * example, invoking the {@code sort} method on an unmodifiable list that is
65 * already sorted may or may not throw {@code UnsupportedOperationException}.
66 *
67 * <p>This class is a member of the
68 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
69 * Java Collections Framework</a>.
70 *
71 * @author Josh Bloch
72 * @author Neal Gafter
73 * @see Collection
74 * @see Set
75 * @see List
76 * @see Map
77 * @since 1.2
78 */
79
80 public class Collections {
81 // Suppresses default constructor, ensuring non-instantiability.
82 private Collections() {
83 }
84
85 // Algorithms
178
179 /**
180 * Searches the specified list for the specified object using the binary
181 * search algorithm. The list must be sorted into ascending order
182 * according to the {@linkplain Comparable natural ordering} of its
183 * elements (as by the {@link #sort(List)} method) prior to making this
184 * call. If it is not sorted, the results are undefined. If the list
185 * contains multiple elements equal to the specified object, there is no
186 * guarantee which one will be found.
187 *
188 * <p>This method runs in log(n) time for a "random access" list (which
189 * provides near-constant-time positional access). If the specified list
190 * does not implement the {@link RandomAccess} interface and is large,
191 * this method will do an iterator-based binary search that performs
192 * O(n) link traversals and O(log n) element comparisons.
193 *
194 * @param <T> the class of the objects in the list
195 * @param list the list to be searched.
196 * @param key the key to be searched for.
197 * @return the index of the search key, if it is contained in the list;
198 * otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The
199 * <i>insertion point</i> is defined as the point at which the
200 * key would be inserted into the list: the index of the first
201 * element greater than the key, or {@code list.size()} if all
202 * elements in the list are less than the specified key. Note
203 * that this guarantees that the return value will be >= 0 if
204 * and only if the key is found.
205 * @throws ClassCastException if the list contains elements that are not
206 * <i>mutually comparable</i> (for example, strings and
207 * integers), or the search key is not mutually comparable
208 * with the elements of the list.
209 */
210 public static <T>
211 int binarySearch(List<? extends Comparable<? super T>> list, T key) {
212 if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
213 return Collections.indexedBinarySearch(list, key);
214 else
215 return Collections.iteratorBinarySearch(list, key);
216 }
217
218 private static <T>
219 int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key) {
220 int low = 0;
221 int high = list.size()-1;
279 /**
280 * Searches the specified list for the specified object using the binary
281 * search algorithm. The list must be sorted into ascending order
282 * according to the specified comparator (as by the
283 * {@link #sort(List, Comparator) sort(List, Comparator)}
284 * method), prior to making this call. If it is
285 * not sorted, the results are undefined. If the list contains multiple
286 * elements equal to the specified object, there is no guarantee which one
287 * will be found.
288 *
289 * <p>This method runs in log(n) time for a "random access" list (which
290 * provides near-constant-time positional access). If the specified list
291 * does not implement the {@link RandomAccess} interface and is large,
292 * this method will do an iterator-based binary search that performs
293 * O(n) link traversals and O(log n) element comparisons.
294 *
295 * @param <T> the class of the objects in the list
296 * @param list the list to be searched.
297 * @param key the key to be searched for.
298 * @param c the comparator by which the list is ordered.
299 * A {@code null} value indicates that the elements'
300 * {@linkplain Comparable natural ordering} should be used.
301 * @return the index of the search key, if it is contained in the list;
302 * otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The
303 * <i>insertion point</i> is defined as the point at which the
304 * key would be inserted into the list: the index of the first
305 * element greater than the key, or {@code list.size()} if all
306 * elements in the list are less than the specified key. Note
307 * that this guarantees that the return value will be >= 0 if
308 * and only if the key is found.
309 * @throws ClassCastException if the list contains elements that are not
310 * <i>mutually comparable</i> using the specified comparator,
311 * or the search key is not mutually comparable with the
312 * elements of the list using this comparator.
313 */
314 @SuppressWarnings("unchecked")
315 public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) {
316 if (c==null)
317 return binarySearch((List<? extends Comparable<? super T>>) list, key);
318
319 if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
320 return Collections.indexedBinarySearch(list, key, c);
321 else
322 return Collections.iteratorBinarySearch(list, key, c);
323 }
324
325 private static <T> int indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {
351 T midVal = get(i, mid);
352 int cmp = c.compare(midVal, key);
353
354 if (cmp < 0)
355 low = mid + 1;
356 else if (cmp > 0)
357 high = mid - 1;
358 else
359 return mid; // key found
360 }
361 return -(low + 1); // key not found
362 }
363
364 /**
365 * Reverses the order of the elements in the specified list.<p>
366 *
367 * This method runs in linear time.
368 *
369 * @param list the list whose elements are to be reversed.
370 * @throws UnsupportedOperationException if the specified list or
371 * its list-iterator does not support the {@code set} operation.
372 */
373 @SuppressWarnings({"rawtypes", "unchecked"})
374 public static void reverse(List<?> list) {
375 int size = list.size();
376 if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
377 for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
378 swap(list, i, j);
379 } else {
380 // instead of using a raw type here, it's possible to capture
381 // the wildcard but it will require a call to a supplementary
382 // private method
383 ListIterator fwd = list.listIterator();
384 ListIterator rev = list.listIterator(size);
385 for (int i=0, mid=list.size()>>1; i<mid; i++) {
386 Object tmp = fwd.next();
387 fwd.set(rev.previous());
388 rev.set(tmp);
389 }
390 }
391 }
399 * default source of randomness is only approximately an unbiased source
400 * of independently chosen bits. If it were a perfect source of randomly
401 * chosen bits, then the algorithm would choose permutations with perfect
402 * uniformity.
403 *
404 * <p>This implementation traverses the list backwards, from the last
405 * element up to the second, repeatedly swapping a randomly selected element
406 * into the "current position". Elements are randomly selected from the
407 * portion of the list that runs from the first element to the current
408 * position, inclusive.
409 *
410 * <p>This method runs in linear time. If the specified list does not
411 * implement the {@link RandomAccess} interface and is large, this
412 * implementation dumps the specified list into an array before shuffling
413 * it, and dumps the shuffled array back into the list. This avoids the
414 * quadratic behavior that would result from shuffling a "sequential
415 * access" list in place.
416 *
417 * @param list the list to be shuffled.
418 * @throws UnsupportedOperationException if the specified list or
419 * its list-iterator does not support the {@code set} operation.
420 */
421 public static void shuffle(List<?> list) {
422 Random rnd = r;
423 if (rnd == null)
424 r = rnd = new Random(); // harmless race.
425 shuffle(list, rnd);
426 }
427
428 private static Random r;
429
430 /**
431 * Randomly permute the specified list using the specified source of
432 * randomness. All permutations occur with equal likelihood
433 * assuming that the source of randomness is fair.<p>
434 *
435 * This implementation traverses the list backwards, from the last element
436 * up to the second, repeatedly swapping a randomly selected element into
437 * the "current position". Elements are randomly selected from the
438 * portion of the list that runs from the first element to the current
439 * position, inclusive.<p>
440 *
441 * This method runs in linear time. If the specified list does not
442 * implement the {@link RandomAccess} interface and is large, this
443 * implementation dumps the specified list into an array before shuffling
444 * it, and dumps the shuffled array back into the list. This avoids the
445 * quadratic behavior that would result from shuffling a "sequential
446 * access" list in place.
447 *
448 * @param list the list to be shuffled.
449 * @param rnd the source of randomness to use to shuffle the list.
450 * @throws UnsupportedOperationException if the specified list or its
451 * list-iterator does not support the {@code set} operation.
452 */
453 @SuppressWarnings({"rawtypes", "unchecked"})
454 public static void shuffle(List<?> list, Random rnd) {
455 int size = list.size();
456 if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
457 for (int i=size; i>1; i--)
458 swap(list, i-1, rnd.nextInt(i));
459 } else {
460 Object arr[] = list.toArray();
461
462 // Shuffle array
463 for (int i=size; i>1; i--)
464 swap(arr, i-1, rnd.nextInt(i));
465
466 // Dump array back into list
467 // instead of using a raw type here, it's possible to capture
468 // the wildcard but it will require a call to a supplementary
469 // private method
470 ListIterator it = list.listIterator();
471 for (Object e : arr) {
472 it.next();
473 it.set(e);
474 }
475 }
476 }
477
478 /**
479 * Swaps the elements at the specified positions in the specified list.
480 * (If the specified positions are equal, invoking this method leaves
481 * the list unchanged.)
482 *
483 * @param list The list in which to swap elements.
484 * @param i the index of one element to be swapped.
485 * @param j the index of the other element to be swapped.
486 * @throws IndexOutOfBoundsException if either {@code i} or {@code j}
487 * is out of range (i < 0 || i >= list.size()
488 * || j < 0 || j >= list.size()).
489 * @since 1.4
490 */
491 @SuppressWarnings({"rawtypes", "unchecked"})
492 public static void swap(List<?> list, int i, int j) {
493 // instead of using a raw type here, it's possible to capture
494 // the wildcard but it will require a call to a supplementary
495 // private method
496 final List l = list;
497 l.set(i, l.set(j, l.get(i)));
498 }
499
500 /**
501 * Swaps the two specified elements in the specified array.
502 */
503 private static void swap(Object[] arr, int i, int j) {
504 Object tmp = arr[i];
505 arr[i] = arr[j];
506 arr[j] = tmp;
507 }
508
509 /**
510 * Replaces all of the elements of the specified list with the specified
511 * element. <p>
512 *
513 * This method runs in linear time.
514 *
515 * @param <T> the class of the objects in the list
516 * @param list the list to be filled with the specified element.
517 * @param obj The element with which to fill the specified list.
518 * @throws UnsupportedOperationException if the specified list or its
519 * list-iterator does not support the {@code set} operation.
520 */
521 public static <T> void fill(List<? super T> list, T obj) {
522 int size = list.size();
523
524 if (size < FILL_THRESHOLD || list instanceof RandomAccess) {
525 for (int i=0; i<size; i++)
526 list.set(i, obj);
527 } else {
528 ListIterator<? super T> itr = list.listIterator();
529 for (int i=0; i<size; i++) {
530 itr.next();
531 itr.set(obj);
532 }
533 }
534 }
535
536 /**
537 * Copies all of the elements from one list into another. After the
538 * operation, the index of each copied element in the destination list
539 * will be identical to its index in the source list. The destination
540 * list must be at least as long as the source list. If it is longer, the
541 * remaining elements in the destination list are unaffected. <p>
542 *
543 * This method runs in linear time.
544 *
545 * @param <T> the class of the objects in the lists
546 * @param dest The destination list.
547 * @param src The source list.
548 * @throws IndexOutOfBoundsException if the destination list is too small
549 * to contain the entire source List.
550 * @throws UnsupportedOperationException if the destination list's
551 * list-iterator does not support the {@code set} operation.
552 */
553 public static <T> void copy(List<? super T> dest, List<? extends T> src) {
554 int srcSize = src.size();
555 if (srcSize > dest.size())
556 throw new IndexOutOfBoundsException("Source does not fit in dest");
557
558 if (srcSize < COPY_THRESHOLD ||
559 (src instanceof RandomAccess && dest instanceof RandomAccess)) {
560 for (int i=0; i<srcSize; i++)
561 dest.set(i, src.get(i));
562 } else {
563 ListIterator<? super T> di=dest.listIterator();
564 ListIterator<? extends T> si=src.listIterator();
565 for (int i=0; i<srcSize; i++) {
566 di.next();
567 di.set(si.next());
568 }
569 }
570 }
571
572 /**
573 * Returns the minimum element of the given collection, according to the
574 * <i>natural ordering</i> of its elements. All elements in the
575 * collection must implement the {@code Comparable} interface.
576 * Furthermore, all elements in the collection must be <i>mutually
577 * comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a
578 * {@code ClassCastException} for any elements {@code e1} and
579 * {@code e2} in the collection).<p>
580 *
581 * This method iterates over the entire collection, hence it requires
582 * time proportional to the size of the collection.
583 *
584 * @param <T> the class of the objects in the collection
585 * @param coll the collection whose minimum element is to be determined.
586 * @return the minimum element of the given collection, according
587 * to the <i>natural ordering</i> of its elements.
588 * @throws ClassCastException if the collection contains elements that are
589 * not <i>mutually comparable</i> (for example, strings and
590 * integers).
591 * @throws NoSuchElementException if the collection is empty.
592 * @see Comparable
593 */
594 public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
595 Iterator<? extends T> i = coll.iterator();
596 T candidate = i.next();
597
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 /**
607 * Returns the minimum element of the given collection, according to the
608 * order induced by the specified comparator. All elements in the
609 * collection must be <i>mutually comparable</i> by the specified
610 * comparator (that is, {@code comp.compare(e1, e2)} must not throw a
611 * {@code ClassCastException} for any elements {@code e1} and
612 * {@code e2} in the collection).<p>
613 *
614 * This method iterates over the entire collection, hence it requires
615 * time proportional to the size of the collection.
616 *
617 * @param <T> the class of the objects in the collection
618 * @param coll the collection whose minimum element is to be determined.
619 * @param comp the comparator with which to determine the minimum element.
620 * A {@code null} value indicates that the elements' <i>natural
621 * ordering</i> should be used.
622 * @return the minimum element of the given collection, according
623 * to the specified comparator.
624 * @throws ClassCastException if the collection contains elements that are
625 * not <i>mutually comparable</i> using the specified comparator.
626 * @throws NoSuchElementException if the collection is empty.
627 * @see Comparable
628 */
629 @SuppressWarnings({"unchecked", "rawtypes"})
630 public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {
631 if (comp==null)
632 return (T)min((Collection) coll);
633
634 Iterator<? extends T> i = coll.iterator();
635 T candidate = i.next();
636
637 while (i.hasNext()) {
638 T next = i.next();
639 if (comp.compare(next, candidate) < 0)
640 candidate = next;
641 }
642 return candidate;
643 }
644
645 /**
646 * Returns the maximum element of the given collection, according to the
647 * <i>natural ordering</i> of its elements. All elements in the
648 * collection must implement the {@code Comparable} interface.
649 * Furthermore, all elements in the collection must be <i>mutually
650 * comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a
651 * {@code ClassCastException} for any elements {@code e1} and
652 * {@code e2} in the collection).<p>
653 *
654 * This method iterates over the entire collection, hence it requires
655 * time proportional to the size of the collection.
656 *
657 * @param <T> the class of the objects in the collection
658 * @param coll the collection whose maximum element is to be determined.
659 * @return the maximum element of the given collection, according
660 * to the <i>natural ordering</i> of its elements.
661 * @throws ClassCastException if the collection contains elements that are
662 * not <i>mutually comparable</i> (for example, strings and
663 * integers).
664 * @throws NoSuchElementException if the collection is empty.
665 * @see Comparable
666 */
667 public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
668 Iterator<? extends T> i = coll.iterator();
669 T candidate = i.next();
670
671 while (i.hasNext()) {
672 T next = i.next();
673 if (next.compareTo(candidate) > 0)
674 candidate = next;
675 }
676 return candidate;
677 }
678
679 /**
680 * Returns the maximum element of the given collection, according to the
681 * order induced by the specified comparator. All elements in the
682 * collection must be <i>mutually comparable</i> by the specified
683 * comparator (that is, {@code comp.compare(e1, e2)} must not throw a
684 * {@code ClassCastException} for any elements {@code e1} and
685 * {@code e2} in the collection).<p>
686 *
687 * This method iterates over the entire collection, hence it requires
688 * time proportional to the size of the collection.
689 *
690 * @param <T> the class of the objects in the collection
691 * @param coll the collection whose maximum element is to be determined.
692 * @param comp the comparator with which to determine the maximum element.
693 * A {@code null} value indicates that the elements' <i>natural
694 * ordering</i> should be used.
695 * @return the maximum element of the given collection, according
696 * to the specified comparator.
697 * @throws ClassCastException if the collection contains elements that are
698 * not <i>mutually comparable</i> using the specified comparator.
699 * @throws NoSuchElementException if the collection is empty.
700 * @see Comparable
701 */
702 @SuppressWarnings({"unchecked", "rawtypes"})
703 public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {
704 if (comp==null)
705 return (T)max((Collection) coll);
706
707 Iterator<? extends T> i = coll.iterator();
708 T candidate = i.next();
709
710 while (i.hasNext()) {
711 T next = i.next();
712 if (comp.compare(next, candidate) > 0)
713 candidate = next;
714 }
715 return candidate;
716 }
717
718 /**
719 * Rotates the elements in the specified list by the specified distance.
720 * After calling this method, the element at index {@code i} will be
721 * the element previously at index {@code (i - distance)} mod
722 * {@code list.size()}, for all values of {@code i} between {@code 0}
723 * and {@code list.size()-1}, inclusive. (This method has no effect on
724 * the size of the list.)
725 *
726 * <p>For example, suppose {@code list} comprises{@code [t, a, n, k, s]}.
727 * After invoking {@code Collections.rotate(list, 1)} (or
728 * {@code Collections.rotate(list, -4)}), {@code list} will comprise
729 * {@code [s, t, a, n, k]}.
730 *
731 * <p>Note that this method can usefully be applied to sublists to
732 * move one or more elements within a list while preserving the
733 * order of the remaining elements. For example, the following idiom
734 * moves the element at index {@code j} forward to position
735 * {@code k} (which must be greater than or equal to {@code j}):
736 * <pre>
737 * Collections.rotate(list.subList(j, k+1), -1);
738 * </pre>
739 * To make this concrete, suppose {@code list} comprises
740 * {@code [a, b, c, d, e]}. To move the element at index {@code 1}
741 * ({@code b}) forward two positions, perform the following invocation:
742 * <pre>
743 * Collections.rotate(l.subList(1, 4), -1);
744 * </pre>
745 * The resulting list is {@code [a, c, d, b, e]}.
746 *
747 * <p>To move more than one element forward, increase the absolute value
748 * of the rotation distance. To move elements backward, use a positive
749 * shift distance.
750 *
751 * <p>If the specified list is small or implements the {@link
752 * RandomAccess} interface, this implementation exchanges the first
753 * element into the location it should go, and then repeatedly exchanges
754 * the displaced element into the location it should go until a displaced
755 * element is swapped into the first element. If necessary, the process
756 * is repeated on the second and successive elements, until the rotation
757 * is complete. If the specified list is large and doesn't implement the
758 * {@code RandomAccess} interface, this implementation breaks the
759 * list into two sublist views around index {@code -distance mod size}.
760 * Then the {@link #reverse(List)} method is invoked on each sublist view,
761 * and finally it is invoked on the entire list. For a more complete
762 * description of both algorithms, see Section 2.3 of Jon Bentley's
763 * <i>Programming Pearls</i> (Addison-Wesley, 1986).
764 *
765 * @param list the list to be rotated.
766 * @param distance the distance to rotate the list. There are no
767 * constraints on this value; it may be zero, negative, or
768 * greater than {@code list.size()}.
769 * @throws UnsupportedOperationException if the specified list or
770 * its list-iterator does not support the {@code set} operation.
771 * @since 1.4
772 */
773 public static void rotate(List<?> list, int distance) {
774 if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD)
775 rotate1(list, distance);
776 else
777 rotate2(list, distance);
778 }
779
780 private static <T> void rotate1(List<T> list, int distance) {
781 int size = list.size();
782 if (size == 0)
783 return;
784 distance = distance % size;
785 if (distance < 0)
786 distance += size;
787 if (distance == 0)
788 return;
789
790 for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) {
800 }
801 }
802
803 private static void rotate2(List<?> list, int distance) {
804 int size = list.size();
805 if (size == 0)
806 return;
807 int mid = -distance % size;
808 if (mid < 0)
809 mid += size;
810 if (mid == 0)
811 return;
812
813 reverse(list.subList(0, mid));
814 reverse(list.subList(mid, size));
815 reverse(list);
816 }
817
818 /**
819 * Replaces all occurrences of one specified value in a list with another.
820 * More formally, replaces with {@code newVal} each element {@code e}
821 * in {@code list} such that
822 * {@code (oldVal==null ? e==null : oldVal.equals(e))}.
823 * (This method has no effect on the size of the list.)
824 *
825 * @param <T> the class of the objects in the list
826 * @param list the list in which replacement is to occur.
827 * @param oldVal the old value to be replaced.
828 * @param newVal the new value with which {@code oldVal} is to be
829 * replaced.
830 * @return {@code true} if {@code list} contained one or more elements
831 * {@code e} such that
832 * {@code (oldVal==null ? e==null : oldVal.equals(e))}.
833 * @throws UnsupportedOperationException if the specified list or
834 * its list-iterator does not support the {@code set} operation.
835 * @since 1.4
836 */
837 public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) {
838 boolean result = false;
839 int size = list.size();
840 if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) {
841 if (oldVal==null) {
842 for (int i=0; i<size; i++) {
843 if (list.get(i)==null) {
844 list.set(i, newVal);
845 result = true;
846 }
847 }
848 } else {
849 for (int i=0; i<size; i++) {
850 if (oldVal.equals(list.get(i))) {
851 list.set(i, newVal);
852 result = true;
853 }
854 }
860 if (itr.next()==null) {
861 itr.set(newVal);
862 result = true;
863 }
864 }
865 } else {
866 for (int i=0; i<size; i++) {
867 if (oldVal.equals(itr.next())) {
868 itr.set(newVal);
869 result = true;
870 }
871 }
872 }
873 }
874 return result;
875 }
876
877 /**
878 * Returns the starting position of the first occurrence of the specified
879 * target list within the specified source list, or -1 if there is no
880 * such occurrence. More formally, returns the lowest index {@code i}
881 * such that {@code source.subList(i, i+target.size()).equals(target)},
882 * or -1 if there is no such index. (Returns -1 if
883 * {@code target.size() > source.size()})
884 *
885 * <p>This implementation uses the "brute force" technique of scanning
886 * over the source list, looking for a match with the target at each
887 * location in turn.
888 *
889 * @param source the list in which to search for the first occurrence
890 * of {@code target}.
891 * @param target the list to search for as a subList of {@code source}.
892 * @return the starting position of the first occurrence of the specified
893 * target list within the specified source list, or -1 if there
894 * is no such occurrence.
895 * @since 1.4
896 */
897 public static int indexOfSubList(List<?> source, List<?> target) {
898 int sourceSize = source.size();
899 int targetSize = target.size();
900 int maxCandidate = sourceSize - targetSize;
901
902 if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
903 (source instanceof RandomAccess&&target instanceof RandomAccess)) {
904 nextCand:
905 for (int candidate = 0; candidate <= maxCandidate; candidate++) {
906 for (int i=0, j=candidate; i<targetSize; i++, j++)
907 if (!eq(target.get(i), source.get(j)))
908 continue nextCand; // Element mismatch, try next cand
909 return candidate; // All elements of candidate matched target
910 }
911 } else { // Iterator version of above algorithm
913 nextCand:
914 for (int candidate = 0; candidate <= maxCandidate; candidate++) {
915 ListIterator<?> ti = target.listIterator();
916 for (int i=0; i<targetSize; i++) {
917 if (!eq(ti.next(), si.next())) {
918 // Back up source iterator to next candidate
919 for (int j=0; j<i; j++)
920 si.previous();
921 continue nextCand;
922 }
923 }
924 return candidate;
925 }
926 }
927 return -1; // No candidate matched the target
928 }
929
930 /**
931 * Returns the starting position of the last occurrence of the specified
932 * target list within the specified source list, or -1 if there is no such
933 * occurrence. More formally, returns the highest index {@code i}
934 * such that {@code source.subList(i, i+target.size()).equals(target)},
935 * or -1 if there is no such index. (Returns -1 if
936 * {@code target.size() > source.size()})
937 *
938 * <p>This implementation uses the "brute force" technique of iterating
939 * over the source list, looking for a match with the target at each
940 * location in turn.
941 *
942 * @param source the list in which to search for the last occurrence
943 * of {@code target}.
944 * @param target the list to search for as a subList of {@code source}.
945 * @return the starting position of the last occurrence of the specified
946 * target list within the specified source list, or -1 if there
947 * is no such occurrence.
948 * @since 1.4
949 */
950 public static int lastIndexOfSubList(List<?> source, List<?> target) {
951 int sourceSize = source.size();
952 int targetSize = target.size();
953 int maxCandidate = sourceSize - targetSize;
954
955 if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
956 source instanceof RandomAccess) { // Index access version
957 nextCand:
958 for (int candidate = maxCandidate; candidate >= 0; candidate--) {
959 for (int i=0, j=candidate; i<targetSize; i++, j++)
960 if (!eq(target.get(i), source.get(j)))
961 continue nextCand; // Element mismatch, try next cand
962 return candidate; // All elements of candidate matched target
963 }
964 } else { // Iterator version of above algorithm
976 si.previous();
977 }
978 continue nextCand;
979 }
980 }
981 return candidate;
982 }
983 }
984 return -1; // No candidate matched the target
985 }
986
987
988 // Unmodifiable Wrappers
989
990 /**
991 * Returns an unmodifiable view of the specified collection. This method
992 * allows modules to provide users with "read-only" access to internal
993 * collections. Query operations on the returned collection "read through"
994 * to the specified collection, and attempts to modify the returned
995 * collection, whether direct or via its iterator, result in an
996 * {@code UnsupportedOperationException}.<p>
997 *
998 * The returned collection does <i>not</i> pass the hashCode and equals
999 * operations through to the backing collection, but relies on
1000 * {@code Object}'s {@code equals} and {@code hashCode} methods. This
1001 * is necessary to preserve the contracts of these operations in the case
1002 * that the backing collection is a set or a list.<p>
1003 *
1004 * The returned collection will be serializable if the specified collection
1005 * is serializable.
1006 *
1007 * @param <T> the class of the objects in the collection
1008 * @param c the collection for which an unmodifiable view is to be
1009 * returned.
1010 * @return an unmodifiable view of the specified collection.
1011 */
1012 public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
1013 return new UnmodifiableCollection<>(c);
1014 }
1015
1016 /**
1017 * @serial include
1018 */
1019 static class UnmodifiableCollection<E> implements Collection<E>, Serializable {
1020 private static final long serialVersionUID = 1820017752578914078L;
1088 public Spliterator<E> spliterator() {
1089 return (Spliterator<E>)c.spliterator();
1090 }
1091 @SuppressWarnings("unchecked")
1092 @Override
1093 public Stream<E> stream() {
1094 return (Stream<E>)c.stream();
1095 }
1096 @SuppressWarnings("unchecked")
1097 @Override
1098 public Stream<E> parallelStream() {
1099 return (Stream<E>)c.parallelStream();
1100 }
1101 }
1102
1103 /**
1104 * Returns an unmodifiable view of the specified set. This method allows
1105 * modules to provide users with "read-only" access to internal sets.
1106 * Query operations on the returned set "read through" to the specified
1107 * set, and attempts to modify the returned set, whether direct or via its
1108 * iterator, result in an {@code UnsupportedOperationException}.<p>
1109 *
1110 * The returned set will be serializable if the specified set
1111 * is serializable.
1112 *
1113 * @param <T> the class of the objects in the set
1114 * @param s the set for which an unmodifiable view is to be returned.
1115 * @return an unmodifiable view of the specified set.
1116 */
1117 public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
1118 return new UnmodifiableSet<>(s);
1119 }
1120
1121 /**
1122 * @serial include
1123 */
1124 static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
1125 implements Set<E>, Serializable {
1126 private static final long serialVersionUID = -9215047833775013803L;
1127
1128 UnmodifiableSet(Set<? extends E> s) {super(s);}
1129 public boolean equals(Object o) {return o == this || c.equals(o);}
1130 public int hashCode() {return c.hashCode();}
1131 }
1132
1133 /**
1134 * Returns an unmodifiable view of the specified sorted set. This method
1135 * allows modules to provide users with "read-only" access to internal
1136 * sorted sets. Query operations on the returned sorted set "read
1137 * through" to the specified sorted set. Attempts to modify the returned
1138 * sorted set, whether direct, via its iterator, or via its
1139 * {@code subSet}, {@code headSet}, or {@code tailSet} views, result in
1140 * an {@code UnsupportedOperationException}.<p>
1141 *
1142 * The returned sorted set will be serializable if the specified sorted set
1143 * is serializable.
1144 *
1145 * @param <T> the class of the objects in the set
1146 * @param s the sorted set for which an unmodifiable view is to be
1147 * returned.
1148 * @return an unmodifiable view of the specified sorted set.
1149 */
1150 public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
1151 return new UnmodifiableSortedSet<>(s);
1152 }
1153
1154 /**
1155 * @serial include
1156 */
1157 static class UnmodifiableSortedSet<E>
1158 extends UnmodifiableSet<E>
1159 implements SortedSet<E>, Serializable {
1160 private static final long serialVersionUID = -4929149591599911165L;
1256 ns.subSet(fromElement, fromInclusive, toElement, toInclusive));
1257 }
1258
1259 public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1260 return new UnmodifiableNavigableSet<>(
1261 ns.headSet(toElement, inclusive));
1262 }
1263
1264 public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1265 return new UnmodifiableNavigableSet<>(
1266 ns.tailSet(fromElement, inclusive));
1267 }
1268 }
1269
1270 /**
1271 * Returns an unmodifiable view of the specified list. This method allows
1272 * modules to provide users with "read-only" access to internal
1273 * lists. Query operations on the returned list "read through" to the
1274 * specified list, and attempts to modify the returned list, whether
1275 * direct or via its iterator, result in an
1276 * {@code UnsupportedOperationException}.<p>
1277 *
1278 * The returned list will be serializable if the specified list
1279 * is serializable. Similarly, the returned list will implement
1280 * {@link RandomAccess} if the specified list does.
1281 *
1282 * @param <T> the class of the objects in the list
1283 * @param list the list for which an unmodifiable view is to be returned.
1284 * @return an unmodifiable view of the specified list.
1285 */
1286 public static <T> List<T> unmodifiableList(List<? extends T> list) {
1287 return (list instanceof RandomAccess ?
1288 new UnmodifiableRandomAccessList<>(list) :
1289 new UnmodifiableList<>(list));
1290 }
1291
1292 /**
1293 * @serial include
1294 */
1295 static class UnmodifiableList<E> extends UnmodifiableCollection<E>
1296 implements List<E> {
1402
1403 private static final long serialVersionUID = -2542308836966382001L;
1404
1405 /**
1406 * Allows instances to be deserialized in pre-1.4 JREs (which do
1407 * not have UnmodifiableRandomAccessList). UnmodifiableList has
1408 * a readResolve method that inverts this transformation upon
1409 * deserialization.
1410 */
1411 private Object writeReplace() {
1412 return new UnmodifiableList<>(list);
1413 }
1414 }
1415
1416 /**
1417 * Returns an unmodifiable view of the specified map. This method
1418 * allows modules to provide users with "read-only" access to internal
1419 * maps. Query operations on the returned map "read through"
1420 * to the specified map, and attempts to modify the returned
1421 * map, whether direct or via its collection views, result in an
1422 * {@code UnsupportedOperationException}.<p>
1423 *
1424 * The returned map will be serializable if the specified map
1425 * is serializable.
1426 *
1427 * @param <K> the class of the map keys
1428 * @param <V> the class of the map values
1429 * @param m the map for which an unmodifiable view is to be returned.
1430 * @return an unmodifiable view of the specified map.
1431 */
1432 public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
1433 return new UnmodifiableMap<>(m);
1434 }
1435
1436 /**
1437 * @serial include
1438 */
1439 private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {
1440 private static final long serialVersionUID = -1034234728574286014L;
1441
1442 private final Map<? extends K, ? extends V> m;
1752 public boolean equals(Object o) {
1753 if (this == o)
1754 return true;
1755 if (!(o instanceof Map.Entry))
1756 return false;
1757 Map.Entry<?,?> t = (Map.Entry<?,?>)o;
1758 return eq(e.getKey(), t.getKey()) &&
1759 eq(e.getValue(), t.getValue());
1760 }
1761 public String toString() {return e.toString();}
1762 }
1763 }
1764 }
1765
1766 /**
1767 * Returns an unmodifiable view of the specified sorted map. This method
1768 * allows modules to provide users with "read-only" access to internal
1769 * sorted maps. Query operations on the returned sorted map "read through"
1770 * to the specified sorted map. Attempts to modify the returned
1771 * sorted map, whether direct, via its collection views, or via its
1772 * {@code subMap}, {@code headMap}, or {@code tailMap} views, result in
1773 * an {@code UnsupportedOperationException}.<p>
1774 *
1775 * The returned sorted map will be serializable if the specified sorted map
1776 * is serializable.
1777 *
1778 * @param <K> the class of the map keys
1779 * @param <V> the class of the map values
1780 * @param m the sorted map for which an unmodifiable view is to be
1781 * returned.
1782 * @return an unmodifiable view of the specified sorted map.
1783 */
1784 public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {
1785 return new UnmodifiableSortedMap<>(m);
1786 }
1787
1788 /**
1789 * @serial include
1790 */
1791 static class UnmodifiableSortedMap<K,V>
1792 extends UnmodifiableMap<K,V>
1793 implements SortedMap<K,V>, Serializable {
2131 super(s, mutex);
2132 }
2133
2134 public boolean equals(Object o) {
2135 if (this == o)
2136 return true;
2137 synchronized (mutex) {return c.equals(o);}
2138 }
2139 public int hashCode() {
2140 synchronized (mutex) {return c.hashCode();}
2141 }
2142 }
2143
2144 /**
2145 * Returns a synchronized (thread-safe) sorted set backed by the specified
2146 * sorted set. In order to guarantee serial access, it is critical that
2147 * <strong>all</strong> access to the backing sorted set is accomplished
2148 * through the returned sorted set (or its views).<p>
2149 *
2150 * It is imperative that the user manually synchronize on the returned
2151 * sorted set when iterating over it or any of its {@code subSet},
2152 * {@code headSet}, or {@code tailSet} views.
2153 * <pre>
2154 * SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
2155 * ...
2156 * synchronized (s) {
2157 * Iterator i = s.iterator(); // Must be in the synchronized block
2158 * while (i.hasNext())
2159 * foo(i.next());
2160 * }
2161 * </pre>
2162 * or:
2163 * <pre>
2164 * SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
2165 * SortedSet s2 = s.headSet(foo);
2166 * ...
2167 * synchronized (s) { // Note: s, not s2!!!
2168 * Iterator i = s2.iterator(); // Must be in the synchronized block
2169 * while (i.hasNext())
2170 * foo(i.next());
2171 * }
2172 * </pre>
2683 }
2684 @Override
2685 public V merge(K key, V value,
2686 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2687 synchronized (mutex) {return m.merge(key, value, remappingFunction);}
2688 }
2689
2690 private void writeObject(ObjectOutputStream s) throws IOException {
2691 synchronized (mutex) {s.defaultWriteObject();}
2692 }
2693 }
2694
2695 /**
2696 * Returns a synchronized (thread-safe) sorted map backed by the specified
2697 * sorted map. In order to guarantee serial access, it is critical that
2698 * <strong>all</strong> access to the backing sorted map is accomplished
2699 * through the returned sorted map (or its views).<p>
2700 *
2701 * It is imperative that the user manually synchronize on the returned
2702 * sorted map when iterating over any of its collection views, or the
2703 * collections views of any of its {@code subMap}, {@code headMap} or
2704 * {@code tailMap} views.
2705 * <pre>
2706 * SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2707 * ...
2708 * Set s = m.keySet(); // Needn't be in synchronized block
2709 * ...
2710 * synchronized (m) { // Synchronizing on m, not s!
2711 * Iterator i = s.iterator(); // Must be in synchronized block
2712 * while (i.hasNext())
2713 * foo(i.next());
2714 * }
2715 * </pre>
2716 * or:
2717 * <pre>
2718 * SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2719 * SortedMap m2 = m.subMap(foo, bar);
2720 * ...
2721 * Set s2 = m2.keySet(); // Needn't be in synchronized block
2722 * ...
2723 * synchronized (m) { // Synchronizing on m, not m2 or s2!
2724 * Iterator i = s.iterator(); // Must be in synchronized block
4389 return (NavigableSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET;
4390 }
4391
4392 /**
4393 * The empty list (immutable). This list is serializable.
4394 *
4395 * @see #emptyList()
4396 */
4397 @SuppressWarnings("rawtypes")
4398 public static final List EMPTY_LIST = new EmptyList<>();
4399
4400 /**
4401 * Returns an empty list (immutable). This list is serializable.
4402 *
4403 * <p>This example illustrates the type-safe way to obtain an empty list:
4404 * <pre>
4405 * List<String> s = Collections.emptyList();
4406 * </pre>
4407 *
4408 * @implNote
4409 * Implementations of this method need not create a separate {@code List}
4410 * object for each call. Using this method is likely to have comparable
4411 * cost to using the like-named field. (Unlike this method, the field does
4412 * not provide type safety.)
4413 *
4414 * @param <T> type of elements, if there were any, in the list
4415 * @return an empty immutable list
4416 *
4417 * @see #EMPTY_LIST
4418 * @since 1.5
4419 */
4420 @SuppressWarnings("unchecked")
4421 public static final <T> List<T> emptyList() {
4422 return (List<T>) EMPTY_LIST;
4423 }
4424
4425 /**
4426 * @serial include
4427 */
4428 private static class EmptyList<E>
4429 extends AbstractList<E>
4829 @Override
4830 public void replaceAll(UnaryOperator<E> operator) {
4831 throw new UnsupportedOperationException();
4832 }
4833 @Override
4834 public void sort(Comparator<? super E> c) {
4835 }
4836 @Override
4837 public Spliterator<E> spliterator() {
4838 return singletonSpliterator(element);
4839 }
4840 }
4841
4842 /**
4843 * Returns an immutable map, mapping only the specified key to the
4844 * specified value. The returned map is serializable.
4845 *
4846 * @param <K> the class of the map keys
4847 * @param <V> the class of the map values
4848 * @param key the sole key to be stored in the returned map.
4849 * @param value the value to which the returned map maps {@code key}.
4850 * @return an immutable map containing only the specified key-value
4851 * mapping.
4852 * @since 1.3
4853 */
4854 public static <K,V> Map<K,V> singletonMap(K key, V value) {
4855 return new SingletonMap<>(key, value);
4856 }
4857
4858 /**
4859 * @serial include
4860 */
4861 private static class SingletonMap<K,V>
4862 extends AbstractMap<K,V>
4863 implements Serializable {
4864 private static final long serialVersionUID = -6979724477215052911L;
4865
4866 private final K k;
4867 private final V v;
4868
4869 SingletonMap(K key, V value) {
4947 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
4948 throw new UnsupportedOperationException();
4949 }
4950
4951 @Override
4952 public V compute(K key,
4953 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
4954 throw new UnsupportedOperationException();
4955 }
4956
4957 @Override
4958 public V merge(K key, V value,
4959 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
4960 throw new UnsupportedOperationException();
4961 }
4962 }
4963
4964 // Miscellaneous
4965
4966 /**
4967 * Returns an immutable list consisting of {@code n} copies of the
4968 * specified object. The newly allocated data object is tiny (it contains
4969 * a single reference to the data object). This method is useful in
4970 * combination with the {@code List.addAll} method to grow lists.
4971 * The returned list is serializable.
4972 *
4973 * @param <T> the class of the object to copy and of the objects
4974 * in the returned list.
4975 * @param n the number of elements in the returned list.
4976 * @param o the element to appear repeatedly in the returned list.
4977 * @return an immutable list consisting of {@code n} copies of the
4978 * specified object.
4979 * @throws IllegalArgumentException if {@code n < 0}
4980 * @see List#addAll(Collection)
4981 * @see List#addAll(int, Collection)
4982 */
4983 public static <T> List<T> nCopies(int n, T o) {
4984 if (n < 0)
4985 throw new IllegalArgumentException("List length = " + n);
4986 return new CopiesList<>(n, o);
4987 }
4988
4989 /**
4990 * @serial include
4991 */
4992 private static class CopiesList<E>
4993 extends AbstractList<E>
4994 implements RandomAccess, Serializable
4995 {
4996 private static final long serialVersionUID = 2739099268398711800L;
4997
5078 }
5079 }
5080
5081 /**
5082 * Returns a comparator that imposes the reverse of the <em>natural
5083 * ordering</em> on a collection of objects that implement the
5084 * {@code Comparable} interface. (The natural ordering is the ordering
5085 * imposed by the objects' own {@code compareTo} method.) This enables a
5086 * simple idiom for sorting (or maintaining) collections (or arrays) of
5087 * objects that implement the {@code Comparable} interface in
5088 * reverse-natural-order. For example, suppose {@code a} is an array of
5089 * strings. Then: <pre>
5090 * Arrays.sort(a, Collections.reverseOrder());
5091 * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>
5092 *
5093 * The returned comparator is serializable.
5094 *
5095 * @param <T> the class of the objects compared by the comparator
5096 * @return A comparator that imposes the reverse of the <i>natural
5097 * ordering</i> on a collection of objects that implement
5098 * the {@code Comparable} interface.
5099 * @see Comparable
5100 */
5101 @SuppressWarnings("unchecked")
5102 public static <T> Comparator<T> reverseOrder() {
5103 return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
5104 }
5105
5106 /**
5107 * @serial include
5108 */
5109 private static class ReverseComparator
5110 implements Comparator<Comparable<Object>>, Serializable {
5111
5112 private static final long serialVersionUID = 7207038068494060240L;
5113
5114 static final ReverseComparator REVERSE_ORDER
5115 = new ReverseComparator();
5116
5117 public int compare(Comparable<Object> c1, Comparable<Object> c2) {
5118 return c2.compareTo(c1);
5242 */
5243 public static <T> ArrayList<T> list(Enumeration<T> e) {
5244 ArrayList<T> l = new ArrayList<>();
5245 while (e.hasMoreElements())
5246 l.add(e.nextElement());
5247 return l;
5248 }
5249
5250 /**
5251 * Returns true if the specified arguments are equal, or both null.
5252 *
5253 * NB: Do not replace with Object.equals until JDK-8015417 is resolved.
5254 */
5255 static boolean eq(Object o1, Object o2) {
5256 return o1==null ? o2==null : o1.equals(o2);
5257 }
5258
5259 /**
5260 * Returns the number of elements in the specified collection equal to the
5261 * specified object. More formally, returns the number of elements
5262 * {@code e} in the collection such that
5263 * {@code (o == null ? e == null : o.equals(e))}.
5264 *
5265 * @param c the collection in which to determine the frequency
5266 * of {@code o}
5267 * @param o the object whose frequency is to be determined
5268 * @return the number of elements in {@code c} equal to {@code o}
5269 * @throws NullPointerException if {@code c} is null
5270 * @since 1.5
5271 */
5272 public static int frequency(Collection<?> c, Object o) {
5273 int result = 0;
5274 if (o == null) {
5275 for (Object e : c)
5276 if (e == null)
5277 result++;
5278 } else {
5279 for (Object e : c)
5280 if (o.equals(e))
5281 result++;
5282 }
5283 return result;
5284 }
5285
5286 /**
5287 * Returns {@code true} if the two specified collections have no
5288 * elements in common.
5289 *
5360 iterate = c2;
5361 contains = c1;
5362 }
5363 }
5364
5365 for (Object e : iterate) {
5366 if (contains.contains(e)) {
5367 // Found a common element. Collections are not disjoint.
5368 return false;
5369 }
5370 }
5371
5372 // No common elements were found.
5373 return true;
5374 }
5375
5376 /**
5377 * Adds all of the specified elements to the specified collection.
5378 * Elements to be added may be specified individually or as an array.
5379 * The behavior of this convenience method is identical to that of
5380 * {@code c.addAll(Arrays.asList(elements))}, but this method is likely
5381 * to run significantly faster under most implementations.
5382 *
5383 * <p>When elements are specified individually, this method provides a
5384 * convenient way to add a few elements to an existing collection:
5385 * <pre>
5386 * Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");
5387 * </pre>
5388 *
5389 * @param <T> the class of the elements to add and of the collection
5390 * @param c the collection into which {@code elements} are to be inserted
5391 * @param elements the elements to insert into {@code c}
5392 * @return {@code true} if the collection changed as a result of the call
5393 * @throws UnsupportedOperationException if {@code c} does not support
5394 * the {@code add} operation
5395 * @throws NullPointerException if {@code elements} contains one or more
5396 * null values and {@code c} does not permit null elements, or
5397 * if {@code c} or {@code elements} are {@code null}
5398 * @throws IllegalArgumentException if some property of a value in
5399 * {@code elements} prevents it from being added to {@code c}
5400 * @see Collection#addAll(Collection)
5401 * @since 1.5
5402 */
5403 @SafeVarargs
5404 public static <T> boolean addAll(Collection<? super T> c, T... elements) {
5405 boolean result = false;
5406 for (T element : elements)
5407 result |= c.add(element);
5408 return result;
5409 }
5410
5411 /**
5412 * Returns a set backed by the specified map. The resulting set displays
5413 * the same ordering, concurrency, and performance characteristics as the
5414 * backing map. In essence, this factory method provides a {@link Set}
5415 * implementation corresponding to any {@link Map} implementation. There
5416 * is no need to use this method on a {@link Map} implementation that
5417 * already has a corresponding {@link Set} implementation (such as {@link
5418 * HashMap} or {@link TreeMap}).
5419 *
5420 * <p>Each method invocation on the set returned by this method results in
5421 * exactly one method invocation on the backing map or its {@code keySet}
5422 * view, with one exception. The {@code addAll} method is implemented
5423 * as a sequence of {@code put} invocations on the backing map.
5424 *
5425 * <p>The specified map must be empty at the time this method is invoked,
5426 * and should not be accessed directly after this method returns. These
5427 * conditions are ensured if the map is created empty, passed directly
5428 * to this method, and no reference to the map is retained, as illustrated
5429 * in the following code fragment:
5430 * <pre>
5431 * Set<Object> weakHashSet = Collections.newSetFromMap(
5432 * new WeakHashMap<Object, Boolean>());
5433 * </pre>
5434 *
5435 * @param <E> the class of the map keys and of the objects in the
5436 * returned set
5437 * @param map the backing map
5438 * @return the set backed by the map
5439 * @throws IllegalArgumentException if {@code map} is not empty
5440 * @since 1.6
5441 */
5442 public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
5443 return new SetFromMap<>(map);
5444 }
5445
5446 /**
5447 * @serial include
5448 */
5449 private static class SetFromMap<E> extends AbstractSet<E>
5450 implements Set<E>, Serializable
5451 {
5452 private final Map<E, Boolean> m; // The backing map
5453 private transient Set<E> s; // Its keySet
5454
5455 SetFromMap(Map<E, Boolean> map) {
5456 if (!map.isEmpty())
5457 throw new IllegalArgumentException("Map is non-empty");
5458 m = map;
5459 s = map.keySet();
5488
5489 @Override
5490 public Spliterator<E> spliterator() {return s.spliterator();}
5491 @Override
5492 public Stream<E> stream() {return s.stream();}
5493 @Override
5494 public Stream<E> parallelStream() {return s.parallelStream();}
5495
5496 private static final long serialVersionUID = 2454657854757543876L;
5497
5498 private void readObject(java.io.ObjectInputStream stream)
5499 throws IOException, ClassNotFoundException
5500 {
5501 stream.defaultReadObject();
5502 s = m.keySet();
5503 }
5504 }
5505
5506 /**
5507 * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)
5508 * {@link Queue}. Method {@code add} is mapped to {@code push},
5509 * {@code remove} is mapped to {@code pop} and so on. This
5510 * view can be useful when you would like to use a method
5511 * requiring a {@code Queue} but you need Lifo ordering.
5512 *
5513 * <p>Each method invocation on the queue returned by this method
5514 * results in exactly one method invocation on the backing deque, with
5515 * one exception. The {@link Queue#addAll addAll} method is
5516 * implemented as a sequence of {@link Deque#addFirst addFirst}
5517 * invocations on the backing deque.
5518 *
5519 * @param <T> the class of the objects in the deque
5520 * @param deque the deque
5521 * @return the queue
5522 * @since 1.6
5523 */
5524 public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
5525 return new AsLIFOQueue<>(deque);
5526 }
5527
5528 /**
5529 * @serial include
5530 */
5531 static class AsLIFOQueue<E> extends AbstractQueue<E>
|