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