0N/A/*
4856N/A * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage java.util;
0N/Aimport java.io.Serializable;
0N/Aimport java.io.ObjectOutputStream;
0N/Aimport java.io.IOException;
0N/Aimport java.lang.reflect.Array;
0N/A
0N/A/**
0N/A * This class consists exclusively of static methods that operate on or return
0N/A * collections. It contains polymorphic algorithms that operate on
0N/A * collections, "wrappers", which return a new collection backed by a
0N/A * specified collection, and a few other odds and ends.
0N/A *
0N/A * <p>The methods of this class all throw a <tt>NullPointerException</tt>
0N/A * if the collections or class objects provided to them are null.
0N/A *
0N/A * <p>The documentation for the polymorphic algorithms contained in this class
0N/A * generally includes a brief description of the <i>implementation</i>. Such
0N/A * descriptions should be regarded as <i>implementation notes</i>, rather than
0N/A * parts of the <i>specification</i>. Implementors should feel free to
0N/A * substitute other algorithms, so long as the specification itself is adhered
0N/A * to. (For example, the algorithm used by <tt>sort</tt> does not have to be
0N/A * a mergesort, but it does have to be <i>stable</i>.)
0N/A *
0N/A * <p>The "destructive" algorithms contained in this class, that is, the
0N/A * algorithms that modify the collection on which they operate, are specified
0N/A * to throw <tt>UnsupportedOperationException</tt> if the collection does not
0N/A * support the appropriate mutation primitive(s), such as the <tt>set</tt>
0N/A * method. These algorithms may, but are not required to, throw this
0N/A * exception if an invocation would have no effect on the collection. For
0N/A * example, invoking the <tt>sort</tt> method on an unmodifiable list that is
0N/A * already sorted may or may not throw <tt>UnsupportedOperationException</tt>.
0N/A *
0N/A * <p>This class is a member of the
0N/A * <a href="{@docRoot}/../technotes/guides/collections/index.html">
0N/A * Java Collections Framework</a>.
0N/A *
0N/A * @author Josh Bloch
0N/A * @author Neal Gafter
0N/A * @see Collection
0N/A * @see Set
0N/A * @see List
0N/A * @see Map
0N/A * @since 1.2
0N/A */
0N/A
0N/Apublic class Collections {
0N/A // Suppresses default constructor, ensuring non-instantiability.
0N/A private Collections() {
0N/A }
0N/A
0N/A // Algorithms
0N/A
0N/A /*
0N/A * Tuning parameters for algorithms - Many of the List algorithms have
0N/A * two implementations, one of which is appropriate for RandomAccess
0N/A * lists, the other for "sequential." Often, the random access variant
0N/A * yields better performance on small sequential access lists. The
0N/A * tuning parameters below determine the cutoff point for what constitutes
0N/A * a "small" sequential access list for each algorithm. The values below
0N/A * were empirically determined to work well for LinkedList. Hopefully
0N/A * they should be reasonable for other sequential access List
0N/A * implementations. Those doing performance work on this code would
0N/A * do well to validate the values of these parameters from time to time.
0N/A * (The first word of each tuning parameter name is the algorithm to which
0N/A * it applies.)
0N/A */
0N/A private static final int BINARYSEARCH_THRESHOLD = 5000;
0N/A private static final int REVERSE_THRESHOLD = 18;
0N/A private static final int SHUFFLE_THRESHOLD = 5;
0N/A private static final int FILL_THRESHOLD = 25;
0N/A private static final int ROTATE_THRESHOLD = 100;
0N/A private static final int COPY_THRESHOLD = 10;
0N/A private static final int REPLACEALL_THRESHOLD = 11;
0N/A private static final int INDEXOFSUBLIST_THRESHOLD = 35;
0N/A
0N/A /**
0N/A * Sorts the specified list into ascending order, according to the
1473N/A * {@linkplain Comparable natural ordering} of its elements.
1473N/A * All elements in the list must implement the {@link Comparable}
1473N/A * interface. Furthermore, all elements in the list must be
1473N/A * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)}
1473N/A * must not throw a {@code ClassCastException} for any elements
1473N/A * {@code e1} and {@code e2} in the list).
0N/A *
1473N/A * <p>This sort is guaranteed to be <i>stable</i>: equal elements will
1473N/A * not be reordered as a result of the sort.
1473N/A *
1473N/A * <p>The specified list must be modifiable, but need not be resizable.
0N/A *
1473N/A * <p>Implementation note: This implementation is a stable, adaptive,
1473N/A * iterative mergesort that requires far fewer than n lg(n) comparisons
1473N/A * when the input array is partially sorted, while offering the
1473N/A * performance of a traditional mergesort when the input array is
1473N/A * randomly ordered. If the input array is nearly sorted, the
1473N/A * implementation requires approximately n comparisons. Temporary
1473N/A * storage requirements vary from a small constant for nearly sorted
1473N/A * input arrays to n/2 object references for randomly ordered input
1473N/A * arrays.
0N/A *
1473N/A * <p>The implementation takes equal advantage of ascending and
1473N/A * descending order in its input array, and can take advantage of
3203N/A * ascending and descending order in different parts of the same
1473N/A * input array. It is well-suited to merging two or more sorted arrays:
1473N/A * simply concatenate the arrays and sort the resulting array.
0N/A *
1473N/A * <p>The implementation was adapted from Tim Peters's list sort for Python
1473N/A * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
1473N/A * TimSort</a>). It uses techiques from Peter McIlroy's "Optimistic
1473N/A * Sorting and Information Theoretic Complexity", in Proceedings of the
1473N/A * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
1473N/A * January 1993.
1473N/A *
1473N/A * <p>This implementation dumps the specified list into an array, sorts
0N/A * the array, and iterates over the list resetting each element
0N/A * from the corresponding position in the array. This avoids the
0N/A * n<sup>2</sup> log(n) performance that would result from attempting
0N/A * to sort a linked list in place.
0N/A *
0N/A * @param list the list to be sorted.
0N/A * @throws ClassCastException if the list contains elements that are not
0N/A * <i>mutually comparable</i> (for example, strings and integers).
0N/A * @throws UnsupportedOperationException if the specified list's
1473N/A * list-iterator does not support the {@code set} operation.
1473N/A * @throws IllegalArgumentException (optional) if the implementation
1473N/A * detects that the natural ordering of the list elements is
1473N/A * found to violate the {@link Comparable} contract
0N/A */
0N/A public static <T extends Comparable<? super T>> void sort(List<T> list) {
0N/A Object[] a = list.toArray();
0N/A Arrays.sort(a);
0N/A ListIterator<T> i = list.listIterator();
0N/A for (int j=0; j<a.length; j++) {
0N/A i.next();
0N/A i.set((T)a[j]);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Sorts the specified list according to the order induced by the
0N/A * specified comparator. All elements in the list must be <i>mutually
0N/A * comparable</i> using the specified comparator (that is,
1473N/A * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
1473N/A * for any elements {@code e1} and {@code e2} in the list).
0N/A *
1473N/A * <p>This sort is guaranteed to be <i>stable</i>: equal elements will
1473N/A * not be reordered as a result of the sort.
1473N/A *
1473N/A * <p>The specified list must be modifiable, but need not be resizable.
0N/A *
1473N/A * <p>Implementation note: This implementation is a stable, adaptive,
1473N/A * iterative mergesort that requires far fewer than n lg(n) comparisons
1473N/A * when the input array is partially sorted, while offering the
1473N/A * performance of a traditional mergesort when the input array is
1473N/A * randomly ordered. If the input array is nearly sorted, the
1473N/A * implementation requires approximately n comparisons. Temporary
1473N/A * storage requirements vary from a small constant for nearly sorted
1473N/A * input arrays to n/2 object references for randomly ordered input
1473N/A * arrays.
0N/A *
1473N/A * <p>The implementation takes equal advantage of ascending and
1473N/A * descending order in its input array, and can take advantage of
3203N/A * ascending and descending order in different parts of the same
1473N/A * input array. It is well-suited to merging two or more sorted arrays:
1473N/A * simply concatenate the arrays and sort the resulting array.
1473N/A *
1473N/A * <p>The implementation was adapted from Tim Peters's list sort for Python
1473N/A * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
1473N/A * TimSort</a>). It uses techiques from Peter McIlroy's "Optimistic
1473N/A * Sorting and Information Theoretic Complexity", in Proceedings of the
1473N/A * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
1473N/A * January 1993.
1473N/A *
1473N/A * <p>This implementation dumps the specified list into an array, sorts
0N/A * the array, and iterates over the list resetting each element
0N/A * from the corresponding position in the array. This avoids the
0N/A * n<sup>2</sup> log(n) performance that would result from attempting
0N/A * to sort a linked list in place.
0N/A *
0N/A * @param list the list to be sorted.
0N/A * @param c the comparator to determine the order of the list. A
1473N/A * {@code null} value indicates that the elements' <i>natural
0N/A * ordering</i> should be used.
0N/A * @throws ClassCastException if the list contains elements that are not
0N/A * <i>mutually comparable</i> using the specified comparator.
0N/A * @throws UnsupportedOperationException if the specified list's
1473N/A * list-iterator does not support the {@code set} operation.
1473N/A * @throws IllegalArgumentException (optional) if the comparator is
1473N/A * found to violate the {@link Comparator} contract
0N/A */
0N/A public static <T> void sort(List<T> list, Comparator<? super T> c) {
0N/A Object[] a = list.toArray();
0N/A Arrays.sort(a, (Comparator)c);
0N/A ListIterator i = list.listIterator();
0N/A for (int j=0; j<a.length; j++) {
0N/A i.next();
0N/A i.set(a[j]);
0N/A }
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Searches the specified list for the specified object using the binary
0N/A * search algorithm. The list must be sorted into ascending order
0N/A * according to the {@linkplain Comparable natural ordering} of its
0N/A * elements (as by the {@link #sort(List)} method) prior to making this
0N/A * call. If it is not sorted, the results are undefined. If the list
0N/A * contains multiple elements equal to the specified object, there is no
0N/A * guarantee which one will be found.
0N/A *
0N/A * <p>This method runs in log(n) time for a "random access" list (which
0N/A * provides near-constant-time positional access). If the specified list
0N/A * does not implement the {@link RandomAccess} interface and is large,
0N/A * this method will do an iterator-based binary search that performs
0N/A * O(n) link traversals and O(log n) element comparisons.
0N/A *
0N/A * @param list the list to be searched.
0N/A * @param key the key to be searched for.
0N/A * @return the index of the search key, if it is contained in the list;
0N/A * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
0N/A * <i>insertion point</i> is defined as the point at which the
0N/A * key would be inserted into the list: the index of the first
0N/A * element greater than the key, or <tt>list.size()</tt> if all
0N/A * elements in the list are less than the specified key. Note
0N/A * that this guarantees that the return value will be &gt;= 0 if
0N/A * and only if the key is found.
0N/A * @throws ClassCastException if the list contains elements that are not
0N/A * <i>mutually comparable</i> (for example, strings and
0N/A * integers), or the search key is not mutually comparable
0N/A * with the elements of the list.
0N/A */
0N/A public static <T>
0N/A int binarySearch(List<? extends Comparable<? super T>> list, T key) {
0N/A if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
0N/A return Collections.indexedBinarySearch(list, key);
0N/A else
0N/A return Collections.iteratorBinarySearch(list, key);
0N/A }
0N/A
0N/A private static <T>
0N/A int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key)
0N/A {
0N/A int low = 0;
0N/A int high = list.size()-1;
0N/A
0N/A while (low <= high) {
0N/A int mid = (low + high) >>> 1;
0N/A Comparable<? super T> midVal = list.get(mid);
0N/A int cmp = midVal.compareTo(key);
0N/A
0N/A if (cmp < 0)
0N/A low = mid + 1;
0N/A else if (cmp > 0)
0N/A high = mid - 1;
0N/A else
0N/A return mid; // key found
0N/A }
0N/A return -(low + 1); // key not found
0N/A }
0N/A
0N/A private static <T>
0N/A int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key)
0N/A {
0N/A int low = 0;
0N/A int high = list.size()-1;
0N/A ListIterator<? extends Comparable<? super T>> i = list.listIterator();
0N/A
0N/A while (low <= high) {
0N/A int mid = (low + high) >>> 1;
0N/A Comparable<? super T> midVal = get(i, mid);
0N/A int cmp = midVal.compareTo(key);
0N/A
0N/A if (cmp < 0)
0N/A low = mid + 1;
0N/A else if (cmp > 0)
0N/A high = mid - 1;
0N/A else
0N/A return mid; // key found
0N/A }
0N/A return -(low + 1); // key not found
0N/A }
0N/A
0N/A /**
0N/A * Gets the ith element from the given list by repositioning the specified
0N/A * list listIterator.
0N/A */
0N/A private static <T> T get(ListIterator<? extends T> i, int index) {
0N/A T obj = null;
0N/A int pos = i.nextIndex();
0N/A if (pos <= index) {
0N/A do {
0N/A obj = i.next();
0N/A } while (pos++ < index);
0N/A } else {
0N/A do {
0N/A obj = i.previous();
0N/A } while (--pos > index);
0N/A }
0N/A return obj;
0N/A }
0N/A
0N/A /**
0N/A * Searches the specified list for the specified object using the binary
0N/A * search algorithm. The list must be sorted into ascending order
0N/A * according to the specified comparator (as by the
0N/A * {@link #sort(List, Comparator) sort(List, Comparator)}
0N/A * method), prior to making this call. If it is
0N/A * not sorted, the results are undefined. If the list contains multiple
0N/A * elements equal to the specified object, there is no guarantee which one
0N/A * will be found.
0N/A *
0N/A * <p>This method runs in log(n) time for a "random access" list (which
0N/A * provides near-constant-time positional access). If the specified list
0N/A * does not implement the {@link RandomAccess} interface and is large,
0N/A * this method will do an iterator-based binary search that performs
0N/A * O(n) link traversals and O(log n) element comparisons.
0N/A *
0N/A * @param list the list to be searched.
0N/A * @param key the key to be searched for.
0N/A * @param c the comparator by which the list is ordered.
0N/A * A <tt>null</tt> value indicates that the elements'
0N/A * {@linkplain Comparable natural ordering} should be used.
0N/A * @return the index of the search key, if it is contained in the list;
0N/A * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
0N/A * <i>insertion point</i> is defined as the point at which the
0N/A * key would be inserted into the list: the index of the first
0N/A * element greater than the key, or <tt>list.size()</tt> if all
0N/A * elements in the list are less than the specified key. Note
0N/A * that this guarantees that the return value will be &gt;= 0 if
0N/A * and only if the key is found.
0N/A * @throws ClassCastException if the list contains elements that are not
0N/A * <i>mutually comparable</i> using the specified comparator,
0N/A * or the search key is not mutually comparable with the
0N/A * elements of the list using this comparator.
0N/A */
0N/A public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) {
0N/A if (c==null)
0N/A return binarySearch((List) list, key);
0N/A
0N/A if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
0N/A return Collections.indexedBinarySearch(list, key, c);
0N/A else
0N/A return Collections.iteratorBinarySearch(list, key, c);
0N/A }
0N/A
0N/A private static <T> int indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {
0N/A int low = 0;
0N/A int high = l.size()-1;
0N/A
0N/A while (low <= high) {
0N/A int mid = (low + high) >>> 1;
0N/A T midVal = l.get(mid);
0N/A int cmp = c.compare(midVal, key);
0N/A
0N/A if (cmp < 0)
0N/A low = mid + 1;
0N/A else if (cmp > 0)
0N/A high = mid - 1;
0N/A else
0N/A return mid; // key found
0N/A }
0N/A return -(low + 1); // key not found
0N/A }
0N/A
0N/A private static <T> int iteratorBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {
0N/A int low = 0;
0N/A int high = l.size()-1;
0N/A ListIterator<? extends T> i = l.listIterator();
0N/A
0N/A while (low <= high) {
0N/A int mid = (low + high) >>> 1;
0N/A T midVal = get(i, mid);
0N/A int cmp = c.compare(midVal, key);
0N/A
0N/A if (cmp < 0)
0N/A low = mid + 1;
0N/A else if (cmp > 0)
0N/A high = mid - 1;
0N/A else
0N/A return mid; // key found
0N/A }
0N/A return -(low + 1); // key not found
0N/A }
0N/A
0N/A private interface SelfComparable extends Comparable<SelfComparable> {}
0N/A
0N/A
0N/A /**
0N/A * Reverses the order of the elements in the specified list.<p>
0N/A *
0N/A * This method runs in linear time.
0N/A *
0N/A * @param list the list whose elements are to be reversed.
0N/A * @throws UnsupportedOperationException if the specified list or
0N/A * its list-iterator does not support the <tt>set</tt> operation.
0N/A */
0N/A public static void reverse(List<?> list) {
0N/A int size = list.size();
0N/A if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
0N/A for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
0N/A swap(list, i, j);
0N/A } else {
0N/A ListIterator fwd = list.listIterator();
0N/A ListIterator rev = list.listIterator(size);
0N/A for (int i=0, mid=list.size()>>1; i<mid; i++) {
0N/A Object tmp = fwd.next();
0N/A fwd.set(rev.previous());
0N/A rev.set(tmp);
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Randomly permutes the specified list using a default source of
0N/A * randomness. All permutations occur with approximately equal
0N/A * likelihood.<p>
0N/A *
0N/A * The hedge "approximately" is used in the foregoing description because
0N/A * default source of randomness is only approximately an unbiased source
0N/A * of independently chosen bits. If it were a perfect source of randomly
0N/A * chosen bits, then the algorithm would choose permutations with perfect
0N/A * uniformity.<p>
0N/A *
0N/A * This implementation traverses the list backwards, from the last element
0N/A * up to the second, repeatedly swapping a randomly selected element into
0N/A * the "current position". Elements are randomly selected from the
0N/A * portion of the list that runs from the first element to the current
0N/A * position, inclusive.<p>
0N/A *
0N/A * This method runs in linear time. If the specified list does not
0N/A * implement the {@link RandomAccess} interface and is large, this
0N/A * implementation dumps the specified list into an array before shuffling
0N/A * it, and dumps the shuffled array back into the list. This avoids the
0N/A * quadratic behavior that would result from shuffling a "sequential
0N/A * access" list in place.
0N/A *
0N/A * @param list the list to be shuffled.
0N/A * @throws UnsupportedOperationException if the specified list or
0N/A * its list-iterator does not support the <tt>set</tt> operation.
0N/A */
0N/A public static void shuffle(List<?> list) {
2468N/A Random rnd = r;
2468N/A if (rnd == null)
2468N/A r = rnd = new Random();
2468N/A shuffle(list, rnd);
0N/A }
0N/A private static Random r;
0N/A
0N/A /**
0N/A * Randomly permute the specified list using the specified source of
0N/A * randomness. All permutations occur with equal likelihood
0N/A * assuming that the source of randomness is fair.<p>
0N/A *
0N/A * This implementation traverses the list backwards, from the last element
0N/A * up to the second, repeatedly swapping a randomly selected element into
0N/A * the "current position". Elements are randomly selected from the
0N/A * portion of the list that runs from the first element to the current
0N/A * position, inclusive.<p>
0N/A *
0N/A * This method runs in linear time. If the specified list does not
0N/A * implement the {@link RandomAccess} interface and is large, this
0N/A * implementation dumps the specified list into an array before shuffling
0N/A * it, and dumps the shuffled array back into the list. This avoids the
0N/A * quadratic behavior that would result from shuffling a "sequential
0N/A * access" list in place.
0N/A *
0N/A * @param list the list to be shuffled.
0N/A * @param rnd the source of randomness to use to shuffle the list.
0N/A * @throws UnsupportedOperationException if the specified list or its
0N/A * list-iterator does not support the <tt>set</tt> operation.
0N/A */
0N/A public static void shuffle(List<?> list, Random rnd) {
0N/A int size = list.size();
0N/A if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
0N/A for (int i=size; i>1; i--)
0N/A swap(list, i-1, rnd.nextInt(i));
0N/A } else {
0N/A Object arr[] = list.toArray();
0N/A
0N/A // Shuffle array
0N/A for (int i=size; i>1; i--)
0N/A swap(arr, i-1, rnd.nextInt(i));
0N/A
0N/A // Dump array back into list
0N/A ListIterator it = list.listIterator();
0N/A for (int i=0; i<arr.length; i++) {
0N/A it.next();
0N/A it.set(arr[i]);
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Swaps the elements at the specified positions in the specified list.
0N/A * (If the specified positions are equal, invoking this method leaves
0N/A * the list unchanged.)
0N/A *
0N/A * @param list The list in which to swap elements.
0N/A * @param i the index of one element to be swapped.
0N/A * @param j the index of the other element to be swapped.
0N/A * @throws IndexOutOfBoundsException if either <tt>i</tt> or <tt>j</tt>
0N/A * is out of range (i &lt; 0 || i &gt;= list.size()
0N/A * || j &lt; 0 || j &gt;= list.size()).
0N/A * @since 1.4
0N/A */
0N/A public static void swap(List<?> list, int i, int j) {
0N/A final List l = list;
0N/A l.set(i, l.set(j, l.get(i)));
0N/A }
0N/A
0N/A /**
0N/A * Swaps the two specified elements in the specified array.
0N/A */
0N/A private static void swap(Object[] arr, int i, int j) {
0N/A Object tmp = arr[i];
0N/A arr[i] = arr[j];
0N/A arr[j] = tmp;
0N/A }
0N/A
0N/A /**
0N/A * Replaces all of the elements of the specified list with the specified
0N/A * element. <p>
0N/A *
0N/A * This method runs in linear time.
0N/A *
0N/A * @param list the list to be filled with the specified element.
0N/A * @param obj The element with which to fill the specified list.
0N/A * @throws UnsupportedOperationException if the specified list or its
0N/A * list-iterator does not support the <tt>set</tt> operation.
0N/A */
0N/A public static <T> void fill(List<? super T> list, T obj) {
0N/A int size = list.size();
0N/A
0N/A if (size < FILL_THRESHOLD || list instanceof RandomAccess) {
0N/A for (int i=0; i<size; i++)
0N/A list.set(i, obj);
0N/A } else {
0N/A ListIterator<? super T> itr = list.listIterator();
0N/A for (int i=0; i<size; i++) {
0N/A itr.next();
0N/A itr.set(obj);
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Copies all of the elements from one list into another. After the
0N/A * operation, the index of each copied element in the destination list
0N/A * will be identical to its index in the source list. The destination
0N/A * list must be at least as long as the source list. If it is longer, the
0N/A * remaining elements in the destination list are unaffected. <p>
0N/A *
0N/A * This method runs in linear time.
0N/A *
0N/A * @param dest The destination list.
0N/A * @param src The source list.
0N/A * @throws IndexOutOfBoundsException if the destination list is too small
0N/A * to contain the entire source List.
0N/A * @throws UnsupportedOperationException if the destination list's
0N/A * list-iterator does not support the <tt>set</tt> operation.
0N/A */
0N/A public static <T> void copy(List<? super T> dest, List<? extends T> src) {
0N/A int srcSize = src.size();
0N/A if (srcSize > dest.size())
0N/A throw new IndexOutOfBoundsException("Source does not fit in dest");
0N/A
0N/A if (srcSize < COPY_THRESHOLD ||
0N/A (src instanceof RandomAccess && dest instanceof RandomAccess)) {
0N/A for (int i=0; i<srcSize; i++)
0N/A dest.set(i, src.get(i));
0N/A } else {
0N/A ListIterator<? super T> di=dest.listIterator();
0N/A ListIterator<? extends T> si=src.listIterator();
0N/A for (int i=0; i<srcSize; i++) {
0N/A di.next();
0N/A di.set(si.next());
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns the minimum element of the given collection, according to the
0N/A * <i>natural ordering</i> of its elements. All elements in the
0N/A * collection must implement the <tt>Comparable</tt> interface.
0N/A * Furthermore, all elements in the collection must be <i>mutually
0N/A * comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a
0N/A * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
0N/A * <tt>e2</tt> in the collection).<p>
0N/A *
0N/A * This method iterates over the entire collection, hence it requires
0N/A * time proportional to the size of the collection.
0N/A *
0N/A * @param coll the collection whose minimum element is to be determined.
0N/A * @return the minimum element of the given collection, according
0N/A * to the <i>natural ordering</i> of its elements.
0N/A * @throws ClassCastException if the collection contains elements that are
0N/A * not <i>mutually comparable</i> (for example, strings and
0N/A * integers).
0N/A * @throws NoSuchElementException if the collection is empty.
0N/A * @see Comparable
0N/A */
0N/A public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
0N/A Iterator<? extends T> i = coll.iterator();
0N/A T candidate = i.next();
0N/A
0N/A while (i.hasNext()) {
0N/A T next = i.next();
0N/A if (next.compareTo(candidate) < 0)
0N/A candidate = next;
0N/A }
0N/A return candidate;
0N/A }
0N/A
0N/A /**
0N/A * Returns the minimum element of the given collection, according to the
0N/A * order induced by the specified comparator. All elements in the
0N/A * collection must be <i>mutually comparable</i> by the specified
0N/A * comparator (that is, <tt>comp.compare(e1, e2)</tt> must not throw a
0N/A * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
0N/A * <tt>e2</tt> in the collection).<p>
0N/A *
0N/A * This method iterates over the entire collection, hence it requires
0N/A * time proportional to the size of the collection.
0N/A *
0N/A * @param coll the collection whose minimum element is to be determined.
0N/A * @param comp the comparator with which to determine the minimum element.
0N/A * A <tt>null</tt> value indicates that the elements' <i>natural
0N/A * ordering</i> should be used.
0N/A * @return the minimum element of the given collection, according
0N/A * to the specified comparator.
0N/A * @throws ClassCastException if the collection contains elements that are
0N/A * not <i>mutually comparable</i> using the specified comparator.
0N/A * @throws NoSuchElementException if the collection is empty.
0N/A * @see Comparable
0N/A */
0N/A public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {
0N/A if (comp==null)
0N/A return (T)min((Collection<SelfComparable>) (Collection) coll);
0N/A
0N/A Iterator<? extends T> i = coll.iterator();
0N/A T candidate = i.next();
0N/A
0N/A while (i.hasNext()) {
0N/A T next = i.next();
0N/A if (comp.compare(next, candidate) < 0)
0N/A candidate = next;
0N/A }
0N/A return candidate;
0N/A }
0N/A
0N/A /**
0N/A * Returns the maximum element of the given collection, according to the
0N/A * <i>natural ordering</i> of its elements. All elements in the
0N/A * collection must implement the <tt>Comparable</tt> interface.
0N/A * Furthermore, all elements in the collection must be <i>mutually
0N/A * comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a
0N/A * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
0N/A * <tt>e2</tt> in the collection).<p>
0N/A *
0N/A * This method iterates over the entire collection, hence it requires
0N/A * time proportional to the size of the collection.
0N/A *
0N/A * @param coll the collection whose maximum element is to be determined.
0N/A * @return the maximum element of the given collection, according
0N/A * to the <i>natural ordering</i> of its elements.
0N/A * @throws ClassCastException if the collection contains elements that are
0N/A * not <i>mutually comparable</i> (for example, strings and
0N/A * integers).
0N/A * @throws NoSuchElementException if the collection is empty.
0N/A * @see Comparable
0N/A */
0N/A public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
0N/A Iterator<? extends T> i = coll.iterator();
0N/A T candidate = i.next();
0N/A
0N/A while (i.hasNext()) {
0N/A T next = i.next();
0N/A if (next.compareTo(candidate) > 0)
0N/A candidate = next;
0N/A }
0N/A return candidate;
0N/A }
0N/A
0N/A /**
0N/A * Returns the maximum element of the given collection, according to the
0N/A * order induced by the specified comparator. All elements in the
0N/A * collection must be <i>mutually comparable</i> by the specified
0N/A * comparator (that is, <tt>comp.compare(e1, e2)</tt> must not throw a
0N/A * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
0N/A * <tt>e2</tt> in the collection).<p>
0N/A *
0N/A * This method iterates over the entire collection, hence it requires
0N/A * time proportional to the size of the collection.
0N/A *
0N/A * @param coll the collection whose maximum element is to be determined.
0N/A * @param comp the comparator with which to determine the maximum element.
0N/A * A <tt>null</tt> value indicates that the elements' <i>natural
0N/A * ordering</i> should be used.
0N/A * @return the maximum element of the given collection, according
0N/A * to the specified comparator.
0N/A * @throws ClassCastException if the collection contains elements that are
0N/A * not <i>mutually comparable</i> using the specified comparator.
0N/A * @throws NoSuchElementException if the collection is empty.
0N/A * @see Comparable
0N/A */
0N/A public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {
0N/A if (comp==null)
0N/A return (T)max((Collection<SelfComparable>) (Collection) coll);
0N/A
0N/A Iterator<? extends T> i = coll.iterator();
0N/A T candidate = i.next();
0N/A
0N/A while (i.hasNext()) {
0N/A T next = i.next();
0N/A if (comp.compare(next, candidate) > 0)
0N/A candidate = next;
0N/A }
0N/A return candidate;
0N/A }
0N/A
0N/A /**
0N/A * Rotates the elements in the specified list by the specified distance.
0N/A * After calling this method, the element at index <tt>i</tt> will be
0N/A * the element previously at index <tt>(i - distance)</tt> mod
0N/A * <tt>list.size()</tt>, for all values of <tt>i</tt> between <tt>0</tt>
0N/A * and <tt>list.size()-1</tt>, inclusive. (This method has no effect on
0N/A * the size of the list.)
0N/A *
0N/A * <p>For example, suppose <tt>list</tt> comprises<tt> [t, a, n, k, s]</tt>.
0N/A * After invoking <tt>Collections.rotate(list, 1)</tt> (or
0N/A * <tt>Collections.rotate(list, -4)</tt>), <tt>list</tt> will comprise
0N/A * <tt>[s, t, a, n, k]</tt>.
0N/A *
0N/A * <p>Note that this method can usefully be applied to sublists to
0N/A * move one or more elements within a list while preserving the
0N/A * order of the remaining elements. For example, the following idiom
0N/A * moves the element at index <tt>j</tt> forward to position
0N/A * <tt>k</tt> (which must be greater than or equal to <tt>j</tt>):
0N/A * <pre>
0N/A * Collections.rotate(list.subList(j, k+1), -1);
0N/A * </pre>
0N/A * To make this concrete, suppose <tt>list</tt> comprises
0N/A * <tt>[a, b, c, d, e]</tt>. To move the element at index <tt>1</tt>
0N/A * (<tt>b</tt>) forward two positions, perform the following invocation:
0N/A * <pre>
0N/A * Collections.rotate(l.subList(1, 4), -1);
0N/A * </pre>
0N/A * The resulting list is <tt>[a, c, d, b, e]</tt>.
0N/A *
0N/A * <p>To move more than one element forward, increase the absolute value
0N/A * of the rotation distance. To move elements backward, use a positive
0N/A * shift distance.
0N/A *
0N/A * <p>If the specified list is small or implements the {@link
0N/A * RandomAccess} interface, this implementation exchanges the first
0N/A * element into the location it should go, and then repeatedly exchanges
0N/A * the displaced element into the location it should go until a displaced
0N/A * element is swapped into the first element. If necessary, the process
0N/A * is repeated on the second and successive elements, until the rotation
0N/A * is complete. If the specified list is large and doesn't implement the
0N/A * <tt>RandomAccess</tt> interface, this implementation breaks the
0N/A * list into two sublist views around index <tt>-distance mod size</tt>.
0N/A * Then the {@link #reverse(List)} method is invoked on each sublist view,
0N/A * and finally it is invoked on the entire list. For a more complete
0N/A * description of both algorithms, see Section 2.3 of Jon Bentley's
0N/A * <i>Programming Pearls</i> (Addison-Wesley, 1986).
0N/A *
0N/A * @param list the list to be rotated.
0N/A * @param distance the distance to rotate the list. There are no
0N/A * constraints on this value; it may be zero, negative, or
0N/A * greater than <tt>list.size()</tt>.
0N/A * @throws UnsupportedOperationException if the specified list or
0N/A * its list-iterator does not support the <tt>set</tt> operation.
0N/A * @since 1.4
0N/A */
0N/A public static void rotate(List<?> list, int distance) {
0N/A if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD)
0N/A rotate1(list, distance);
0N/A else
0N/A rotate2(list, distance);
0N/A }
0N/A
0N/A private static <T> void rotate1(List<T> list, int distance) {
0N/A int size = list.size();
0N/A if (size == 0)
0N/A return;
0N/A distance = distance % size;
0N/A if (distance < 0)
0N/A distance += size;
0N/A if (distance == 0)
0N/A return;
0N/A
0N/A for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) {
0N/A T displaced = list.get(cycleStart);
0N/A int i = cycleStart;
0N/A do {
0N/A i += distance;
0N/A if (i >= size)
0N/A i -= size;
0N/A displaced = list.set(i, displaced);
0N/A nMoved ++;
3203N/A } while (i != cycleStart);
0N/A }
0N/A }
0N/A
0N/A private static void rotate2(List<?> list, int distance) {
0N/A int size = list.size();
0N/A if (size == 0)
0N/A return;
0N/A int mid = -distance % size;
0N/A if (mid < 0)
0N/A mid += size;
0N/A if (mid == 0)
0N/A return;
0N/A
0N/A reverse(list.subList(0, mid));
0N/A reverse(list.subList(mid, size));
0N/A reverse(list);
0N/A }
0N/A
0N/A /**
0N/A * Replaces all occurrences of one specified value in a list with another.
0N/A * More formally, replaces with <tt>newVal</tt> each element <tt>e</tt>
0N/A * in <tt>list</tt> such that
0N/A * <tt>(oldVal==null ? e==null : oldVal.equals(e))</tt>.
0N/A * (This method has no effect on the size of the list.)
0N/A *
0N/A * @param list the list in which replacement is to occur.
0N/A * @param oldVal the old value to be replaced.
0N/A * @param newVal the new value with which <tt>oldVal</tt> is to be
0N/A * replaced.
0N/A * @return <tt>true</tt> if <tt>list</tt> contained one or more elements
0N/A * <tt>e</tt> such that
0N/A * <tt>(oldVal==null ? e==null : oldVal.equals(e))</tt>.
0N/A * @throws UnsupportedOperationException if the specified list or
0N/A * its list-iterator does not support the <tt>set</tt> operation.
0N/A * @since 1.4
0N/A */
0N/A public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) {
0N/A boolean result = false;
0N/A int size = list.size();
0N/A if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) {
0N/A if (oldVal==null) {
0N/A for (int i=0; i<size; i++) {
0N/A if (list.get(i)==null) {
0N/A list.set(i, newVal);
0N/A result = true;
0N/A }
0N/A }
0N/A } else {
0N/A for (int i=0; i<size; i++) {
0N/A if (oldVal.equals(list.get(i))) {
0N/A list.set(i, newVal);
0N/A result = true;
0N/A }
0N/A }
0N/A }
0N/A } else {
0N/A ListIterator<T> itr=list.listIterator();
0N/A if (oldVal==null) {
0N/A for (int i=0; i<size; i++) {
0N/A if (itr.next()==null) {
0N/A itr.set(newVal);
0N/A result = true;
0N/A }
0N/A }
0N/A } else {
0N/A for (int i=0; i<size; i++) {
0N/A if (oldVal.equals(itr.next())) {
0N/A itr.set(newVal);
0N/A result = true;
0N/A }
0N/A }
0N/A }
0N/A }
0N/A return result;
0N/A }
0N/A
0N/A /**
0N/A * Returns the starting position of the first occurrence of the specified
0N/A * target list within the specified source list, or -1 if there is no
0N/A * such occurrence. More formally, returns the lowest index <tt>i</tt>
0N/A * such that <tt>source.subList(i, i+target.size()).equals(target)</tt>,
0N/A * or -1 if there is no such index. (Returns -1 if
0N/A * <tt>target.size() > source.size()</tt>.)
0N/A *
0N/A * <p>This implementation uses the "brute force" technique of scanning
0N/A * over the source list, looking for a match with the target at each
0N/A * location in turn.
0N/A *
0N/A * @param source the list in which to search for the first occurrence
0N/A * of <tt>target</tt>.
0N/A * @param target the list to search for as a subList of <tt>source</tt>.
0N/A * @return the starting position of the first occurrence of the specified
0N/A * target list within the specified source list, or -1 if there
0N/A * is no such occurrence.
0N/A * @since 1.4
0N/A */
0N/A public static int indexOfSubList(List<?> source, List<?> target) {
0N/A int sourceSize = source.size();
0N/A int targetSize = target.size();
0N/A int maxCandidate = sourceSize - targetSize;
0N/A
0N/A if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
0N/A (source instanceof RandomAccess&&target instanceof RandomAccess)) {
0N/A nextCand:
0N/A for (int candidate = 0; candidate <= maxCandidate; candidate++) {
0N/A for (int i=0, j=candidate; i<targetSize; i++, j++)
0N/A if (!eq(target.get(i), source.get(j)))
0N/A continue nextCand; // Element mismatch, try next cand
0N/A return candidate; // All elements of candidate matched target
0N/A }
0N/A } else { // Iterator version of above algorithm
0N/A ListIterator<?> si = source.listIterator();
0N/A nextCand:
0N/A for (int candidate = 0; candidate <= maxCandidate; candidate++) {
0N/A ListIterator<?> ti = target.listIterator();
0N/A for (int i=0; i<targetSize; i++) {
0N/A if (!eq(ti.next(), si.next())) {
0N/A // Back up source iterator to next candidate
0N/A for (int j=0; j<i; j++)
0N/A si.previous();
0N/A continue nextCand;
0N/A }
0N/A }
0N/A return candidate;
0N/A }
0N/A }
0N/A return -1; // No candidate matched the target
0N/A }
0N/A
0N/A /**
0N/A * Returns the starting position of the last occurrence of the specified
0N/A * target list within the specified source list, or -1 if there is no such
0N/A * occurrence. More formally, returns the highest index <tt>i</tt>
0N/A * such that <tt>source.subList(i, i+target.size()).equals(target)</tt>,
0N/A * or -1 if there is no such index. (Returns -1 if
0N/A * <tt>target.size() > source.size()</tt>.)
0N/A *
0N/A * <p>This implementation uses the "brute force" technique of iterating
0N/A * over the source list, looking for a match with the target at each
0N/A * location in turn.
0N/A *
0N/A * @param source the list in which to search for the last occurrence
0N/A * of <tt>target</tt>.
0N/A * @param target the list to search for as a subList of <tt>source</tt>.
0N/A * @return the starting position of the last occurrence of the specified
0N/A * target list within the specified source list, or -1 if there
0N/A * is no such occurrence.
0N/A * @since 1.4
0N/A */
0N/A public static int lastIndexOfSubList(List<?> source, List<?> target) {
0N/A int sourceSize = source.size();
0N/A int targetSize = target.size();
0N/A int maxCandidate = sourceSize - targetSize;
0N/A
0N/A if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
0N/A source instanceof RandomAccess) { // Index access version
0N/A nextCand:
0N/A for (int candidate = maxCandidate; candidate >= 0; candidate--) {
0N/A for (int i=0, j=candidate; i<targetSize; i++, j++)
0N/A if (!eq(target.get(i), source.get(j)))
0N/A continue nextCand; // Element mismatch, try next cand
0N/A return candidate; // All elements of candidate matched target
0N/A }
0N/A } else { // Iterator version of above algorithm
0N/A if (maxCandidate < 0)
0N/A return -1;
0N/A ListIterator<?> si = source.listIterator(maxCandidate);
0N/A nextCand:
0N/A for (int candidate = maxCandidate; candidate >= 0; candidate--) {
0N/A ListIterator<?> ti = target.listIterator();
0N/A for (int i=0; i<targetSize; i++) {
0N/A if (!eq(ti.next(), si.next())) {
0N/A if (candidate != 0) {
0N/A // Back up source iterator to next candidate
0N/A for (int j=0; j<=i+1; j++)
0N/A si.previous();
0N/A }
0N/A continue nextCand;
0N/A }
0N/A }
0N/A return candidate;
0N/A }
0N/A }
0N/A return -1; // No candidate matched the target
0N/A }
0N/A
0N/A
0N/A // Unmodifiable Wrappers
0N/A
0N/A /**
0N/A * Returns an unmodifiable view of the specified collection. This method
0N/A * allows modules to provide users with "read-only" access to internal
0N/A * collections. Query operations on the returned collection "read through"
0N/A * to the specified collection, and attempts to modify the returned
0N/A * collection, whether direct or via its iterator, result in an
0N/A * <tt>UnsupportedOperationException</tt>.<p>
0N/A *
0N/A * The returned collection does <i>not</i> pass the hashCode and equals
0N/A * operations through to the backing collection, but relies on
0N/A * <tt>Object</tt>'s <tt>equals</tt> and <tt>hashCode</tt> methods. This
0N/A * is necessary to preserve the contracts of these operations in the case
0N/A * that the backing collection is a set or a list.<p>
0N/A *
0N/A * The returned collection will be serializable if the specified collection
0N/A * is serializable.
0N/A *
0N/A * @param c the collection for which an unmodifiable view is to be
0N/A * returned.
0N/A * @return an unmodifiable view of the specified collection.
0N/A */
0N/A public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
3323N/A return new UnmodifiableCollection<>(c);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class UnmodifiableCollection<E> implements Collection<E>, Serializable {
0N/A private static final long serialVersionUID = 1820017752578914078L;
0N/A
0N/A final Collection<? extends E> c;
0N/A
0N/A UnmodifiableCollection(Collection<? extends E> c) {
0N/A if (c==null)
0N/A throw new NullPointerException();
0N/A this.c = c;
0N/A }
0N/A
0N/A public int size() {return c.size();}
0N/A public boolean isEmpty() {return c.isEmpty();}
0N/A public boolean contains(Object o) {return c.contains(o);}
0N/A public Object[] toArray() {return c.toArray();}
0N/A public <T> T[] toArray(T[] a) {return c.toArray(a);}
0N/A public String toString() {return c.toString();}
0N/A
0N/A public Iterator<E> iterator() {
0N/A return new Iterator<E>() {
0N/A private final Iterator<? extends E> i = c.iterator();
0N/A
0N/A public boolean hasNext() {return i.hasNext();}
0N/A public E next() {return i.next();}
0N/A public void remove() {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A };
0N/A }
0N/A
0N/A public boolean add(E e) {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A public boolean remove(Object o) {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A
0N/A public boolean containsAll(Collection<?> coll) {
0N/A return c.containsAll(coll);
0N/A }
0N/A public boolean addAll(Collection<? extends E> coll) {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A public boolean removeAll(Collection<?> coll) {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A public boolean retainAll(Collection<?> coll) {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A public void clear() {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns an unmodifiable view of the specified set. This method allows
0N/A * modules to provide users with "read-only" access to internal sets.
0N/A * Query operations on the returned set "read through" to the specified
0N/A * set, and attempts to modify the returned set, whether direct or via its
0N/A * iterator, result in an <tt>UnsupportedOperationException</tt>.<p>
0N/A *
0N/A * The returned set will be serializable if the specified set
0N/A * is serializable.
0N/A *
0N/A * @param s the set for which an unmodifiable view is to be returned.
0N/A * @return an unmodifiable view of the specified set.
0N/A */
0N/A public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
3323N/A return new UnmodifiableSet<>(s);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
0N/A implements Set<E>, Serializable {
0N/A private static final long serialVersionUID = -9215047833775013803L;
0N/A
0N/A UnmodifiableSet(Set<? extends E> s) {super(s);}
0N/A public boolean equals(Object o) {return o == this || c.equals(o);}
0N/A public int hashCode() {return c.hashCode();}
0N/A }
0N/A
0N/A /**
0N/A * Returns an unmodifiable view of the specified sorted set. This method
0N/A * allows modules to provide users with "read-only" access to internal
0N/A * sorted sets. Query operations on the returned sorted set "read
0N/A * through" to the specified sorted set. Attempts to modify the returned
0N/A * sorted set, whether direct, via its iterator, or via its
0N/A * <tt>subSet</tt>, <tt>headSet</tt>, or <tt>tailSet</tt> views, result in
0N/A * an <tt>UnsupportedOperationException</tt>.<p>
0N/A *
0N/A * The returned sorted set will be serializable if the specified sorted set
0N/A * is serializable.
0N/A *
0N/A * @param s the sorted set for which an unmodifiable view is to be
0N/A * returned.
0N/A * @return an unmodifiable view of the specified sorted set.
0N/A */
0N/A public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
3323N/A return new UnmodifiableSortedSet<>(s);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class UnmodifiableSortedSet<E>
0N/A extends UnmodifiableSet<E>
0N/A implements SortedSet<E>, Serializable {
0N/A private static final long serialVersionUID = -4929149591599911165L;
0N/A private final SortedSet<E> ss;
0N/A
0N/A UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}
0N/A
0N/A public Comparator<? super E> comparator() {return ss.comparator();}
0N/A
0N/A public SortedSet<E> subSet(E fromElement, E toElement) {
3323N/A return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement));
0N/A }
0N/A public SortedSet<E> headSet(E toElement) {
3323N/A return new UnmodifiableSortedSet<>(ss.headSet(toElement));
0N/A }
0N/A public SortedSet<E> tailSet(E fromElement) {
3323N/A return new UnmodifiableSortedSet<>(ss.tailSet(fromElement));
0N/A }
0N/A
0N/A public E first() {return ss.first();}
0N/A public E last() {return ss.last();}
0N/A }
0N/A
0N/A /**
0N/A * Returns an unmodifiable view of the specified list. This method allows
0N/A * modules to provide users with "read-only" access to internal
0N/A * lists. Query operations on the returned list "read through" to the
0N/A * specified list, and attempts to modify the returned list, whether
0N/A * direct or via its iterator, result in an
0N/A * <tt>UnsupportedOperationException</tt>.<p>
0N/A *
0N/A * The returned list will be serializable if the specified list
0N/A * is serializable. Similarly, the returned list will implement
0N/A * {@link RandomAccess} if the specified list does.
0N/A *
0N/A * @param list the list for which an unmodifiable view is to be returned.
0N/A * @return an unmodifiable view of the specified list.
0N/A */
0N/A public static <T> List<T> unmodifiableList(List<? extends T> list) {
0N/A return (list instanceof RandomAccess ?
3323N/A new UnmodifiableRandomAccessList<>(list) :
3323N/A new UnmodifiableList<>(list));
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class UnmodifiableList<E> extends UnmodifiableCollection<E>
0N/A implements List<E> {
0N/A private static final long serialVersionUID = -283967356065247728L;
0N/A final List<? extends E> list;
0N/A
0N/A UnmodifiableList(List<? extends E> list) {
0N/A super(list);
0N/A this.list = list;
0N/A }
0N/A
0N/A public boolean equals(Object o) {return o == this || list.equals(o);}
0N/A public int hashCode() {return list.hashCode();}
0N/A
0N/A public E get(int index) {return list.get(index);}
0N/A public E set(int index, E element) {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A public void add(int index, E element) {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A public E remove(int index) {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A public int indexOf(Object o) {return list.indexOf(o);}
0N/A public int lastIndexOf(Object o) {return list.lastIndexOf(o);}
0N/A public boolean addAll(int index, Collection<? extends E> c) {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A public ListIterator<E> listIterator() {return listIterator(0);}
0N/A
0N/A public ListIterator<E> listIterator(final int index) {
0N/A return new ListIterator<E>() {
0N/A private final ListIterator<? extends E> i
0N/A = list.listIterator(index);
0N/A
0N/A public boolean hasNext() {return i.hasNext();}
0N/A public E next() {return i.next();}
0N/A public boolean hasPrevious() {return i.hasPrevious();}
0N/A public E previous() {return i.previous();}
0N/A public int nextIndex() {return i.nextIndex();}
0N/A public int previousIndex() {return i.previousIndex();}
0N/A
0N/A public void remove() {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A public void set(E e) {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A public void add(E e) {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A };
0N/A }
0N/A
0N/A public List<E> subList(int fromIndex, int toIndex) {
3323N/A return new UnmodifiableList<>(list.subList(fromIndex, toIndex));
0N/A }
0N/A
0N/A /**
0N/A * UnmodifiableRandomAccessList instances are serialized as
0N/A * UnmodifiableList instances to allow them to be deserialized
0N/A * in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList).
0N/A * This method inverts the transformation. As a beneficial
0N/A * side-effect, it also grafts the RandomAccess marker onto
0N/A * UnmodifiableList instances that were serialized in pre-1.4 JREs.
0N/A *
0N/A * Note: Unfortunately, UnmodifiableRandomAccessList instances
0N/A * serialized in 1.4.1 and deserialized in 1.4 will become
0N/A * UnmodifiableList instances, as this method was missing in 1.4.
0N/A */
0N/A private Object readResolve() {
0N/A return (list instanceof RandomAccess
3323N/A ? new UnmodifiableRandomAccessList<>(list)
0N/A : this);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E>
0N/A implements RandomAccess
0N/A {
0N/A UnmodifiableRandomAccessList(List<? extends E> list) {
0N/A super(list);
0N/A }
0N/A
0N/A public List<E> subList(int fromIndex, int toIndex) {
3323N/A return new UnmodifiableRandomAccessList<>(
0N/A list.subList(fromIndex, toIndex));
0N/A }
0N/A
0N/A private static final long serialVersionUID = -2542308836966382001L;
0N/A
0N/A /**
0N/A * Allows instances to be deserialized in pre-1.4 JREs (which do
0N/A * not have UnmodifiableRandomAccessList). UnmodifiableList has
0N/A * a readResolve method that inverts this transformation upon
0N/A * deserialization.
0N/A */
0N/A private Object writeReplace() {
3323N/A return new UnmodifiableList<>(list);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns an unmodifiable view of the specified map. This method
0N/A * allows modules to provide users with "read-only" access to internal
0N/A * maps. Query operations on the returned map "read through"
0N/A * to the specified map, and attempts to modify the returned
0N/A * map, whether direct or via its collection views, result in an
0N/A * <tt>UnsupportedOperationException</tt>.<p>
0N/A *
0N/A * The returned map will be serializable if the specified map
0N/A * is serializable.
0N/A *
0N/A * @param m the map for which an unmodifiable view is to be returned.
0N/A * @return an unmodifiable view of the specified map.
0N/A */
0N/A public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
3323N/A return new UnmodifiableMap<>(m);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {
0N/A private static final long serialVersionUID = -1034234728574286014L;
0N/A
0N/A private final Map<? extends K, ? extends V> m;
0N/A
0N/A UnmodifiableMap(Map<? extends K, ? extends V> m) {
0N/A if (m==null)
0N/A throw new NullPointerException();
0N/A this.m = m;
0N/A }
0N/A
0N/A public int size() {return m.size();}
0N/A public boolean isEmpty() {return m.isEmpty();}
0N/A public boolean containsKey(Object key) {return m.containsKey(key);}
0N/A public boolean containsValue(Object val) {return m.containsValue(val);}
0N/A public V get(Object key) {return m.get(key);}
0N/A
0N/A public V put(K key, V value) {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A public V remove(Object key) {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A public void putAll(Map<? extends K, ? extends V> m) {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A public void clear() {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A
0N/A private transient Set<K> keySet = null;
0N/A private transient Set<Map.Entry<K,V>> entrySet = null;
0N/A private transient Collection<V> values = null;
0N/A
0N/A public Set<K> keySet() {
0N/A if (keySet==null)
0N/A keySet = unmodifiableSet(m.keySet());
0N/A return keySet;
0N/A }
0N/A
0N/A public Set<Map.Entry<K,V>> entrySet() {
0N/A if (entrySet==null)
3323N/A entrySet = new UnmodifiableEntrySet<>(m.entrySet());
0N/A return entrySet;
0N/A }
0N/A
0N/A public Collection<V> values() {
0N/A if (values==null)
0N/A values = unmodifiableCollection(m.values());
0N/A return values;
0N/A }
0N/A
0N/A public boolean equals(Object o) {return o == this || m.equals(o);}
0N/A public int hashCode() {return m.hashCode();}
0N/A public String toString() {return m.toString();}
0N/A
0N/A /**
0N/A * We need this class in addition to UnmodifiableSet as
0N/A * Map.Entries themselves permit modification of the backing Map
0N/A * via their setValue operation. This class is subtle: there are
0N/A * many possible attacks that must be thwarted.
0N/A *
0N/A * @serial include
0N/A */
0N/A static class UnmodifiableEntrySet<K,V>
0N/A extends UnmodifiableSet<Map.Entry<K,V>> {
0N/A private static final long serialVersionUID = 7854390611657943733L;
0N/A
0N/A UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) {
0N/A super((Set)s);
0N/A }
0N/A public Iterator<Map.Entry<K,V>> iterator() {
0N/A return new Iterator<Map.Entry<K,V>>() {
0N/A private final Iterator<? extends Map.Entry<? extends K, ? extends V>> i = c.iterator();
0N/A
0N/A public boolean hasNext() {
0N/A return i.hasNext();
0N/A }
0N/A public Map.Entry<K,V> next() {
3323N/A return new UnmodifiableEntry<>(i.next());
0N/A }
0N/A public void remove() {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A };
0N/A }
0N/A
0N/A public Object[] toArray() {
0N/A Object[] a = c.toArray();
0N/A for (int i=0; i<a.length; i++)
3323N/A a[i] = new UnmodifiableEntry<>((Map.Entry<K,V>)a[i]);
0N/A return a;
0N/A }
0N/A
0N/A public <T> T[] toArray(T[] a) {
0N/A // We don't pass a to c.toArray, to avoid window of
0N/A // vulnerability wherein an unscrupulous multithreaded client
0N/A // could get his hands on raw (unwrapped) Entries from c.
0N/A Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
0N/A
0N/A for (int i=0; i<arr.length; i++)
3323N/A arr[i] = new UnmodifiableEntry<>((Map.Entry<K,V>)arr[i]);
0N/A
0N/A if (arr.length > a.length)
0N/A return (T[])arr;
0N/A
0N/A System.arraycopy(arr, 0, a, 0, arr.length);
0N/A if (a.length > arr.length)
0N/A a[arr.length] = null;
0N/A return a;
0N/A }
0N/A
0N/A /**
0N/A * This method is overridden to protect the backing set against
0N/A * an object with a nefarious equals function that senses
0N/A * that the equality-candidate is Map.Entry and calls its
0N/A * setValue method.
0N/A */
0N/A public boolean contains(Object o) {
0N/A if (!(o instanceof Map.Entry))
0N/A return false;
0N/A return c.contains(
3323N/A new UnmodifiableEntry<>((Map.Entry<?,?>) o));
0N/A }
0N/A
0N/A /**
0N/A * The next two methods are overridden to protect against
0N/A * an unscrupulous List whose contains(Object o) method senses
0N/A * when o is a Map.Entry, and calls o.setValue.
0N/A */
0N/A public boolean containsAll(Collection<?> coll) {
3387N/A for (Object e : coll) {
3387N/A if (!contains(e)) // Invokes safe contains() above
0N/A return false;
3387N/A }
0N/A return true;
0N/A }
0N/A public boolean equals(Object o) {
0N/A if (o == this)
0N/A return true;
0N/A
0N/A if (!(o instanceof Set))
0N/A return false;
0N/A Set s = (Set) o;
0N/A if (s.size() != c.size())
0N/A return false;
0N/A return containsAll(s); // Invokes safe containsAll() above
0N/A }
0N/A
0N/A /**
0N/A * This "wrapper class" serves two purposes: it prevents
0N/A * the client from modifying the backing Map, by short-circuiting
0N/A * the setValue method, and it protects the backing Map against
0N/A * an ill-behaved Map.Entry that attempts to modify another
0N/A * Map Entry when asked to perform an equality check.
0N/A */
0N/A private static class UnmodifiableEntry<K,V> implements Map.Entry<K,V> {
0N/A private Map.Entry<? extends K, ? extends V> e;
0N/A
0N/A UnmodifiableEntry(Map.Entry<? extends K, ? extends V> e) {this.e = e;}
0N/A
3203N/A public K getKey() {return e.getKey();}
3203N/A public V getValue() {return e.getValue();}
0N/A public V setValue(V value) {
0N/A throw new UnsupportedOperationException();
0N/A }
3203N/A public int hashCode() {return e.hashCode();}
0N/A public boolean equals(Object o) {
4856N/A if (this == o)
4856N/A return true;
0N/A if (!(o instanceof Map.Entry))
0N/A return false;
0N/A Map.Entry t = (Map.Entry)o;
0N/A return eq(e.getKey(), t.getKey()) &&
0N/A eq(e.getValue(), t.getValue());
0N/A }
3203N/A public String toString() {return e.toString();}
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns an unmodifiable view of the specified sorted map. This method
0N/A * allows modules to provide users with "read-only" access to internal
0N/A * sorted maps. Query operations on the returned sorted map "read through"
0N/A * to the specified sorted map. Attempts to modify the returned
0N/A * sorted map, whether direct, via its collection views, or via its
0N/A * <tt>subMap</tt>, <tt>headMap</tt>, or <tt>tailMap</tt> views, result in
0N/A * an <tt>UnsupportedOperationException</tt>.<p>
0N/A *
0N/A * The returned sorted map will be serializable if the specified sorted map
0N/A * is serializable.
0N/A *
0N/A * @param m the sorted map for which an unmodifiable view is to be
0N/A * returned.
0N/A * @return an unmodifiable view of the specified sorted map.
0N/A */
0N/A public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {
3323N/A return new UnmodifiableSortedMap<>(m);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class UnmodifiableSortedMap<K,V>
0N/A extends UnmodifiableMap<K,V>
0N/A implements SortedMap<K,V>, Serializable {
0N/A private static final long serialVersionUID = -8806743815996713206L;
0N/A
0N/A private final SortedMap<K, ? extends V> sm;
0N/A
0N/A UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m;}
0N/A
0N/A public Comparator<? super K> comparator() {return sm.comparator();}
0N/A
0N/A public SortedMap<K,V> subMap(K fromKey, K toKey) {
3323N/A return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey));
0N/A }
0N/A public SortedMap<K,V> headMap(K toKey) {
3323N/A return new UnmodifiableSortedMap<>(sm.headMap(toKey));
0N/A }
0N/A public SortedMap<K,V> tailMap(K fromKey) {
3323N/A return new UnmodifiableSortedMap<>(sm.tailMap(fromKey));
0N/A }
0N/A
0N/A public K firstKey() {return sm.firstKey();}
0N/A public K lastKey() {return sm.lastKey();}
0N/A }
0N/A
0N/A
0N/A // Synch Wrappers
0N/A
0N/A /**
0N/A * Returns a synchronized (thread-safe) collection backed by the specified
0N/A * collection. In order to guarantee serial access, it is critical that
0N/A * <strong>all</strong> access to the backing collection is accomplished
0N/A * through the returned collection.<p>
0N/A *
0N/A * It is imperative that the user manually synchronize on the returned
0N/A * collection when iterating over it:
0N/A * <pre>
0N/A * Collection c = Collections.synchronizedCollection(myCollection);
0N/A * ...
3203N/A * synchronized (c) {
0N/A * Iterator i = c.iterator(); // Must be in the synchronized block
0N/A * while (i.hasNext())
0N/A * foo(i.next());
0N/A * }
0N/A * </pre>
0N/A * Failure to follow this advice may result in non-deterministic behavior.
0N/A *
0N/A * <p>The returned collection does <i>not</i> pass the <tt>hashCode</tt>
0N/A * and <tt>equals</tt> operations through to the backing collection, but
0N/A * relies on <tt>Object</tt>'s equals and hashCode methods. This is
0N/A * necessary to preserve the contracts of these operations in the case
0N/A * that the backing collection is a set or a list.<p>
0N/A *
0N/A * The returned collection will be serializable if the specified collection
0N/A * is serializable.
0N/A *
0N/A * @param c the collection to be "wrapped" in a synchronized collection.
0N/A * @return a synchronized view of the specified collection.
0N/A */
0N/A public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
3323N/A return new SynchronizedCollection<>(c);
0N/A }
0N/A
0N/A static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {
3323N/A return new SynchronizedCollection<>(c, mutex);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class SynchronizedCollection<E> implements Collection<E>, Serializable {
0N/A private static final long serialVersionUID = 3053995032091335093L;
0N/A
0N/A final Collection<E> c; // Backing Collection
0N/A final Object mutex; // Object on which to synchronize
0N/A
0N/A SynchronizedCollection(Collection<E> c) {
0N/A if (c==null)
0N/A throw new NullPointerException();
0N/A this.c = c;
0N/A mutex = this;
0N/A }
0N/A SynchronizedCollection(Collection<E> c, Object mutex) {
0N/A this.c = c;
0N/A this.mutex = mutex;
0N/A }
0N/A
0N/A public int size() {
3203N/A synchronized (mutex) {return c.size();}
0N/A }
0N/A public boolean isEmpty() {
3203N/A synchronized (mutex) {return c.isEmpty();}
0N/A }
0N/A public boolean contains(Object o) {
3203N/A synchronized (mutex) {return c.contains(o);}
0N/A }
0N/A public Object[] toArray() {
3203N/A synchronized (mutex) {return c.toArray();}
0N/A }
0N/A public <T> T[] toArray(T[] a) {
3203N/A synchronized (mutex) {return c.toArray(a);}
0N/A }
0N/A
0N/A public Iterator<E> iterator() {
0N/A return c.iterator(); // Must be manually synched by user!
0N/A }
0N/A
0N/A public boolean add(E e) {
3203N/A synchronized (mutex) {return c.add(e);}
0N/A }
0N/A public boolean remove(Object o) {
3203N/A synchronized (mutex) {return c.remove(o);}
0N/A }
0N/A
0N/A public boolean containsAll(Collection<?> coll) {
3203N/A synchronized (mutex) {return c.containsAll(coll);}
0N/A }
0N/A public boolean addAll(Collection<? extends E> coll) {
3203N/A synchronized (mutex) {return c.addAll(coll);}
0N/A }
0N/A public boolean removeAll(Collection<?> coll) {
3203N/A synchronized (mutex) {return c.removeAll(coll);}
0N/A }
0N/A public boolean retainAll(Collection<?> coll) {
3203N/A synchronized (mutex) {return c.retainAll(coll);}
0N/A }
0N/A public void clear() {
3203N/A synchronized (mutex) {c.clear();}
0N/A }
0N/A public String toString() {
3203N/A synchronized (mutex) {return c.toString();}
0N/A }
0N/A private void writeObject(ObjectOutputStream s) throws IOException {
3203N/A synchronized (mutex) {s.defaultWriteObject();}
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a synchronized (thread-safe) set backed by the specified
0N/A * set. In order to guarantee serial access, it is critical that
0N/A * <strong>all</strong> access to the backing set is accomplished
0N/A * through the returned set.<p>
0N/A *
0N/A * It is imperative that the user manually synchronize on the returned
0N/A * set when iterating over it:
0N/A * <pre>
0N/A * Set s = Collections.synchronizedSet(new HashSet());
0N/A * ...
3203N/A * synchronized (s) {
0N/A * Iterator i = s.iterator(); // Must be in the synchronized block
0N/A * while (i.hasNext())
0N/A * foo(i.next());
0N/A * }
0N/A * </pre>
0N/A * Failure to follow this advice may result in non-deterministic behavior.
0N/A *
0N/A * <p>The returned set will be serializable if the specified set is
0N/A * serializable.
0N/A *
0N/A * @param s the set to be "wrapped" in a synchronized set.
0N/A * @return a synchronized view of the specified set.
0N/A */
0N/A public static <T> Set<T> synchronizedSet(Set<T> s) {
3323N/A return new SynchronizedSet<>(s);
0N/A }
0N/A
0N/A static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {
3323N/A return new SynchronizedSet<>(s, mutex);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class SynchronizedSet<E>
0N/A extends SynchronizedCollection<E>
0N/A implements Set<E> {
0N/A private static final long serialVersionUID = 487447009682186044L;
0N/A
0N/A SynchronizedSet(Set<E> s) {
0N/A super(s);
0N/A }
0N/A SynchronizedSet(Set<E> s, Object mutex) {
0N/A super(s, mutex);
0N/A }
0N/A
0N/A public boolean equals(Object o) {
4856N/A if (this == o)
4856N/A return true;
3203N/A synchronized (mutex) {return c.equals(o);}
0N/A }
0N/A public int hashCode() {
3203N/A synchronized (mutex) {return c.hashCode();}
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a synchronized (thread-safe) sorted set backed by the specified
0N/A * sorted set. In order to guarantee serial access, it is critical that
0N/A * <strong>all</strong> access to the backing sorted set is accomplished
0N/A * through the returned sorted set (or its views).<p>
0N/A *
0N/A * It is imperative that the user manually synchronize on the returned
0N/A * sorted set when iterating over it or any of its <tt>subSet</tt>,
0N/A * <tt>headSet</tt>, or <tt>tailSet</tt> views.
0N/A * <pre>
0N/A * SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
0N/A * ...
3203N/A * synchronized (s) {
0N/A * Iterator i = s.iterator(); // Must be in the synchronized block
0N/A * while (i.hasNext())
0N/A * foo(i.next());
0N/A * }
0N/A * </pre>
0N/A * or:
0N/A * <pre>
0N/A * SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
0N/A * SortedSet s2 = s.headSet(foo);
0N/A * ...
3203N/A * synchronized (s) { // Note: s, not s2!!!
0N/A * Iterator i = s2.iterator(); // Must be in the synchronized block
0N/A * while (i.hasNext())
0N/A * foo(i.next());
0N/A * }
0N/A * </pre>
0N/A * Failure to follow this advice may result in non-deterministic behavior.
0N/A *
0N/A * <p>The returned sorted set will be serializable if the specified
0N/A * sorted set is serializable.
0N/A *
0N/A * @param s the sorted set to be "wrapped" in a synchronized sorted set.
0N/A * @return a synchronized view of the specified sorted set.
0N/A */
0N/A public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) {
3323N/A return new SynchronizedSortedSet<>(s);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class SynchronizedSortedSet<E>
0N/A extends SynchronizedSet<E>
0N/A implements SortedSet<E>
0N/A {
0N/A private static final long serialVersionUID = 8695801310862127406L;
0N/A
3203N/A private final SortedSet<E> ss;
0N/A
0N/A SynchronizedSortedSet(SortedSet<E> s) {
0N/A super(s);
0N/A ss = s;
0N/A }
0N/A SynchronizedSortedSet(SortedSet<E> s, Object mutex) {
0N/A super(s, mutex);
0N/A ss = s;
0N/A }
0N/A
0N/A public Comparator<? super E> comparator() {
3203N/A synchronized (mutex) {return ss.comparator();}
0N/A }
0N/A
0N/A public SortedSet<E> subSet(E fromElement, E toElement) {
3203N/A synchronized (mutex) {
3323N/A return new SynchronizedSortedSet<>(
0N/A ss.subSet(fromElement, toElement), mutex);
0N/A }
0N/A }
0N/A public SortedSet<E> headSet(E toElement) {
3203N/A synchronized (mutex) {
3323N/A return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex);
0N/A }
0N/A }
0N/A public SortedSet<E> tailSet(E fromElement) {
3203N/A synchronized (mutex) {
3323N/A return new SynchronizedSortedSet<>(ss.tailSet(fromElement),mutex);
0N/A }
0N/A }
0N/A
0N/A public E first() {
3203N/A synchronized (mutex) {return ss.first();}
0N/A }
0N/A public E last() {
3203N/A synchronized (mutex) {return ss.last();}
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a synchronized (thread-safe) list backed by the specified
0N/A * list. In order to guarantee serial access, it is critical that
0N/A * <strong>all</strong> access to the backing list is accomplished
0N/A * through the returned list.<p>
0N/A *
0N/A * It is imperative that the user manually synchronize on the returned
0N/A * list when iterating over it:
0N/A * <pre>
0N/A * List list = Collections.synchronizedList(new ArrayList());
0N/A * ...
3203N/A * synchronized (list) {
0N/A * Iterator i = list.iterator(); // Must be in synchronized block
0N/A * while (i.hasNext())
0N/A * foo(i.next());
0N/A * }
0N/A * </pre>
0N/A * Failure to follow this advice may result in non-deterministic behavior.
0N/A *
0N/A * <p>The returned list will be serializable if the specified list is
0N/A * serializable.
0N/A *
0N/A * @param list the list to be "wrapped" in a synchronized list.
0N/A * @return a synchronized view of the specified list.
0N/A */
0N/A public static <T> List<T> synchronizedList(List<T> list) {
0N/A return (list instanceof RandomAccess ?
3323N/A new SynchronizedRandomAccessList<>(list) :
3323N/A new SynchronizedList<>(list));
0N/A }
0N/A
0N/A static <T> List<T> synchronizedList(List<T> list, Object mutex) {
0N/A return (list instanceof RandomAccess ?
3323N/A new SynchronizedRandomAccessList<>(list, mutex) :
3323N/A new SynchronizedList<>(list, mutex));
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class SynchronizedList<E>
0N/A extends SynchronizedCollection<E>
0N/A implements List<E> {
0N/A private static final long serialVersionUID = -7754090372962971524L;
0N/A
0N/A final List<E> list;
0N/A
0N/A SynchronizedList(List<E> list) {
0N/A super(list);
0N/A this.list = list;
0N/A }
0N/A SynchronizedList(List<E> list, Object mutex) {
0N/A super(list, mutex);
0N/A this.list = list;
0N/A }
0N/A
0N/A public boolean equals(Object o) {
4856N/A if (this == o)
4856N/A return true;
3203N/A synchronized (mutex) {return list.equals(o);}
0N/A }
0N/A public int hashCode() {
3203N/A synchronized (mutex) {return list.hashCode();}
0N/A }
0N/A
0N/A public E get(int index) {
3203N/A synchronized (mutex) {return list.get(index);}
0N/A }
0N/A public E set(int index, E element) {
3203N/A synchronized (mutex) {return list.set(index, element);}
0N/A }
0N/A public void add(int index, E element) {
3203N/A synchronized (mutex) {list.add(index, element);}
0N/A }
0N/A public E remove(int index) {
3203N/A synchronized (mutex) {return list.remove(index);}
0N/A }
0N/A
0N/A public int indexOf(Object o) {
3203N/A synchronized (mutex) {return list.indexOf(o);}
0N/A }
0N/A public int lastIndexOf(Object o) {
3203N/A synchronized (mutex) {return list.lastIndexOf(o);}
0N/A }
0N/A
0N/A public boolean addAll(int index, Collection<? extends E> c) {
3203N/A synchronized (mutex) {return list.addAll(index, c);}
0N/A }
0N/A
0N/A public ListIterator<E> listIterator() {
0N/A return list.listIterator(); // Must be manually synched by user
0N/A }
0N/A
0N/A public ListIterator<E> listIterator(int index) {
0N/A return list.listIterator(index); // Must be manually synched by user
0N/A }
0N/A
0N/A public List<E> subList(int fromIndex, int toIndex) {
3203N/A synchronized (mutex) {
3323N/A return new SynchronizedList<>(list.subList(fromIndex, toIndex),
0N/A mutex);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * SynchronizedRandomAccessList instances are serialized as
0N/A * SynchronizedList instances to allow them to be deserialized
0N/A * in pre-1.4 JREs (which do not have SynchronizedRandomAccessList).
0N/A * This method inverts the transformation. As a beneficial
0N/A * side-effect, it also grafts the RandomAccess marker onto
0N/A * SynchronizedList instances that were serialized in pre-1.4 JREs.
0N/A *
0N/A * Note: Unfortunately, SynchronizedRandomAccessList instances
0N/A * serialized in 1.4.1 and deserialized in 1.4 will become
0N/A * SynchronizedList instances, as this method was missing in 1.4.
0N/A */
0N/A private Object readResolve() {
0N/A return (list instanceof RandomAccess
3323N/A ? new SynchronizedRandomAccessList<>(list)
0N/A : this);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class SynchronizedRandomAccessList<E>
0N/A extends SynchronizedList<E>
0N/A implements RandomAccess {
0N/A
0N/A SynchronizedRandomAccessList(List<E> list) {
0N/A super(list);
0N/A }
0N/A
0N/A SynchronizedRandomAccessList(List<E> list, Object mutex) {
0N/A super(list, mutex);
0N/A }
0N/A
0N/A public List<E> subList(int fromIndex, int toIndex) {
3203N/A synchronized (mutex) {
3323N/A return new SynchronizedRandomAccessList<>(
0N/A list.subList(fromIndex, toIndex), mutex);
0N/A }
0N/A }
0N/A
0N/A private static final long serialVersionUID = 1530674583602358482L;
0N/A
0N/A /**
0N/A * Allows instances to be deserialized in pre-1.4 JREs (which do
0N/A * not have SynchronizedRandomAccessList). SynchronizedList has
0N/A * a readResolve method that inverts this transformation upon
0N/A * deserialization.
0N/A */
0N/A private Object writeReplace() {
3323N/A return new SynchronizedList<>(list);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a synchronized (thread-safe) map backed by the specified
0N/A * map. In order to guarantee serial access, it is critical that
0N/A * <strong>all</strong> access to the backing map is accomplished
0N/A * through the returned map.<p>
0N/A *
0N/A * It is imperative that the user manually synchronize on the returned
0N/A * map when iterating over any of its collection views:
0N/A * <pre>
0N/A * Map m = Collections.synchronizedMap(new HashMap());
0N/A * ...
0N/A * Set s = m.keySet(); // Needn't be in synchronized block
0N/A * ...
3203N/A * synchronized (m) { // Synchronizing on m, not s!
0N/A * Iterator i = s.iterator(); // Must be in synchronized block
0N/A * while (i.hasNext())
0N/A * foo(i.next());
0N/A * }
0N/A * </pre>
0N/A * Failure to follow this advice may result in non-deterministic behavior.
0N/A *
0N/A * <p>The returned map will be serializable if the specified map is
0N/A * serializable.
0N/A *
0N/A * @param m the map to be "wrapped" in a synchronized map.
0N/A * @return a synchronized view of the specified map.
0N/A */
0N/A public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
3323N/A return new SynchronizedMap<>(m);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A private static class SynchronizedMap<K,V>
0N/A implements Map<K,V>, Serializable {
0N/A private static final long serialVersionUID = 1978198479659022715L;
0N/A
0N/A private final Map<K,V> m; // Backing Map
0N/A final Object mutex; // Object on which to synchronize
0N/A
0N/A SynchronizedMap(Map<K,V> m) {
0N/A if (m==null)
0N/A throw new NullPointerException();
0N/A this.m = m;
0N/A mutex = this;
0N/A }
0N/A
0N/A SynchronizedMap(Map<K,V> m, Object mutex) {
0N/A this.m = m;
0N/A this.mutex = mutex;
0N/A }
0N/A
0N/A public int size() {
3203N/A synchronized (mutex) {return m.size();}
0N/A }
0N/A public boolean isEmpty() {
3203N/A synchronized (mutex) {return m.isEmpty();}
0N/A }
0N/A public boolean containsKey(Object key) {
3203N/A synchronized (mutex) {return m.containsKey(key);}
0N/A }
0N/A public boolean containsValue(Object value) {
3203N/A synchronized (mutex) {return m.containsValue(value);}
0N/A }
0N/A public V get(Object key) {
3203N/A synchronized (mutex) {return m.get(key);}
0N/A }
0N/A
0N/A public V put(K key, V value) {
3203N/A synchronized (mutex) {return m.put(key, value);}
0N/A }
0N/A public V remove(Object key) {
3203N/A synchronized (mutex) {return m.remove(key);}
0N/A }
0N/A public void putAll(Map<? extends K, ? extends V> map) {
3203N/A synchronized (mutex) {m.putAll(map);}
0N/A }
0N/A public void clear() {
3203N/A synchronized (mutex) {m.clear();}
0N/A }
0N/A
0N/A private transient Set<K> keySet = null;
0N/A private transient Set<Map.Entry<K,V>> entrySet = null;
0N/A private transient Collection<V> values = null;
0N/A
0N/A public Set<K> keySet() {
3203N/A synchronized (mutex) {
0N/A if (keySet==null)
3323N/A keySet = new SynchronizedSet<>(m.keySet(), mutex);
0N/A return keySet;
0N/A }
0N/A }
0N/A
0N/A public Set<Map.Entry<K,V>> entrySet() {
3203N/A synchronized (mutex) {
0N/A if (entrySet==null)
3323N/A entrySet = new SynchronizedSet<>(m.entrySet(), mutex);
0N/A return entrySet;
0N/A }
0N/A }
0N/A
0N/A public Collection<V> values() {
3203N/A synchronized (mutex) {
0N/A if (values==null)
3323N/A values = new SynchronizedCollection<>(m.values(), mutex);
0N/A return values;
0N/A }
0N/A }
0N/A
0N/A public boolean equals(Object o) {
4856N/A if (this == o)
4856N/A return true;
3203N/A synchronized (mutex) {return m.equals(o);}
0N/A }
0N/A public int hashCode() {
3203N/A synchronized (mutex) {return m.hashCode();}
0N/A }
0N/A public String toString() {
3203N/A synchronized (mutex) {return m.toString();}
0N/A }
0N/A private void writeObject(ObjectOutputStream s) throws IOException {
3203N/A synchronized (mutex) {s.defaultWriteObject();}
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a synchronized (thread-safe) sorted map backed by the specified
0N/A * sorted map. In order to guarantee serial access, it is critical that
0N/A * <strong>all</strong> access to the backing sorted map is accomplished
0N/A * through the returned sorted map (or its views).<p>
0N/A *
0N/A * It is imperative that the user manually synchronize on the returned
0N/A * sorted map when iterating over any of its collection views, or the
0N/A * collections views of any of its <tt>subMap</tt>, <tt>headMap</tt> or
0N/A * <tt>tailMap</tt> views.
0N/A * <pre>
0N/A * SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
0N/A * ...
0N/A * Set s = m.keySet(); // Needn't be in synchronized block
0N/A * ...
3203N/A * synchronized (m) { // Synchronizing on m, not s!
0N/A * Iterator i = s.iterator(); // Must be in synchronized block
0N/A * while (i.hasNext())
0N/A * foo(i.next());
0N/A * }
0N/A * </pre>
0N/A * or:
0N/A * <pre>
0N/A * SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
0N/A * SortedMap m2 = m.subMap(foo, bar);
0N/A * ...
0N/A * Set s2 = m2.keySet(); // Needn't be in synchronized block
0N/A * ...
3203N/A * synchronized (m) { // Synchronizing on m, not m2 or s2!
0N/A * Iterator i = s.iterator(); // Must be in synchronized block
0N/A * while (i.hasNext())
0N/A * foo(i.next());
0N/A * }
0N/A * </pre>
0N/A * Failure to follow this advice may result in non-deterministic behavior.
0N/A *
0N/A * <p>The returned sorted map will be serializable if the specified
0N/A * sorted map is serializable.
0N/A *
0N/A * @param m the sorted map to be "wrapped" in a synchronized sorted map.
0N/A * @return a synchronized view of the specified sorted map.
0N/A */
0N/A public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {
3323N/A return new SynchronizedSortedMap<>(m);
0N/A }
0N/A
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class SynchronizedSortedMap<K,V>
0N/A extends SynchronizedMap<K,V>
0N/A implements SortedMap<K,V>
0N/A {
0N/A private static final long serialVersionUID = -8798146769416483793L;
0N/A
0N/A private final SortedMap<K,V> sm;
0N/A
0N/A SynchronizedSortedMap(SortedMap<K,V> m) {
0N/A super(m);
0N/A sm = m;
0N/A }
0N/A SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) {
0N/A super(m, mutex);
0N/A sm = m;
0N/A }
0N/A
0N/A public Comparator<? super K> comparator() {
3203N/A synchronized (mutex) {return sm.comparator();}
0N/A }
0N/A
0N/A public SortedMap<K,V> subMap(K fromKey, K toKey) {
3203N/A synchronized (mutex) {
3323N/A return new SynchronizedSortedMap<>(
0N/A sm.subMap(fromKey, toKey), mutex);
0N/A }
0N/A }
0N/A public SortedMap<K,V> headMap(K toKey) {
3203N/A synchronized (mutex) {
3323N/A return new SynchronizedSortedMap<>(sm.headMap(toKey), mutex);
0N/A }
0N/A }
0N/A public SortedMap<K,V> tailMap(K fromKey) {
3203N/A synchronized (mutex) {
3323N/A return new SynchronizedSortedMap<>(sm.tailMap(fromKey),mutex);
0N/A }
0N/A }
0N/A
0N/A public K firstKey() {
3203N/A synchronized (mutex) {return sm.firstKey();}
0N/A }
0N/A public K lastKey() {
3203N/A synchronized (mutex) {return sm.lastKey();}
0N/A }
0N/A }
0N/A
0N/A // Dynamically typesafe collection wrappers
0N/A
0N/A /**
0N/A * Returns a dynamically typesafe view of the specified collection.
0N/A * Any attempt to insert an element of the wrong type will result in an
0N/A * immediate {@link ClassCastException}. Assuming a collection
0N/A * contains no incorrectly typed elements prior to the time a
0N/A * dynamically typesafe view is generated, and that all subsequent
0N/A * access to the collection takes place through the view, it is
0N/A * <i>guaranteed</i> that the collection cannot contain an incorrectly
0N/A * typed element.
0N/A *
0N/A * <p>The generics mechanism in the language provides compile-time
0N/A * (static) type checking, but it is possible to defeat this mechanism
0N/A * with unchecked casts. Usually this is not a problem, as the compiler
0N/A * issues warnings on all such unchecked operations. There are, however,
0N/A * times when static type checking alone is not sufficient. For example,
0N/A * suppose a collection is passed to a third-party library and it is
0N/A * imperative that the library code not corrupt the collection by
0N/A * inserting an element of the wrong type.
0N/A *
0N/A * <p>Another use of dynamically typesafe views is debugging. Suppose a
0N/A * program fails with a {@code ClassCastException}, indicating that an
0N/A * incorrectly typed element was put into a parameterized collection.
0N/A * Unfortunately, the exception can occur at any time after the erroneous
0N/A * element is inserted, so it typically provides little or no information
0N/A * as to the real source of the problem. If the problem is reproducible,
0N/A * one can quickly determine its source by temporarily modifying the
0N/A * program to wrap the collection with a dynamically typesafe view.
0N/A * For example, this declaration:
0N/A * <pre> {@code
0N/A * Collection<String> c = new HashSet<String>();
0N/A * }</pre>
0N/A * may be replaced temporarily by this one:
0N/A * <pre> {@code
0N/A * Collection<String> c = Collections.checkedCollection(
0N/A * new HashSet<String>(), String.class);
0N/A * }</pre>
0N/A * Running the program again will cause it to fail at the point where
0N/A * an incorrectly typed element is inserted into the collection, clearly
0N/A * identifying the source of the problem. Once the problem is fixed, the
0N/A * modified declaration may be reverted back to the original.
0N/A *
0N/A * <p>The returned collection does <i>not</i> pass the hashCode and equals
0N/A * operations through to the backing collection, but relies on
0N/A * {@code Object}'s {@code equals} and {@code hashCode} methods. This
0N/A * is necessary to preserve the contracts of these operations in the case
0N/A * that the backing collection is a set or a list.
0N/A *
0N/A * <p>The returned collection will be serializable if the specified
0N/A * collection is serializable.
0N/A *
0N/A * <p>Since {@code null} is considered to be a value of any reference
0N/A * type, the returned collection permits insertion of null elements
0N/A * whenever the backing collection does.
0N/A *
0N/A * @param c the collection for which a dynamically typesafe view is to be
0N/A * returned
0N/A * @param type the type of element that {@code c} is permitted to hold
0N/A * @return a dynamically typesafe view of the specified collection
0N/A * @since 1.5
0N/A */
0N/A public static <E> Collection<E> checkedCollection(Collection<E> c,
0N/A Class<E> type) {
3323N/A return new CheckedCollection<>(c, type);
0N/A }
0N/A
0N/A @SuppressWarnings("unchecked")
0N/A static <T> T[] zeroLengthArray(Class<T> type) {
0N/A return (T[]) Array.newInstance(type, 0);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class CheckedCollection<E> implements Collection<E>, Serializable {
0N/A private static final long serialVersionUID = 1578914078182001775L;
0N/A
0N/A final Collection<E> c;
0N/A final Class<E> type;
0N/A
0N/A void typeCheck(Object o) {
0N/A if (o != null && !type.isInstance(o))
0N/A throw new ClassCastException(badElementMsg(o));
0N/A }
0N/A
0N/A private String badElementMsg(Object o) {
0N/A return "Attempt to insert " + o.getClass() +
0N/A " element into collection with element type " + type;
0N/A }
0N/A
0N/A CheckedCollection(Collection<E> c, Class<E> type) {
0N/A if (c==null || type == null)
0N/A throw new NullPointerException();
0N/A this.c = c;
0N/A this.type = type;
0N/A }
0N/A
0N/A public int size() { return c.size(); }
0N/A public boolean isEmpty() { return c.isEmpty(); }
0N/A public boolean contains(Object o) { return c.contains(o); }
0N/A public Object[] toArray() { return c.toArray(); }
0N/A public <T> T[] toArray(T[] a) { return c.toArray(a); }
0N/A public String toString() { return c.toString(); }
0N/A public boolean remove(Object o) { return c.remove(o); }
0N/A public void clear() { c.clear(); }
0N/A
0N/A public boolean containsAll(Collection<?> coll) {
0N/A return c.containsAll(coll);
0N/A }
0N/A public boolean removeAll(Collection<?> coll) {
0N/A return c.removeAll(coll);
0N/A }
0N/A public boolean retainAll(Collection<?> coll) {
0N/A return c.retainAll(coll);
0N/A }
0N/A
0N/A public Iterator<E> iterator() {
0N/A final Iterator<E> it = c.iterator();
0N/A return new Iterator<E>() {
0N/A public boolean hasNext() { return it.hasNext(); }
0N/A public E next() { return it.next(); }
0N/A public void remove() { it.remove(); }};
0N/A }
0N/A
0N/A public boolean add(E e) {
0N/A typeCheck(e);
0N/A return c.add(e);
0N/A }
0N/A
0N/A private E[] zeroLengthElementArray = null; // Lazily initialized
0N/A
0N/A private E[] zeroLengthElementArray() {
0N/A return zeroLengthElementArray != null ? zeroLengthElementArray :
0N/A (zeroLengthElementArray = zeroLengthArray(type));
0N/A }
0N/A
0N/A @SuppressWarnings("unchecked")
0N/A Collection<E> checkedCopyOf(Collection<? extends E> coll) {
0N/A Object[] a = null;
0N/A try {
0N/A E[] z = zeroLengthElementArray();
0N/A a = coll.toArray(z);
0N/A // Defend against coll violating the toArray contract
0N/A if (a.getClass() != z.getClass())
0N/A a = Arrays.copyOf(a, a.length, z.getClass());
0N/A } catch (ArrayStoreException ignore) {
0N/A // To get better and consistent diagnostics,
0N/A // we call typeCheck explicitly on each element.
0N/A // We call clone() to defend against coll retaining a
0N/A // reference to the returned array and storing a bad
0N/A // element into it after it has been type checked.
0N/A a = coll.toArray().clone();
0N/A for (Object o : a)
0N/A typeCheck(o);
0N/A }
0N/A // A slight abuse of the type system, but safe here.
0N/A return (Collection<E>) Arrays.asList(a);
0N/A }
0N/A
0N/A public boolean addAll(Collection<? extends E> coll) {
0N/A // Doing things this way insulates us from concurrent changes
0N/A // in the contents of coll and provides all-or-nothing
0N/A // semantics (which we wouldn't get if we type-checked each
0N/A // element as we added it)
0N/A return c.addAll(checkedCopyOf(coll));
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a dynamically typesafe view of the specified set.
0N/A * Any attempt to insert an element of the wrong type will result in
0N/A * an immediate {@link ClassCastException}. Assuming a set contains
0N/A * no incorrectly typed elements prior to the time a dynamically typesafe
0N/A * view is generated, and that all subsequent access to the set
0N/A * takes place through the view, it is <i>guaranteed</i> that the
0N/A * set cannot contain an incorrectly typed element.
0N/A *
0N/A * <p>A discussion of the use of dynamically typesafe views may be
0N/A * found in the documentation for the {@link #checkedCollection
0N/A * checkedCollection} method.
0N/A *
0N/A * <p>The returned set will be serializable if the specified set is
0N/A * serializable.
0N/A *
0N/A * <p>Since {@code null} is considered to be a value of any reference
0N/A * type, the returned set permits insertion of null elements whenever
0N/A * the backing set does.
0N/A *
0N/A * @param s the set for which a dynamically typesafe view is to be
0N/A * returned
0N/A * @param type the type of element that {@code s} is permitted to hold
0N/A * @return a dynamically typesafe view of the specified set
0N/A * @since 1.5
0N/A */
0N/A public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {
3323N/A return new CheckedSet<>(s, type);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class CheckedSet<E> extends CheckedCollection<E>
0N/A implements Set<E>, Serializable
0N/A {
0N/A private static final long serialVersionUID = 4694047833775013803L;
0N/A
0N/A CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); }
0N/A
0N/A public boolean equals(Object o) { return o == this || c.equals(o); }
0N/A public int hashCode() { return c.hashCode(); }
0N/A }
0N/A
0N/A /**
0N/A * Returns a dynamically typesafe view of the specified sorted set.
0N/A * Any attempt to insert an element of the wrong type will result in an
0N/A * immediate {@link ClassCastException}. Assuming a sorted set
0N/A * contains no incorrectly typed elements prior to the time a
0N/A * dynamically typesafe view is generated, and that all subsequent
0N/A * access to the sorted set takes place through the view, it is
0N/A * <i>guaranteed</i> that the sorted set cannot contain an incorrectly
0N/A * typed element.
0N/A *
0N/A * <p>A discussion of the use of dynamically typesafe views may be
0N/A * found in the documentation for the {@link #checkedCollection
0N/A * checkedCollection} method.
0N/A *
0N/A * <p>The returned sorted set will be serializable if the specified sorted
0N/A * set is serializable.
0N/A *
0N/A * <p>Since {@code null} is considered to be a value of any reference
0N/A * type, the returned sorted set permits insertion of null elements
0N/A * whenever the backing sorted set does.
0N/A *
0N/A * @param s the sorted set for which a dynamically typesafe view is to be
0N/A * returned
0N/A * @param type the type of element that {@code s} is permitted to hold
0N/A * @return a dynamically typesafe view of the specified sorted set
0N/A * @since 1.5
0N/A */
0N/A public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
0N/A Class<E> type) {
3323N/A return new CheckedSortedSet<>(s, type);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class CheckedSortedSet<E> extends CheckedSet<E>
0N/A implements SortedSet<E>, Serializable
0N/A {
0N/A private static final long serialVersionUID = 1599911165492914959L;
0N/A private final SortedSet<E> ss;
0N/A
0N/A CheckedSortedSet(SortedSet<E> s, Class<E> type) {
0N/A super(s, type);
0N/A ss = s;
0N/A }
0N/A
0N/A public Comparator<? super E> comparator() { return ss.comparator(); }
0N/A public E first() { return ss.first(); }
0N/A public E last() { return ss.last(); }
0N/A
0N/A public SortedSet<E> subSet(E fromElement, E toElement) {
0N/A return checkedSortedSet(ss.subSet(fromElement,toElement), type);
0N/A }
0N/A public SortedSet<E> headSet(E toElement) {
0N/A return checkedSortedSet(ss.headSet(toElement), type);
0N/A }
0N/A public SortedSet<E> tailSet(E fromElement) {
0N/A return checkedSortedSet(ss.tailSet(fromElement), type);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a dynamically typesafe view of the specified list.
0N/A * Any attempt to insert an element of the wrong type will result in
0N/A * an immediate {@link ClassCastException}. Assuming a list contains
0N/A * no incorrectly typed elements prior to the time a dynamically typesafe
0N/A * view is generated, and that all subsequent access to the list
0N/A * takes place through the view, it is <i>guaranteed</i> that the
0N/A * list cannot contain an incorrectly typed element.
0N/A *
0N/A * <p>A discussion of the use of dynamically typesafe views may be
0N/A * found in the documentation for the {@link #checkedCollection
0N/A * checkedCollection} method.
0N/A *
0N/A * <p>The returned list will be serializable if the specified list
0N/A * is serializable.
0N/A *
0N/A * <p>Since {@code null} is considered to be a value of any reference
0N/A * type, the returned list permits insertion of null elements whenever
0N/A * the backing list does.
0N/A *
0N/A * @param list the list for which a dynamically typesafe view is to be
0N/A * returned
0N/A * @param type the type of element that {@code list} is permitted to hold
0N/A * @return a dynamically typesafe view of the specified list
0N/A * @since 1.5
0N/A */
0N/A public static <E> List<E> checkedList(List<E> list, Class<E> type) {
0N/A return (list instanceof RandomAccess ?
3323N/A new CheckedRandomAccessList<>(list, type) :
3323N/A new CheckedList<>(list, type));
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class CheckedList<E>
0N/A extends CheckedCollection<E>
0N/A implements List<E>
0N/A {
0N/A private static final long serialVersionUID = 65247728283967356L;
0N/A final List<E> list;
0N/A
0N/A CheckedList(List<E> list, Class<E> type) {
0N/A super(list, type);
0N/A this.list = list;
0N/A }
0N/A
0N/A public boolean equals(Object o) { return o == this || list.equals(o); }
0N/A public int hashCode() { return list.hashCode(); }
0N/A public E get(int index) { return list.get(index); }
0N/A public E remove(int index) { return list.remove(index); }
0N/A public int indexOf(Object o) { return list.indexOf(o); }
0N/A public int lastIndexOf(Object o) { return list.lastIndexOf(o); }
0N/A
0N/A public E set(int index, E element) {
0N/A typeCheck(element);
0N/A return list.set(index, element);
0N/A }
0N/A
0N/A public void add(int index, E element) {
0N/A typeCheck(element);
0N/A list.add(index, element);
0N/A }
0N/A
0N/A public boolean addAll(int index, Collection<? extends E> c) {
0N/A return list.addAll(index, checkedCopyOf(c));
0N/A }
0N/A public ListIterator<E> listIterator() { return listIterator(0); }
0N/A
0N/A public ListIterator<E> listIterator(final int index) {
0N/A final ListIterator<E> i = list.listIterator(index);
0N/A
0N/A return new ListIterator<E>() {
0N/A public boolean hasNext() { return i.hasNext(); }
0N/A public E next() { return i.next(); }
0N/A public boolean hasPrevious() { return i.hasPrevious(); }
0N/A public E previous() { return i.previous(); }
0N/A public int nextIndex() { return i.nextIndex(); }
0N/A public int previousIndex() { return i.previousIndex(); }
0N/A public void remove() { i.remove(); }
0N/A
0N/A public void set(E e) {
0N/A typeCheck(e);
0N/A i.set(e);
0N/A }
0N/A
0N/A public void add(E e) {
0N/A typeCheck(e);
0N/A i.add(e);
0N/A }
0N/A };
0N/A }
0N/A
0N/A public List<E> subList(int fromIndex, int toIndex) {
3323N/A return new CheckedList<>(list.subList(fromIndex, toIndex), type);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class CheckedRandomAccessList<E> extends CheckedList<E>
0N/A implements RandomAccess
0N/A {
0N/A private static final long serialVersionUID = 1638200125423088369L;
0N/A
0N/A CheckedRandomAccessList(List<E> list, Class<E> type) {
0N/A super(list, type);
0N/A }
0N/A
0N/A public List<E> subList(int fromIndex, int toIndex) {
3323N/A return new CheckedRandomAccessList<>(
0N/A list.subList(fromIndex, toIndex), type);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a dynamically typesafe view of the specified map.
0N/A * Any attempt to insert a mapping whose key or value have the wrong
0N/A * type will result in an immediate {@link ClassCastException}.
0N/A * Similarly, any attempt to modify the value currently associated with
0N/A * a key will result in an immediate {@link ClassCastException},
0N/A * whether the modification is attempted directly through the map
0N/A * itself, or through a {@link Map.Entry} instance obtained from the
0N/A * map's {@link Map#entrySet() entry set} view.
0N/A *
0N/A * <p>Assuming a map contains no incorrectly typed keys or values
0N/A * prior to the time a dynamically typesafe view is generated, and
0N/A * that all subsequent access to the map takes place through the view
0N/A * (or one of its collection views), it is <i>guaranteed</i> that the
0N/A * map cannot contain an incorrectly typed key or value.
0N/A *
0N/A * <p>A discussion of the use of dynamically typesafe views may be
0N/A * found in the documentation for the {@link #checkedCollection
0N/A * checkedCollection} method.
0N/A *
0N/A * <p>The returned map will be serializable if the specified map is
0N/A * serializable.
0N/A *
0N/A * <p>Since {@code null} is considered to be a value of any reference
0N/A * type, the returned map permits insertion of null keys or values
0N/A * whenever the backing map does.
0N/A *
0N/A * @param m the map for which a dynamically typesafe view is to be
0N/A * returned
0N/A * @param keyType the type of key that {@code m} is permitted to hold
0N/A * @param valueType the type of value that {@code m} is permitted to hold
0N/A * @return a dynamically typesafe view of the specified map
0N/A * @since 1.5
0N/A */
0N/A public static <K, V> Map<K, V> checkedMap(Map<K, V> m,
0N/A Class<K> keyType,
0N/A Class<V> valueType) {
3323N/A return new CheckedMap<>(m, keyType, valueType);
0N/A }
0N/A
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A private static class CheckedMap<K,V>
0N/A implements Map<K,V>, Serializable
0N/A {
0N/A private static final long serialVersionUID = 5742860141034234728L;
0N/A
0N/A private final Map<K, V> m;
0N/A final Class<K> keyType;
0N/A final Class<V> valueType;
0N/A
0N/A private void typeCheck(Object key, Object value) {
0N/A if (key != null && !keyType.isInstance(key))
0N/A throw new ClassCastException(badKeyMsg(key));
0N/A
0N/A if (value != null && !valueType.isInstance(value))
0N/A throw new ClassCastException(badValueMsg(value));
0N/A }
0N/A
0N/A private String badKeyMsg(Object key) {
0N/A return "Attempt to insert " + key.getClass() +
0N/A " key into map with key type " + keyType;
0N/A }
0N/A
0N/A private String badValueMsg(Object value) {
0N/A return "Attempt to insert " + value.getClass() +
0N/A " value into map with value type " + valueType;
0N/A }
0N/A
0N/A CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) {
0N/A if (m == null || keyType == null || valueType == null)
0N/A throw new NullPointerException();
0N/A this.m = m;
0N/A this.keyType = keyType;
0N/A this.valueType = valueType;
0N/A }
0N/A
0N/A public int size() { return m.size(); }
0N/A public boolean isEmpty() { return m.isEmpty(); }
0N/A public boolean containsKey(Object key) { return m.containsKey(key); }
0N/A public boolean containsValue(Object v) { return m.containsValue(v); }
0N/A public V get(Object key) { return m.get(key); }
0N/A public V remove(Object key) { return m.remove(key); }
0N/A public void clear() { m.clear(); }
0N/A public Set<K> keySet() { return m.keySet(); }
0N/A public Collection<V> values() { return m.values(); }
0N/A public boolean equals(Object o) { return o == this || m.equals(o); }
0N/A public int hashCode() { return m.hashCode(); }
0N/A public String toString() { return m.toString(); }
0N/A
0N/A public V put(K key, V value) {
0N/A typeCheck(key, value);
0N/A return m.put(key, value);
0N/A }
0N/A
0N/A @SuppressWarnings("unchecked")
0N/A public void putAll(Map<? extends K, ? extends V> t) {
0N/A // Satisfy the following goals:
0N/A // - good diagnostics in case of type mismatch
0N/A // - all-or-nothing semantics
0N/A // - protection from malicious t
0N/A // - correct behavior if t is a concurrent map
0N/A Object[] entries = t.entrySet().toArray();
3323N/A List<Map.Entry<K,V>> checked = new ArrayList<>(entries.length);
0N/A for (Object o : entries) {
0N/A Map.Entry<?,?> e = (Map.Entry<?,?>) o;
0N/A Object k = e.getKey();
0N/A Object v = e.getValue();
0N/A typeCheck(k, v);
0N/A checked.add(
3323N/A new AbstractMap.SimpleImmutableEntry<>((K) k, (V) v));
0N/A }
0N/A for (Map.Entry<K,V> e : checked)
0N/A m.put(e.getKey(), e.getValue());
0N/A }
0N/A
0N/A private transient Set<Map.Entry<K,V>> entrySet = null;
0N/A
0N/A public Set<Map.Entry<K,V>> entrySet() {
0N/A if (entrySet==null)
3323N/A entrySet = new CheckedEntrySet<>(m.entrySet(), valueType);
0N/A return entrySet;
0N/A }
0N/A
0N/A /**
0N/A * We need this class in addition to CheckedSet as Map.Entry permits
0N/A * modification of the backing Map via the setValue operation. This
0N/A * class is subtle: there are many possible attacks that must be
0N/A * thwarted.
0N/A *
0N/A * @serial exclude
0N/A */
0N/A static class CheckedEntrySet<K,V> implements Set<Map.Entry<K,V>> {
0N/A private final Set<Map.Entry<K,V>> s;
0N/A private final Class<V> valueType;
0N/A
0N/A CheckedEntrySet(Set<Map.Entry<K, V>> s, Class<V> valueType) {
0N/A this.s = s;
0N/A this.valueType = valueType;
0N/A }
0N/A
0N/A public int size() { return s.size(); }
0N/A public boolean isEmpty() { return s.isEmpty(); }
0N/A public String toString() { return s.toString(); }
0N/A public int hashCode() { return s.hashCode(); }
0N/A public void clear() { s.clear(); }
0N/A
0N/A public boolean add(Map.Entry<K, V> e) {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A public boolean addAll(Collection<? extends Map.Entry<K, V>> coll) {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A
0N/A public Iterator<Map.Entry<K,V>> iterator() {
0N/A final Iterator<Map.Entry<K, V>> i = s.iterator();
0N/A final Class<V> valueType = this.valueType;
0N/A
0N/A return new Iterator<Map.Entry<K,V>>() {
0N/A public boolean hasNext() { return i.hasNext(); }
0N/A public void remove() { i.remove(); }
0N/A
0N/A public Map.Entry<K,V> next() {
0N/A return checkedEntry(i.next(), valueType);
0N/A }
0N/A };
0N/A }
0N/A
0N/A @SuppressWarnings("unchecked")
0N/A public Object[] toArray() {
0N/A Object[] source = s.toArray();
0N/A
0N/A /*
0N/A * Ensure that we don't get an ArrayStoreException even if
0N/A * s.toArray returns an array of something other than Object
0N/A */
0N/A Object[] dest = (CheckedEntry.class.isInstance(
0N/A source.getClass().getComponentType()) ? source :
0N/A new Object[source.length]);
0N/A
0N/A for (int i = 0; i < source.length; i++)
0N/A dest[i] = checkedEntry((Map.Entry<K,V>)source[i],
0N/A valueType);
0N/A return dest;
0N/A }
0N/A
0N/A @SuppressWarnings("unchecked")
0N/A public <T> T[] toArray(T[] a) {
0N/A // We don't pass a to s.toArray, to avoid window of
0N/A // vulnerability wherein an unscrupulous multithreaded client
0N/A // could get his hands on raw (unwrapped) Entries from s.
0N/A T[] arr = s.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
0N/A
0N/A for (int i=0; i<arr.length; i++)
0N/A arr[i] = (T) checkedEntry((Map.Entry<K,V>)arr[i],
0N/A valueType);
0N/A if (arr.length > a.length)
0N/A return arr;
0N/A
0N/A System.arraycopy(arr, 0, a, 0, arr.length);
0N/A if (a.length > arr.length)
0N/A a[arr.length] = null;
0N/A return a;
0N/A }
0N/A
0N/A /**
0N/A * This method is overridden to protect the backing set against
0N/A * an object with a nefarious equals function that senses
0N/A * that the equality-candidate is Map.Entry and calls its
0N/A * setValue method.
0N/A */
0N/A public boolean contains(Object o) {
0N/A if (!(o instanceof Map.Entry))
0N/A return false;
0N/A Map.Entry<?,?> e = (Map.Entry<?,?>) o;
0N/A return s.contains(
0N/A (e instanceof CheckedEntry) ? e : checkedEntry(e, valueType));
0N/A }
0N/A
0N/A /**
0N/A * The bulk collection methods are overridden to protect
0N/A * against an unscrupulous collection whose contains(Object o)
0N/A * method senses when o is a Map.Entry, and calls o.setValue.
0N/A */
0N/A public boolean containsAll(Collection<?> c) {
0N/A for (Object o : c)
0N/A if (!contains(o)) // Invokes safe contains() above
0N/A return false;
0N/A return true;
0N/A }
0N/A
0N/A public boolean remove(Object o) {
0N/A if (!(o instanceof Map.Entry))
0N/A return false;
0N/A return s.remove(new AbstractMap.SimpleImmutableEntry
3323N/A <>((Map.Entry<?,?>)o));
0N/A }
0N/A
0N/A public boolean removeAll(Collection<?> c) {
0N/A return batchRemove(c, false);
0N/A }
0N/A public boolean retainAll(Collection<?> c) {
0N/A return batchRemove(c, true);
0N/A }
0N/A private boolean batchRemove(Collection<?> c, boolean complement) {
0N/A boolean modified = false;
0N/A Iterator<Map.Entry<K,V>> it = iterator();
0N/A while (it.hasNext()) {
0N/A if (c.contains(it.next()) != complement) {
0N/A it.remove();
0N/A modified = true;
0N/A }
0N/A }
0N/A return modified;
0N/A }
0N/A
0N/A public boolean equals(Object o) {
0N/A if (o == this)
0N/A return true;
0N/A if (!(o instanceof Set))
0N/A return false;
0N/A Set<?> that = (Set<?>) o;
0N/A return that.size() == s.size()
0N/A && containsAll(that); // Invokes safe containsAll() above
0N/A }
0N/A
0N/A static <K,V,T> CheckedEntry<K,V,T> checkedEntry(Map.Entry<K,V> e,
0N/A Class<T> valueType) {
3323N/A return new CheckedEntry<>(e, valueType);
0N/A }
0N/A
0N/A /**
0N/A * This "wrapper class" serves two purposes: it prevents
0N/A * the client from modifying the backing Map, by short-circuiting
0N/A * the setValue method, and it protects the backing Map against
0N/A * an ill-behaved Map.Entry that attempts to modify another
0N/A * Map.Entry when asked to perform an equality check.
0N/A */
0N/A private static class CheckedEntry<K,V,T> implements Map.Entry<K,V> {
0N/A private final Map.Entry<K, V> e;
0N/A private final Class<T> valueType;
0N/A
0N/A CheckedEntry(Map.Entry<K, V> e, Class<T> valueType) {
0N/A this.e = e;
0N/A this.valueType = valueType;
0N/A }
0N/A
0N/A public K getKey() { return e.getKey(); }
0N/A public V getValue() { return e.getValue(); }
0N/A public int hashCode() { return e.hashCode(); }
0N/A public String toString() { return e.toString(); }
0N/A
0N/A public V setValue(V value) {
0N/A if (value != null && !valueType.isInstance(value))
0N/A throw new ClassCastException(badValueMsg(value));
0N/A return e.setValue(value);
0N/A }
0N/A
0N/A private String badValueMsg(Object value) {
0N/A return "Attempt to insert " + value.getClass() +
0N/A " value into map with value type " + valueType;
0N/A }
0N/A
0N/A public boolean equals(Object o) {
0N/A if (o == this)
0N/A return true;
0N/A if (!(o instanceof Map.Entry))
0N/A return false;
0N/A return e.equals(new AbstractMap.SimpleImmutableEntry
3323N/A <>((Map.Entry<?,?>)o));
0N/A }
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a dynamically typesafe view of the specified sorted map.
0N/A * Any attempt to insert a mapping whose key or value have the wrong
0N/A * type will result in an immediate {@link ClassCastException}.
0N/A * Similarly, any attempt to modify the value currently associated with
0N/A * a key will result in an immediate {@link ClassCastException},
0N/A * whether the modification is attempted directly through the map
0N/A * itself, or through a {@link Map.Entry} instance obtained from the
0N/A * map's {@link Map#entrySet() entry set} view.
0N/A *
0N/A * <p>Assuming a map contains no incorrectly typed keys or values
0N/A * prior to the time a dynamically typesafe view is generated, and
0N/A * that all subsequent access to the map takes place through the view
0N/A * (or one of its collection views), it is <i>guaranteed</i> that the
0N/A * map cannot contain an incorrectly typed key or value.
0N/A *
0N/A * <p>A discussion of the use of dynamically typesafe views may be
0N/A * found in the documentation for the {@link #checkedCollection
0N/A * checkedCollection} method.
0N/A *
0N/A * <p>The returned map will be serializable if the specified map is
0N/A * serializable.
0N/A *
0N/A * <p>Since {@code null} is considered to be a value of any reference
0N/A * type, the returned map permits insertion of null keys or values
0N/A * whenever the backing map does.
0N/A *
0N/A * @param m the map for which a dynamically typesafe view is to be
0N/A * returned
0N/A * @param keyType the type of key that {@code m} is permitted to hold
0N/A * @param valueType the type of value that {@code m} is permitted to hold
0N/A * @return a dynamically typesafe view of the specified map
0N/A * @since 1.5
0N/A */
0N/A public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,
0N/A Class<K> keyType,
0N/A Class<V> valueType) {
3323N/A return new CheckedSortedMap<>(m, keyType, valueType);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class CheckedSortedMap<K,V> extends CheckedMap<K,V>
0N/A implements SortedMap<K,V>, Serializable
0N/A {
0N/A private static final long serialVersionUID = 1599671320688067438L;
0N/A
0N/A private final SortedMap<K, V> sm;
0N/A
0N/A CheckedSortedMap(SortedMap<K, V> m,
0N/A Class<K> keyType, Class<V> valueType) {
0N/A super(m, keyType, valueType);
0N/A sm = m;
0N/A }
0N/A
0N/A public Comparator<? super K> comparator() { return sm.comparator(); }
0N/A public K firstKey() { return sm.firstKey(); }
0N/A public K lastKey() { return sm.lastKey(); }
0N/A
0N/A public SortedMap<K,V> subMap(K fromKey, K toKey) {
0N/A return checkedSortedMap(sm.subMap(fromKey, toKey),
0N/A keyType, valueType);
0N/A }
0N/A public SortedMap<K,V> headMap(K toKey) {
0N/A return checkedSortedMap(sm.headMap(toKey), keyType, valueType);
0N/A }
0N/A public SortedMap<K,V> tailMap(K fromKey) {
0N/A return checkedSortedMap(sm.tailMap(fromKey), keyType, valueType);
0N/A }
0N/A }
0N/A
0N/A // Empty collections
0N/A
0N/A /**
0N/A * Returns an iterator that has no elements. More precisely,
0N/A *
0N/A * <ul compact>
0N/A *
0N/A * <li>{@link Iterator#hasNext hasNext} always returns {@code
0N/A * false}.
0N/A *
0N/A * <li>{@link Iterator#next next} always throws {@link
0N/A * NoSuchElementException}.
0N/A *
0N/A * <li>{@link Iterator#remove remove} always throws {@link
0N/A * IllegalStateException}.
0N/A *
0N/A * </ul>
0N/A *
0N/A * <p>Implementations of this method are permitted, but not
0N/A * required, to return the same object from multiple invocations.
0N/A *
0N/A * @return an empty iterator
0N/A * @since 1.7
0N/A */
0N/A @SuppressWarnings("unchecked")
0N/A public static <T> Iterator<T> emptyIterator() {
0N/A return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR;
0N/A }
0N/A
0N/A private static class EmptyIterator<E> implements Iterator<E> {
0N/A static final EmptyIterator<Object> EMPTY_ITERATOR
3323N/A = new EmptyIterator<>();
0N/A
0N/A public boolean hasNext() { return false; }
0N/A public E next() { throw new NoSuchElementException(); }
0N/A public void remove() { throw new IllegalStateException(); }
0N/A }
0N/A
0N/A /**
0N/A * Returns a list iterator that has no elements. More precisely,
0N/A *
0N/A * <ul compact>
0N/A *
0N/A * <li>{@link Iterator#hasNext hasNext} and {@link
0N/A * ListIterator#hasPrevious hasPrevious} always return {@code
0N/A * false}.
0N/A *
0N/A * <li>{@link Iterator#next next} and {@link ListIterator#previous
0N/A * previous} always throw {@link NoSuchElementException}.
0N/A *
0N/A * <li>{@link Iterator#remove remove} and {@link ListIterator#set
0N/A * set} always throw {@link IllegalStateException}.
0N/A *
0N/A * <li>{@link ListIterator#add add} always throws {@link
0N/A * UnsupportedOperationException}.
0N/A *
0N/A * <li>{@link ListIterator#nextIndex nextIndex} always returns
0N/A * {@code 0} .
0N/A *
0N/A * <li>{@link ListIterator#previousIndex previousIndex} always
0N/A * returns {@code -1}.
0N/A *
0N/A * </ul>
0N/A *
0N/A * <p>Implementations of this method are permitted, but not
0N/A * required, to return the same object from multiple invocations.
0N/A *
0N/A * @return an empty list iterator
0N/A * @since 1.7
0N/A */
0N/A @SuppressWarnings("unchecked")
0N/A public static <T> ListIterator<T> emptyListIterator() {
0N/A return (ListIterator<T>) EmptyListIterator.EMPTY_ITERATOR;
0N/A }
0N/A
0N/A private static class EmptyListIterator<E>
0N/A extends EmptyIterator<E>
0N/A implements ListIterator<E>
0N/A {
0N/A static final EmptyListIterator<Object> EMPTY_ITERATOR
3323N/A = new EmptyListIterator<>();
0N/A
0N/A public boolean hasPrevious() { return false; }
0N/A public E previous() { throw new NoSuchElementException(); }
0N/A public int nextIndex() { return 0; }
0N/A public int previousIndex() { return -1; }
0N/A public void set(E e) { throw new IllegalStateException(); }
0N/A public void add(E e) { throw new UnsupportedOperationException(); }
0N/A }
0N/A
0N/A /**
0N/A * Returns an enumeration that has no elements. More precisely,
0N/A *
0N/A * <ul compact>
0N/A *
0N/A * <li>{@link Enumeration#hasMoreElements hasMoreElements} always
0N/A * returns {@code false}.
0N/A *
0N/A * <li> {@link Enumeration#nextElement nextElement} always throws
0N/A * {@link NoSuchElementException}.
0N/A *
0N/A * </ul>
0N/A *
0N/A * <p>Implementations of this method are permitted, but not
0N/A * required, to return the same object from multiple invocations.
0N/A *
0N/A * @return an empty enumeration
0N/A * @since 1.7
0N/A */
0N/A @SuppressWarnings("unchecked")
0N/A public static <T> Enumeration<T> emptyEnumeration() {
0N/A return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION;
0N/A }
0N/A
0N/A private static class EmptyEnumeration<E> implements Enumeration<E> {
0N/A static final EmptyEnumeration<Object> EMPTY_ENUMERATION
3323N/A = new EmptyEnumeration<>();
0N/A
0N/A public boolean hasMoreElements() { return false; }
0N/A public E nextElement() { throw new NoSuchElementException(); }
0N/A }
0N/A
0N/A /**
0N/A * The empty set (immutable). This set is serializable.
0N/A *
0N/A * @see #emptySet()
0N/A */
0N/A @SuppressWarnings("unchecked")
3323N/A public static final Set EMPTY_SET = new EmptySet<>();
0N/A
0N/A /**
0N/A * Returns the empty set (immutable). This set is serializable.
0N/A * Unlike the like-named field, this method is parameterized.
0N/A *
0N/A * <p>This example illustrates the type-safe way to obtain an empty set:
0N/A * <pre>
0N/A * Set&lt;String&gt; s = Collections.emptySet();
0N/A * </pre>
0N/A * Implementation note: Implementations of this method need not
0N/A * create a separate <tt>Set</tt> object for each call. Using this
0N/A * method is likely to have comparable cost to using the like-named
0N/A * field. (Unlike this method, the field does not provide type safety.)
0N/A *
0N/A * @see #EMPTY_SET
0N/A * @since 1.5
0N/A */
0N/A @SuppressWarnings("unchecked")
0N/A public static final <T> Set<T> emptySet() {
0N/A return (Set<T>) EMPTY_SET;
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A private static class EmptySet<E>
0N/A extends AbstractSet<E>
0N/A implements Serializable
0N/A {
0N/A private static final long serialVersionUID = 1582296315990362920L;
0N/A
0N/A public Iterator<E> iterator() { return emptyIterator(); }
0N/A
0N/A public int size() {return 0;}
0N/A public boolean isEmpty() {return true;}
0N/A
0N/A public boolean contains(Object obj) {return false;}
0N/A public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
0N/A
0N/A public Object[] toArray() { return new Object[0]; }
0N/A
0N/A public <T> T[] toArray(T[] a) {
0N/A if (a.length > 0)
0N/A a[0] = null;
0N/A return a;
0N/A }
0N/A
0N/A // Preserves singleton property
0N/A private Object readResolve() {
0N/A return EMPTY_SET;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * The empty list (immutable). This list is serializable.
0N/A *
0N/A * @see #emptyList()
0N/A */
0N/A @SuppressWarnings("unchecked")
3323N/A public static final List EMPTY_LIST = new EmptyList<>();
0N/A
0N/A /**
0N/A * Returns the empty list (immutable). This list is serializable.
0N/A *
0N/A * <p>This example illustrates the type-safe way to obtain an empty list:
0N/A * <pre>
0N/A * List&lt;String&gt; s = Collections.emptyList();
0N/A * </pre>
0N/A * Implementation note: Implementations of this method need not
0N/A * create a separate <tt>List</tt> object for each call. Using this
0N/A * method is likely to have comparable cost to using the like-named
0N/A * field. (Unlike this method, the field does not provide type safety.)
0N/A *
0N/A * @see #EMPTY_LIST
0N/A * @since 1.5
0N/A */
0N/A @SuppressWarnings("unchecked")
0N/A public static final <T> List<T> emptyList() {
0N/A return (List<T>) EMPTY_LIST;
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A private static class EmptyList<E>
0N/A extends AbstractList<E>
0N/A implements RandomAccess, Serializable {
0N/A private static final long serialVersionUID = 8842843931221139166L;
0N/A
0N/A public Iterator<E> iterator() {
0N/A return emptyIterator();
0N/A }
0N/A public ListIterator<E> listIterator() {
0N/A return emptyListIterator();
0N/A }
0N/A
0N/A public int size() {return 0;}
0N/A public boolean isEmpty() {return true;}
0N/A
0N/A public boolean contains(Object obj) {return false;}
0N/A public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
0N/A
0N/A public Object[] toArray() { return new Object[0]; }
0N/A
0N/A public <T> T[] toArray(T[] a) {
0N/A if (a.length > 0)
0N/A a[0] = null;
0N/A return a;
0N/A }
0N/A
0N/A public E get(int index) {
0N/A throw new IndexOutOfBoundsException("Index: "+index);
0N/A }
0N/A
0N/A public boolean equals(Object o) {
0N/A return (o instanceof List) && ((List<?>)o).isEmpty();
0N/A }
0N/A
0N/A public int hashCode() { return 1; }
0N/A
0N/A // Preserves singleton property
0N/A private Object readResolve() {
0N/A return EMPTY_LIST;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * The empty map (immutable). This map is serializable.
0N/A *
0N/A * @see #emptyMap()
0N/A * @since 1.3
0N/A */
0N/A @SuppressWarnings("unchecked")
3323N/A public static final Map EMPTY_MAP = new EmptyMap<>();
0N/A
0N/A /**
0N/A * Returns the empty map (immutable). This map is serializable.
0N/A *
0N/A * <p>This example illustrates the type-safe way to obtain an empty set:
0N/A * <pre>
0N/A * Map&lt;String, Date&gt; s = Collections.emptyMap();
0N/A * </pre>
0N/A * Implementation note: Implementations of this method need not
0N/A * create a separate <tt>Map</tt> object for each call. Using this
0N/A * method is likely to have comparable cost to using the like-named
0N/A * field. (Unlike this method, the field does not provide type safety.)
0N/A *
0N/A * @see #EMPTY_MAP
0N/A * @since 1.5
0N/A */
0N/A @SuppressWarnings("unchecked")
0N/A public static final <K,V> Map<K,V> emptyMap() {
0N/A return (Map<K,V>) EMPTY_MAP;
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A private static class EmptyMap<K,V>
0N/A extends AbstractMap<K,V>
0N/A implements Serializable
0N/A {
0N/A private static final long serialVersionUID = 6428348081105594320L;
0N/A
0N/A public int size() {return 0;}
0N/A public boolean isEmpty() {return true;}
0N/A public boolean containsKey(Object key) {return false;}
0N/A public boolean containsValue(Object value) {return false;}
0N/A public V get(Object key) {return null;}
0N/A public Set<K> keySet() {return emptySet();}
0N/A public Collection<V> values() {return emptySet();}
0N/A public Set<Map.Entry<K,V>> entrySet() {return emptySet();}
0N/A
0N/A public boolean equals(Object o) {
0N/A return (o instanceof Map) && ((Map<?,?>)o).isEmpty();
0N/A }
0N/A
0N/A public int hashCode() {return 0;}
0N/A
0N/A // Preserves singleton property
0N/A private Object readResolve() {
0N/A return EMPTY_MAP;
0N/A }
0N/A }
0N/A
0N/A // Singleton collections
0N/A
0N/A /**
0N/A * Returns an immutable set containing only the specified object.
0N/A * The returned set is serializable.
0N/A *
0N/A * @param o the sole object to be stored in the returned set.
0N/A * @return an immutable set containing only the specified object.
0N/A */
0N/A public static <T> Set<T> singleton(T o) {
3323N/A return new SingletonSet<>(o);
0N/A }
0N/A
0N/A static <E> Iterator<E> singletonIterator(final E e) {
0N/A return new Iterator<E>() {
0N/A private boolean hasNext = true;
0N/A public boolean hasNext() {
0N/A return hasNext;
0N/A }
0N/A public E next() {
0N/A if (hasNext) {
0N/A hasNext = false;
0N/A return e;
0N/A }
0N/A throw new NoSuchElementException();
0N/A }
0N/A public void remove() {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A };
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A private static class SingletonSet<E>
0N/A extends AbstractSet<E>
0N/A implements Serializable
0N/A {
0N/A private static final long serialVersionUID = 3193687207550431679L;
0N/A
3203N/A private final E element;
0N/A
0N/A SingletonSet(E e) {element = e;}
0N/A
0N/A public Iterator<E> iterator() {
0N/A return singletonIterator(element);
0N/A }
0N/A
0N/A public int size() {return 1;}
0N/A
0N/A public boolean contains(Object o) {return eq(o, element);}
0N/A }
0N/A
0N/A /**
0N/A * Returns an immutable list containing only the specified object.
0N/A * The returned list is serializable.
0N/A *
0N/A * @param o the sole object to be stored in the returned list.
0N/A * @return an immutable list containing only the specified object.
0N/A * @since 1.3
0N/A */
0N/A public static <T> List<T> singletonList(T o) {
3323N/A return new SingletonList<>(o);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A private static class SingletonList<E>
0N/A extends AbstractList<E>
0N/A implements RandomAccess, Serializable {
0N/A
0N/A private static final long serialVersionUID = 3093736618740652951L;
0N/A
0N/A private final E element;
0N/A
0N/A SingletonList(E obj) {element = obj;}
0N/A
0N/A public Iterator<E> iterator() {
0N/A return singletonIterator(element);
0N/A }
0N/A
0N/A public int size() {return 1;}
0N/A
0N/A public boolean contains(Object obj) {return eq(obj, element);}
0N/A
0N/A public E get(int index) {
0N/A if (index != 0)
0N/A throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");
0N/A return element;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns an immutable map, mapping only the specified key to the
0N/A * specified value. The returned map is serializable.
0N/A *
0N/A * @param key the sole key to be stored in the returned map.
0N/A * @param value the value to which the returned map maps <tt>key</tt>.
0N/A * @return an immutable map containing only the specified key-value
0N/A * mapping.
0N/A * @since 1.3
0N/A */
0N/A public static <K,V> Map<K,V> singletonMap(K key, V value) {
3323N/A return new SingletonMap<>(key, value);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A private static class SingletonMap<K,V>
0N/A extends AbstractMap<K,V>
0N/A implements Serializable {
0N/A private static final long serialVersionUID = -6979724477215052911L;
0N/A
0N/A private final K k;
0N/A private final V v;
0N/A
0N/A SingletonMap(K key, V value) {
0N/A k = key;
0N/A v = value;
0N/A }
0N/A
0N/A public int size() {return 1;}
0N/A
0N/A public boolean isEmpty() {return false;}
0N/A
0N/A public boolean containsKey(Object key) {return eq(key, k);}
0N/A
0N/A public boolean containsValue(Object value) {return eq(value, v);}
0N/A
0N/A public V get(Object key) {return (eq(key, k) ? v : null);}
0N/A
0N/A private transient Set<K> keySet = null;
0N/A private transient Set<Map.Entry<K,V>> entrySet = null;
0N/A private transient Collection<V> values = null;
0N/A
0N/A public Set<K> keySet() {
0N/A if (keySet==null)
0N/A keySet = singleton(k);
0N/A return keySet;
0N/A }
0N/A
0N/A public Set<Map.Entry<K,V>> entrySet() {
0N/A if (entrySet==null)
0N/A entrySet = Collections.<Map.Entry<K,V>>singleton(
3323N/A new SimpleImmutableEntry<>(k, v));
0N/A return entrySet;
0N/A }
0N/A
0N/A public Collection<V> values() {
0N/A if (values==null)
0N/A values = singleton(v);
0N/A return values;
0N/A }
0N/A
0N/A }
0N/A
0N/A // Miscellaneous
0N/A
0N/A /**
0N/A * Returns an immutable list consisting of <tt>n</tt> copies of the
0N/A * specified object. The newly allocated data object is tiny (it contains
0N/A * a single reference to the data object). This method is useful in
0N/A * combination with the <tt>List.addAll</tt> method to grow lists.
0N/A * The returned list is serializable.
0N/A *
0N/A * @param n the number of elements in the returned list.
0N/A * @param o the element to appear repeatedly in the returned list.
0N/A * @return an immutable list consisting of <tt>n</tt> copies of the
0N/A * specified object.
3203N/A * @throws IllegalArgumentException if {@code n < 0}
0N/A * @see List#addAll(Collection)
0N/A * @see List#addAll(int, Collection)
0N/A */
0N/A public static <T> List<T> nCopies(int n, T o) {
0N/A if (n < 0)
0N/A throw new IllegalArgumentException("List length = " + n);
3323N/A return new CopiesList<>(n, o);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A private static class CopiesList<E>
0N/A extends AbstractList<E>
0N/A implements RandomAccess, Serializable
0N/A {
0N/A private static final long serialVersionUID = 2739099268398711800L;
0N/A
0N/A final int n;
0N/A final E element;
0N/A
0N/A CopiesList(int n, E e) {
0N/A assert n >= 0;
0N/A this.n = n;
0N/A element = e;
0N/A }
0N/A
0N/A public int size() {
0N/A return n;
0N/A }
0N/A
0N/A public boolean contains(Object obj) {
0N/A return n != 0 && eq(obj, element);
0N/A }
0N/A
0N/A public int indexOf(Object o) {
0N/A return contains(o) ? 0 : -1;
0N/A }
0N/A
0N/A public int lastIndexOf(Object o) {
0N/A return contains(o) ? n - 1 : -1;
0N/A }
0N/A
0N/A public E get(int index) {
0N/A if (index < 0 || index >= n)
0N/A throw new IndexOutOfBoundsException("Index: "+index+
0N/A ", Size: "+n);
0N/A return element;
0N/A }
0N/A
0N/A public Object[] toArray() {
0N/A final Object[] a = new Object[n];
0N/A if (element != null)
0N/A Arrays.fill(a, 0, n, element);
0N/A return a;
0N/A }
0N/A
0N/A public <T> T[] toArray(T[] a) {
0N/A final int n = this.n;
0N/A if (a.length < n) {
0N/A a = (T[])java.lang.reflect.Array
0N/A .newInstance(a.getClass().getComponentType(), n);
0N/A if (element != null)
0N/A Arrays.fill(a, 0, n, element);
0N/A } else {
0N/A Arrays.fill(a, 0, n, element);
0N/A if (a.length > n)
0N/A a[n] = null;
0N/A }
0N/A return a;
0N/A }
0N/A
0N/A public List<E> subList(int fromIndex, int toIndex) {
0N/A if (fromIndex < 0)
0N/A throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
0N/A if (toIndex > n)
0N/A throw new IndexOutOfBoundsException("toIndex = " + toIndex);
0N/A if (fromIndex > toIndex)
0N/A throw new IllegalArgumentException("fromIndex(" + fromIndex +
0N/A ") > toIndex(" + toIndex + ")");
3323N/A return new CopiesList<>(toIndex - fromIndex, element);
0N/A }
0N/A }
0N/A
0N/A /**
3878N/A * Returns a comparator that imposes the reverse of the <em>natural
3878N/A * ordering</em> on a collection of objects that implement the
3878N/A * {@code Comparable} interface. (The natural ordering is the ordering
3878N/A * imposed by the objects' own {@code compareTo} method.) This enables a
0N/A * simple idiom for sorting (or maintaining) collections (or arrays) of
3878N/A * objects that implement the {@code Comparable} interface in
3878N/A * reverse-natural-order. For example, suppose {@code a} is an array of
0N/A * strings. Then: <pre>
0N/A * Arrays.sort(a, Collections.reverseOrder());
0N/A * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>
0N/A *
0N/A * The returned comparator is serializable.
0N/A *
3878N/A * @return A comparator that imposes the reverse of the <i>natural
0N/A * ordering</i> on a collection of objects that implement
0N/A * the <tt>Comparable</tt> interface.
0N/A * @see Comparable
0N/A */
0N/A public static <T> Comparator<T> reverseOrder() {
0N/A return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A private static class ReverseComparator
0N/A implements Comparator<Comparable<Object>>, Serializable {
0N/A
0N/A private static final long serialVersionUID = 7207038068494060240L;
0N/A
0N/A static final ReverseComparator REVERSE_ORDER
0N/A = new ReverseComparator();
0N/A
0N/A public int compare(Comparable<Object> c1, Comparable<Object> c2) {
0N/A return c2.compareTo(c1);
0N/A }
0N/A
0N/A private Object readResolve() { return reverseOrder(); }
0N/A }
0N/A
0N/A /**
0N/A * Returns a comparator that imposes the reverse ordering of the specified
3878N/A * comparator. If the specified comparator is {@code null}, this method is
0N/A * equivalent to {@link #reverseOrder()} (in other words, it returns a
3878N/A * comparator that imposes the reverse of the <em>natural ordering</em> on
3878N/A * a collection of objects that implement the Comparable interface).
0N/A *
0N/A * <p>The returned comparator is serializable (assuming the specified
3878N/A * comparator is also serializable or {@code null}).
0N/A *
3878N/A * @param cmp a comparator who's ordering is to be reversed by the returned
3878N/A * comparator or {@code null}
3878N/A * @return A comparator that imposes the reverse ordering of the
3878N/A * specified comparator.
0N/A * @since 1.5
0N/A */
0N/A public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) {
0N/A if (cmp == null)
0N/A return reverseOrder();
0N/A
0N/A if (cmp instanceof ReverseComparator2)
0N/A return ((ReverseComparator2<T>)cmp).cmp;
0N/A
3323N/A return new ReverseComparator2<>(cmp);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A private static class ReverseComparator2<T> implements Comparator<T>,
0N/A Serializable
0N/A {
0N/A private static final long serialVersionUID = 4374092139857L;
0N/A
0N/A /**
0N/A * The comparator specified in the static factory. This will never
0N/A * be null, as the static factory returns a ReverseComparator
0N/A * instance if its argument is null.
0N/A *
0N/A * @serial
0N/A */
0N/A final Comparator<T> cmp;
0N/A
0N/A ReverseComparator2(Comparator<T> cmp) {
0N/A assert cmp != null;
0N/A this.cmp = cmp;
0N/A }
0N/A
0N/A public int compare(T t1, T t2) {
0N/A return cmp.compare(t2, t1);
0N/A }
0N/A
0N/A public boolean equals(Object o) {
0N/A return (o == this) ||
0N/A (o instanceof ReverseComparator2 &&
0N/A cmp.equals(((ReverseComparator2)o).cmp));
0N/A }
0N/A
0N/A public int hashCode() {
0N/A return cmp.hashCode() ^ Integer.MIN_VALUE;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns an enumeration over the specified collection. This provides
0N/A * interoperability with legacy APIs that require an enumeration
0N/A * as input.
0N/A *
0N/A * @param c the collection for which an enumeration is to be returned.
0N/A * @return an enumeration over the specified collection.
0N/A * @see Enumeration
0N/A */
0N/A public static <T> Enumeration<T> enumeration(final Collection<T> c) {
0N/A return new Enumeration<T>() {
0N/A private final Iterator<T> i = c.iterator();
0N/A
0N/A public boolean hasMoreElements() {
0N/A return i.hasNext();
0N/A }
0N/A
0N/A public T nextElement() {
0N/A return i.next();
0N/A }
0N/A };
0N/A }
0N/A
0N/A /**
0N/A * Returns an array list containing the elements returned by the
0N/A * specified enumeration in the order they are returned by the
0N/A * enumeration. This method provides interoperability between
0N/A * legacy APIs that return enumerations and new APIs that require
0N/A * collections.
0N/A *
0N/A * @param e enumeration providing elements for the returned
0N/A * array list
0N/A * @return an array list containing the elements returned
0N/A * by the specified enumeration.
0N/A * @since 1.4
0N/A * @see Enumeration
0N/A * @see ArrayList
0N/A */
0N/A public static <T> ArrayList<T> list(Enumeration<T> e) {
3323N/A ArrayList<T> l = new ArrayList<>();
0N/A while (e.hasMoreElements())
0N/A l.add(e.nextElement());
0N/A return l;
0N/A }
0N/A
0N/A /**
0N/A * Returns true if the specified arguments are equal, or both null.
0N/A */
0N/A static boolean eq(Object o1, Object o2) {
0N/A return o1==null ? o2==null : o1.equals(o2);
0N/A }
0N/A
0N/A /**
0N/A * Returns the number of elements in the specified collection equal to the
0N/A * specified object. More formally, returns the number of elements
0N/A * <tt>e</tt> in the collection such that
0N/A * <tt>(o == null ? e == null : o.equals(e))</tt>.
0N/A *
0N/A * @param c the collection in which to determine the frequency
0N/A * of <tt>o</tt>
0N/A * @param o the object whose frequency is to be determined
0N/A * @throws NullPointerException if <tt>c</tt> is null
0N/A * @since 1.5
0N/A */
0N/A public static int frequency(Collection<?> c, Object o) {
0N/A int result = 0;
0N/A if (o == null) {
0N/A for (Object e : c)
0N/A if (e == null)
0N/A result++;
0N/A } else {
0N/A for (Object e : c)
0N/A if (o.equals(e))
0N/A result++;
0N/A }
0N/A return result;
0N/A }
0N/A
0N/A /**
3398N/A * Returns {@code true} if the two specified collections have no
0N/A * elements in common.
0N/A *
0N/A * <p>Care must be exercised if this method is used on collections that
3398N/A * do not comply with the general contract for {@code Collection}.
0N/A * Implementations may elect to iterate over either collection and test
0N/A * for containment in the other collection (or to perform any equivalent
0N/A * computation). If either collection uses a nonstandard equality test
3398N/A * (as does a {@link SortedSet} whose ordering is not <em>compatible with
3398N/A * equals</em>, or the key set of an {@link IdentityHashMap}), both
0N/A * collections must use the same nonstandard equality test, or the
0N/A * result of this method is undefined.
0N/A *
3398N/A * <p>Care must also be exercised when using collections that have
3398N/A * restrictions on the elements that they may contain. Collection
3398N/A * implementations are allowed to throw exceptions for any operation
3398N/A * involving elements they deem ineligible. For absolute safety the
3398N/A * specified collections should contain only elements which are
3398N/A * eligible elements for both collections.
3398N/A *
0N/A * <p>Note that it is permissible to pass the same collection in both
3398N/A * parameters, in which case the method will return {@code true} if and
3398N/A * only if the collection is empty.
0N/A *
0N/A * @param c1 a collection
0N/A * @param c2 a collection
3398N/A * @return {@code true} if the two specified collections have no
3398N/A * elements in common.
3398N/A * @throws NullPointerException if either collection is {@code null}.
3398N/A * @throws NullPointerException if one collection contains a {@code null}
3398N/A * element and {@code null} is not an eligible element for the other collection.
4106N/A * (<a href="Collection.html#optional-restrictions">optional</a>)
3398N/A * @throws ClassCastException if one collection contains an element that is
4106N/A * of a type which is ineligible for the other collection.
4106N/A * (<a href="Collection.html#optional-restrictions">optional</a>)
0N/A * @since 1.5
0N/A */
0N/A public static boolean disjoint(Collection<?> c1, Collection<?> c2) {
3398N/A // The collection to be used for contains(). Preference is given to
3398N/A // the collection who's contains() has lower O() complexity.
3398N/A Collection<?> contains = c2;
3398N/A // The collection to be iterated. If the collections' contains() impl
3398N/A // are of different O() complexity, the collection with slower
3398N/A // contains() will be used for iteration. For collections who's
3398N/A // contains() are of the same complexity then best performance is
3398N/A // achieved by iterating the smaller collection.
3398N/A Collection<?> iterate = c1;
3398N/A
3398N/A // Performance optimization cases. The heuristics:
3398N/A // 1. Generally iterate over c1.
3398N/A // 2. If c1 is a Set then iterate over c2.
3398N/A // 3. If either collection is empty then result is always true.
3398N/A // 4. Iterate over the smaller Collection.
3398N/A if (c1 instanceof Set) {
3398N/A // Use c1 for contains as a Set's contains() is expected to perform
3398N/A // better than O(N/2)
3398N/A iterate = c2;
3398N/A contains = c1;
3398N/A } else if (!(c2 instanceof Set)) {
3398N/A // Both are mere Collections. Iterate over smaller collection.
3398N/A // Example: If c1 contains 3 elements and c2 contains 50 elements and
3398N/A // assuming contains() requires ceiling(N/2) comparisons then
3398N/A // checking for all c1 elements in c2 would require 75 comparisons
3398N/A // (3 * ceiling(50/2)) vs. checking all c2 elements in c1 requiring
3398N/A // 100 comparisons (50 * ceiling(3/2)).
3398N/A int c1size = c1.size();
3398N/A int c2size = c2.size();
3398N/A if (c1size == 0 || c2size == 0) {
3398N/A // At least one collection is empty. Nothing will match.
3398N/A return true;
3398N/A }
3398N/A
3398N/A if (c1size > c2size) {
3398N/A iterate = c2;
3398N/A contains = c1;
3398N/A }
0N/A }
0N/A
3398N/A for (Object e : iterate) {
3398N/A if (contains.contains(e)) {
3398N/A // Found a common element. Collections are not disjoint.
0N/A return false;
3398N/A }
3398N/A }
3398N/A
3398N/A // No common elements were found.
0N/A return true;
0N/A }
0N/A
0N/A /**
0N/A * Adds all of the specified elements to the specified collection.
0N/A * Elements to be added may be specified individually or as an array.
0N/A * The behavior of this convenience method is identical to that of
0N/A * <tt>c.addAll(Arrays.asList(elements))</tt>, but this method is likely
0N/A * to run significantly faster under most implementations.
0N/A *
0N/A * <p>When elements are specified individually, this method provides a
0N/A * convenient way to add a few elements to an existing collection:
0N/A * <pre>
0N/A * Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");
0N/A * </pre>
0N/A *
0N/A * @param c the collection into which <tt>elements</tt> are to be inserted
0N/A * @param elements the elements to insert into <tt>c</tt>
0N/A * @return <tt>true</tt> if the collection changed as a result of the call
0N/A * @throws UnsupportedOperationException if <tt>c</tt> does not support
0N/A * the <tt>add</tt> operation
0N/A * @throws NullPointerException if <tt>elements</tt> contains one or more
0N/A * null values and <tt>c</tt> does not permit null elements, or
0N/A * if <tt>c</tt> or <tt>elements</tt> are <tt>null</tt>
0N/A * @throws IllegalArgumentException if some property of a value in
0N/A * <tt>elements</tt> prevents it from being added to <tt>c</tt>
0N/A * @see Collection#addAll(Collection)
0N/A * @since 1.5
0N/A */
3464N/A @SafeVarargs
0N/A public static <T> boolean addAll(Collection<? super T> c, T... elements) {
0N/A boolean result = false;
0N/A for (T element : elements)
0N/A result |= c.add(element);
0N/A return result;
0N/A }
0N/A
0N/A /**
0N/A * Returns a set backed by the specified map. The resulting set displays
0N/A * the same ordering, concurrency, and performance characteristics as the
0N/A * backing map. In essence, this factory method provides a {@link Set}
0N/A * implementation corresponding to any {@link Map} implementation. There
0N/A * is no need to use this method on a {@link Map} implementation that
0N/A * already has a corresponding {@link Set} implementation (such as {@link
0N/A * HashMap} or {@link TreeMap}).
0N/A *
0N/A * <p>Each method invocation on the set returned by this method results in
0N/A * exactly one method invocation on the backing map or its <tt>keySet</tt>
0N/A * view, with one exception. The <tt>addAll</tt> method is implemented
0N/A * as a sequence of <tt>put</tt> invocations on the backing map.
0N/A *
0N/A * <p>The specified map must be empty at the time this method is invoked,
0N/A * and should not be accessed directly after this method returns. These
0N/A * conditions are ensured if the map is created empty, passed directly
0N/A * to this method, and no reference to the map is retained, as illustrated
0N/A * in the following code fragment:
0N/A * <pre>
0N/A * Set&lt;Object&gt; weakHashSet = Collections.newSetFromMap(
0N/A * new WeakHashMap&lt;Object, Boolean&gt;());
0N/A * </pre>
0N/A *
0N/A * @param map the backing map
0N/A * @return the set backed by the map
0N/A * @throws IllegalArgumentException if <tt>map</tt> is not empty
0N/A * @since 1.6
0N/A */
0N/A public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
3323N/A return new SetFromMap<>(map);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A private static class SetFromMap<E> extends AbstractSet<E>
0N/A implements Set<E>, Serializable
0N/A {
0N/A private final Map<E, Boolean> m; // The backing map
0N/A private transient Set<E> s; // Its keySet
0N/A
0N/A SetFromMap(Map<E, Boolean> map) {
0N/A if (!map.isEmpty())
0N/A throw new IllegalArgumentException("Map is non-empty");
0N/A m = map;
0N/A s = map.keySet();
0N/A }
0N/A
0N/A public void clear() { m.clear(); }
0N/A public int size() { return m.size(); }
0N/A public boolean isEmpty() { return m.isEmpty(); }
0N/A public boolean contains(Object o) { return m.containsKey(o); }
0N/A public boolean remove(Object o) { return m.remove(o) != null; }
0N/A public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; }
0N/A public Iterator<E> iterator() { return s.iterator(); }
0N/A public Object[] toArray() { return s.toArray(); }
0N/A public <T> T[] toArray(T[] a) { return s.toArray(a); }
0N/A public String toString() { return s.toString(); }
0N/A public int hashCode() { return s.hashCode(); }
0N/A public boolean equals(Object o) { return o == this || s.equals(o); }
0N/A public boolean containsAll(Collection<?> c) {return s.containsAll(c);}
0N/A public boolean removeAll(Collection<?> c) {return s.removeAll(c);}
0N/A public boolean retainAll(Collection<?> c) {return s.retainAll(c);}
0N/A // addAll is the only inherited implementation
0N/A
0N/A private static final long serialVersionUID = 2454657854757543876L;
0N/A
0N/A private void readObject(java.io.ObjectInputStream stream)
0N/A throws IOException, ClassNotFoundException
0N/A {
0N/A stream.defaultReadObject();
0N/A s = m.keySet();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)
0N/A * {@link Queue}. Method <tt>add</tt> is mapped to <tt>push</tt>,
0N/A * <tt>remove</tt> is mapped to <tt>pop</tt> and so on. This
0N/A * view can be useful when you would like to use a method
0N/A * requiring a <tt>Queue</tt> but you need Lifo ordering.
0N/A *
0N/A * <p>Each method invocation on the queue returned by this method
0N/A * results in exactly one method invocation on the backing deque, with
0N/A * one exception. The {@link Queue#addAll addAll} method is
0N/A * implemented as a sequence of {@link Deque#addFirst addFirst}
0N/A * invocations on the backing deque.
0N/A *
0N/A * @param deque the deque
0N/A * @return the queue
0N/A * @since 1.6
0N/A */
0N/A public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
3323N/A return new AsLIFOQueue<>(deque);
0N/A }
0N/A
0N/A /**
0N/A * @serial include
0N/A */
0N/A static class AsLIFOQueue<E> extends AbstractQueue<E>
0N/A implements Queue<E>, Serializable {
0N/A private static final long serialVersionUID = 1802017725587941708L;
0N/A private final Deque<E> q;
0N/A AsLIFOQueue(Deque<E> q) { this.q = q; }
0N/A public boolean add(E e) { q.addFirst(e); return true; }
0N/A public boolean offer(E e) { return q.offerFirst(e); }
0N/A public E poll() { return q.pollFirst(); }
0N/A public E remove() { return q.removeFirst(); }
0N/A public E peek() { return q.peekFirst(); }
0N/A public E element() { return q.getFirst(); }
0N/A public void clear() { q.clear(); }
0N/A public int size() { return q.size(); }
0N/A public boolean isEmpty() { return q.isEmpty(); }
0N/A public boolean contains(Object o) { return q.contains(o); }
0N/A public boolean remove(Object o) { return q.remove(o); }
0N/A public Iterator<E> iterator() { return q.iterator(); }
0N/A public Object[] toArray() { return q.toArray(); }
0N/A public <T> T[] toArray(T[] a) { return q.toArray(a); }
0N/A public String toString() { return q.toString(); }
0N/A public boolean containsAll(Collection<?> c) {return q.containsAll(c);}
0N/A public boolean removeAll(Collection<?> c) {return q.removeAll(c);}
0N/A public boolean retainAll(Collection<?> c) {return q.retainAll(c);}
0N/A // We use inherited addAll; forwarding addAll would be wrong
0N/A }
0N/A}