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