rt/emul/compact/src/main/java/java/util/Arrays.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 26 Feb 2013 16:54:16 +0100
changeset 772 d382dacfd73f
parent 636 emul/compact/src/main/java/java/util/Arrays.java@8d0be6a9a809
permissions -rw-r--r--
Moving modules around so the runtime is under one master pom and can be built without building other modules that are in the repository
     1 /*
     2  * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    25 
    26 package java.util;
    27 
    28 import java.lang.reflect.*;
    29 
    30 /**
    31  * This class contains various methods for manipulating arrays (such as
    32  * sorting and searching). This class also contains a static factory
    33  * that allows arrays to be viewed as lists.
    34  *
    35  * <p>The methods in this class all throw a {@code NullPointerException},
    36  * if the specified array reference is null, except where noted.
    37  *
    38  * <p>The documentation for the methods contained in this class includes
    39  * briefs description of the <i>implementations</i>. Such descriptions should
    40  * be regarded as <i>implementation notes</i>, rather than parts of the
    41  * <i>specification</i>. Implementors should feel free to substitute other
    42  * algorithms, so long as the specification itself is adhered to. (For
    43  * example, the algorithm used by {@code sort(Object[])} does not have to be
    44  * a MergeSort, but it does have to be <i>stable</i>.)
    45  *
    46  * <p>This class is a member of the
    47  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
    48  * Java Collections Framework</a>.
    49  *
    50  * @author Josh Bloch
    51  * @author Neal Gafter
    52  * @author John Rose
    53  * @since  1.2
    54  */
    55 public class Arrays {
    56 
    57     // Suppresses default constructor, ensuring non-instantiability.
    58     private Arrays() {}
    59 
    60     /*
    61      * Sorting of primitive type arrays.
    62      */
    63 
    64     /**
    65      * Sorts the specified array into ascending numerical order.
    66      *
    67      * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
    68      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
    69      * offers O(n log(n)) performance on many data sets that cause other
    70      * quicksorts to degrade to quadratic performance, and is typically
    71      * faster than traditional (one-pivot) Quicksort implementations.
    72      *
    73      * @param a the array to be sorted
    74      */
    75     public static void sort(int[] a) {
    76         DualPivotQuicksort.sort(a);
    77     }
    78 
    79     /**
    80      * Sorts the specified range of the array into ascending order. The range
    81      * to be sorted extends from the index {@code fromIndex}, inclusive, to
    82      * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
    83      * the range to be sorted is empty.
    84      *
    85      * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
    86      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
    87      * offers O(n log(n)) performance on many data sets that cause other
    88      * quicksorts to degrade to quadratic performance, and is typically
    89      * faster than traditional (one-pivot) Quicksort implementations.
    90      *
    91      * @param a the array to be sorted
    92      * @param fromIndex the index of the first element, inclusive, to be sorted
    93      * @param toIndex the index of the last element, exclusive, to be sorted
    94      *
    95      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
    96      * @throws ArrayIndexOutOfBoundsException
    97      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
    98      */
    99     public static void sort(int[] a, int fromIndex, int toIndex) {
   100         rangeCheck(a.length, fromIndex, toIndex);
   101         DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
   102     }
   103 
   104     /**
   105      * Sorts the specified array into ascending numerical order.
   106      *
   107      * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
   108      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
   109      * offers O(n log(n)) performance on many data sets that cause other
   110      * quicksorts to degrade to quadratic performance, and is typically
   111      * faster than traditional (one-pivot) Quicksort implementations.
   112      *
   113      * @param a the array to be sorted
   114      */
   115     public static void sort(long[] a) {
   116         DualPivotQuicksort.sort(a);
   117     }
   118 
   119     /**
   120      * Sorts the specified range of the array into ascending order. The range
   121      * to be sorted extends from the index {@code fromIndex}, inclusive, to
   122      * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
   123      * the range to be sorted is empty.
   124      *
   125      * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
   126      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
   127      * offers O(n log(n)) performance on many data sets that cause other
   128      * quicksorts to degrade to quadratic performance, and is typically
   129      * faster than traditional (one-pivot) Quicksort implementations.
   130      *
   131      * @param a the array to be sorted
   132      * @param fromIndex the index of the first element, inclusive, to be sorted
   133      * @param toIndex the index of the last element, exclusive, to be sorted
   134      *
   135      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
   136      * @throws ArrayIndexOutOfBoundsException
   137      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
   138      */
   139     public static void sort(long[] a, int fromIndex, int toIndex) {
   140         rangeCheck(a.length, fromIndex, toIndex);
   141         DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
   142     }
   143 
   144     /**
   145      * Sorts the specified array into ascending numerical order.
   146      *
   147      * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
   148      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
   149      * offers O(n log(n)) performance on many data sets that cause other
   150      * quicksorts to degrade to quadratic performance, and is typically
   151      * faster than traditional (one-pivot) Quicksort implementations.
   152      *
   153      * @param a the array to be sorted
   154      */
   155     public static void sort(short[] a) {
   156         DualPivotQuicksort.sort(a);
   157     }
   158 
   159     /**
   160      * Sorts the specified range of the array into ascending order. The range
   161      * to be sorted extends from the index {@code fromIndex}, inclusive, to
   162      * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
   163      * the range to be sorted is empty.
   164      *
   165      * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
   166      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
   167      * offers O(n log(n)) performance on many data sets that cause other
   168      * quicksorts to degrade to quadratic performance, and is typically
   169      * faster than traditional (one-pivot) Quicksort implementations.
   170      *
   171      * @param a the array to be sorted
   172      * @param fromIndex the index of the first element, inclusive, to be sorted
   173      * @param toIndex the index of the last element, exclusive, to be sorted
   174      *
   175      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
   176      * @throws ArrayIndexOutOfBoundsException
   177      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
   178      */
   179     public static void sort(short[] a, int fromIndex, int toIndex) {
   180         rangeCheck(a.length, fromIndex, toIndex);
   181         DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
   182     }
   183 
   184     /**
   185      * Sorts the specified array into ascending numerical order.
   186      *
   187      * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
   188      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
   189      * offers O(n log(n)) performance on many data sets that cause other
   190      * quicksorts to degrade to quadratic performance, and is typically
   191      * faster than traditional (one-pivot) Quicksort implementations.
   192      *
   193      * @param a the array to be sorted
   194      */
   195     public static void sort(char[] a) {
   196         DualPivotQuicksort.sort(a);
   197     }
   198 
   199     /**
   200      * Sorts the specified range of the array into ascending order. The range
   201      * to be sorted extends from the index {@code fromIndex}, inclusive, to
   202      * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
   203      * the range to be sorted is empty.
   204      *
   205      * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
   206      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
   207      * offers O(n log(n)) performance on many data sets that cause other
   208      * quicksorts to degrade to quadratic performance, and is typically
   209      * faster than traditional (one-pivot) Quicksort implementations.
   210      *
   211      * @param a the array to be sorted
   212      * @param fromIndex the index of the first element, inclusive, to be sorted
   213      * @param toIndex the index of the last element, exclusive, to be sorted
   214      *
   215      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
   216      * @throws ArrayIndexOutOfBoundsException
   217      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
   218      */
   219     public static void sort(char[] a, int fromIndex, int toIndex) {
   220         rangeCheck(a.length, fromIndex, toIndex);
   221         DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
   222     }
   223 
   224     /**
   225      * Sorts the specified array into ascending numerical order.
   226      *
   227      * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
   228      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
   229      * offers O(n log(n)) performance on many data sets that cause other
   230      * quicksorts to degrade to quadratic performance, and is typically
   231      * faster than traditional (one-pivot) Quicksort implementations.
   232      *
   233      * @param a the array to be sorted
   234      */
   235     public static void sort(byte[] a) {
   236         DualPivotQuicksort.sort(a);
   237     }
   238 
   239     /**
   240      * Sorts the specified range of the array into ascending order. The range
   241      * to be sorted extends from the index {@code fromIndex}, inclusive, to
   242      * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
   243      * the range to be sorted is empty.
   244      *
   245      * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
   246      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
   247      * offers O(n log(n)) performance on many data sets that cause other
   248      * quicksorts to degrade to quadratic performance, and is typically
   249      * faster than traditional (one-pivot) Quicksort implementations.
   250      *
   251      * @param a the array to be sorted
   252      * @param fromIndex the index of the first element, inclusive, to be sorted
   253      * @param toIndex the index of the last element, exclusive, to be sorted
   254      *
   255      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
   256      * @throws ArrayIndexOutOfBoundsException
   257      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
   258      */
   259     public static void sort(byte[] a, int fromIndex, int toIndex) {
   260         rangeCheck(a.length, fromIndex, toIndex);
   261         DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
   262     }
   263 
   264     /**
   265      * Sorts the specified array into ascending numerical order.
   266      *
   267      * <p>The {@code <} relation does not provide a total order on all float
   268      * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
   269      * value compares neither less than, greater than, nor equal to any value,
   270      * even itself. This method uses the total order imposed by the method
   271      * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
   272      * {@code 0.0f} and {@code Float.NaN} is considered greater than any
   273      * other value and all {@code Float.NaN} values are considered equal.
   274      *
   275      * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
   276      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
   277      * offers O(n log(n)) performance on many data sets that cause other
   278      * quicksorts to degrade to quadratic performance, and is typically
   279      * faster than traditional (one-pivot) Quicksort implementations.
   280      *
   281      * @param a the array to be sorted
   282      */
   283     public static void sort(float[] a) {
   284         DualPivotQuicksort.sort(a);
   285     }
   286 
   287     /**
   288      * Sorts the specified range of the array into ascending order. The range
   289      * to be sorted extends from the index {@code fromIndex}, inclusive, to
   290      * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
   291      * the range to be sorted is empty.
   292      *
   293      * <p>The {@code <} relation does not provide a total order on all float
   294      * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
   295      * value compares neither less than, greater than, nor equal to any value,
   296      * even itself. This method uses the total order imposed by the method
   297      * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
   298      * {@code 0.0f} and {@code Float.NaN} is considered greater than any
   299      * other value and all {@code Float.NaN} values are considered equal.
   300      *
   301      * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
   302      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
   303      * offers O(n log(n)) performance on many data sets that cause other
   304      * quicksorts to degrade to quadratic performance, and is typically
   305      * faster than traditional (one-pivot) Quicksort implementations.
   306      *
   307      * @param a the array to be sorted
   308      * @param fromIndex the index of the first element, inclusive, to be sorted
   309      * @param toIndex the index of the last element, exclusive, to be sorted
   310      *
   311      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
   312      * @throws ArrayIndexOutOfBoundsException
   313      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
   314      */
   315     public static void sort(float[] a, int fromIndex, int toIndex) {
   316         rangeCheck(a.length, fromIndex, toIndex);
   317         DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
   318     }
   319 
   320     /**
   321      * Sorts the specified array into ascending numerical order.
   322      *
   323      * <p>The {@code <} relation does not provide a total order on all double
   324      * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
   325      * value compares neither less than, greater than, nor equal to any value,
   326      * even itself. This method uses the total order imposed by the method
   327      * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
   328      * {@code 0.0d} and {@code Double.NaN} is considered greater than any
   329      * other value and all {@code Double.NaN} values are considered equal.
   330      *
   331      * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
   332      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
   333      * offers O(n log(n)) performance on many data sets that cause other
   334      * quicksorts to degrade to quadratic performance, and is typically
   335      * faster than traditional (one-pivot) Quicksort implementations.
   336      *
   337      * @param a the array to be sorted
   338      */
   339     public static void sort(double[] a) {
   340         DualPivotQuicksort.sort(a);
   341     }
   342 
   343     /**
   344      * Sorts the specified range of the array into ascending order. The range
   345      * to be sorted extends from the index {@code fromIndex}, inclusive, to
   346      * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
   347      * the range to be sorted is empty.
   348      *
   349      * <p>The {@code <} relation does not provide a total order on all double
   350      * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
   351      * value compares neither less than, greater than, nor equal to any value,
   352      * even itself. This method uses the total order imposed by the method
   353      * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
   354      * {@code 0.0d} and {@code Double.NaN} is considered greater than any
   355      * other value and all {@code Double.NaN} values are considered equal.
   356      *
   357      * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
   358      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
   359      * offers O(n log(n)) performance on many data sets that cause other
   360      * quicksorts to degrade to quadratic performance, and is typically
   361      * faster than traditional (one-pivot) Quicksort implementations.
   362      *
   363      * @param a the array to be sorted
   364      * @param fromIndex the index of the first element, inclusive, to be sorted
   365      * @param toIndex the index of the last element, exclusive, to be sorted
   366      *
   367      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
   368      * @throws ArrayIndexOutOfBoundsException
   369      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
   370      */
   371     public static void sort(double[] a, int fromIndex, int toIndex) {
   372         rangeCheck(a.length, fromIndex, toIndex);
   373         DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
   374     }
   375 
   376     /*
   377      * Sorting of complex type arrays.
   378      */
   379 
   380     /**
   381      * Old merge sort implementation can be selected (for
   382      * compatibility with broken comparators) using a system property.
   383      * Cannot be a static boolean in the enclosing class due to
   384      * circular dependencies. To be removed in a future release.
   385      */
   386     static final class LegacyMergeSort {
   387         private static final boolean userRequested = false;
   388     }
   389 
   390     /*
   391      * If this platform has an optimizing VM, check whether ComparableTimSort
   392      * offers any performance benefit over TimSort in conjunction with a
   393      * comparator that returns:
   394      *    {@code ((Comparable)first).compareTo(Second)}.
   395      * If not, you are better off deleting ComparableTimSort to
   396      * eliminate the code duplication.  In other words, the commented
   397      * out code below is the preferable implementation for sorting
   398      * arrays of Comparables if it offers sufficient performance.
   399      */
   400 
   401 //    /**
   402 //     * A comparator that implements the natural ordering of a group of
   403 //     * mutually comparable elements.  Using this comparator saves us
   404 //     * from duplicating most of the code in this file (one version for
   405 //     * Comparables, one for explicit Comparators).
   406 //     */
   407 //    private static final Comparator<Object> NATURAL_ORDER =
   408 //            new Comparator<Object>() {
   409 //        @SuppressWarnings("unchecked")
   410 //        public int compare(Object first, Object second) {
   411 //            return ((Comparable<Object>)first).compareTo(second);
   412 //        }
   413 //    };
   414 //
   415 //    public static void sort(Object[] a) {
   416 //        sort(a, 0, a.length, NATURAL_ORDER);
   417 //    }
   418 //
   419 //    public static void sort(Object[] a, int fromIndex, int toIndex) {
   420 //        sort(a, fromIndex, toIndex, NATURAL_ORDER);
   421 //    }
   422 
   423     /**
   424      * Sorts the specified array of objects into ascending order, according
   425      * to the {@linkplain Comparable natural ordering} of its elements.
   426      * All elements in the array must implement the {@link Comparable}
   427      * interface.  Furthermore, all elements in the array must be
   428      * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)} must
   429      * not throw a {@code ClassCastException} for any elements {@code e1}
   430      * and {@code e2} in the array).
   431      *
   432      * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
   433      * not be reordered as a result of the sort.
   434      *
   435      * <p>Implementation note: This implementation is a stable, adaptive,
   436      * iterative mergesort that requires far fewer than n lg(n) comparisons
   437      * when the input array is partially sorted, while offering the
   438      * performance of a traditional mergesort when the input array is
   439      * randomly ordered.  If the input array is nearly sorted, the
   440      * implementation requires approximately n comparisons.  Temporary
   441      * storage requirements vary from a small constant for nearly sorted
   442      * input arrays to n/2 object references for randomly ordered input
   443      * arrays.
   444      *
   445      * <p>The implementation takes equal advantage of ascending and
   446      * descending order in its input array, and can take advantage of
   447      * ascending and descending order in different parts of the the same
   448      * input array.  It is well-suited to merging two or more sorted arrays:
   449      * simply concatenate the arrays and sort the resulting array.
   450      *
   451      * <p>The implementation was adapted from Tim Peters's list sort for Python
   452      * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
   453      * TimSort</a>).  It uses techiques from Peter McIlroy's "Optimistic
   454      * Sorting and Information Theoretic Complexity", in Proceedings of the
   455      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
   456      * January 1993.
   457      *
   458      * @param a the array to be sorted
   459      * @throws ClassCastException if the array contains elements that are not
   460      *         <i>mutually comparable</i> (for example, strings and integers)
   461      * @throws IllegalArgumentException (optional) if the natural
   462      *         ordering of the array elements is found to violate the
   463      *         {@link Comparable} contract
   464      */
   465     public static void sort(Object[] a) {
   466         if (LegacyMergeSort.userRequested)
   467             legacyMergeSort(a);
   468         else
   469             ComparableTimSort.sort(a);
   470     }
   471 
   472     /** To be removed in a future release. */
   473     private static void legacyMergeSort(Object[] a) {
   474         Object[] aux = a.clone();
   475         mergeSort(aux, a, 0, a.length, 0);
   476     }
   477 
   478     /**
   479      * Sorts the specified range of the specified array of objects into
   480      * ascending order, according to the
   481      * {@linkplain Comparable natural ordering} of its
   482      * elements.  The range to be sorted extends from index
   483      * {@code fromIndex}, inclusive, to index {@code toIndex}, exclusive.
   484      * (If {@code fromIndex==toIndex}, the range to be sorted is empty.)  All
   485      * elements in this range must implement the {@link Comparable}
   486      * interface.  Furthermore, all elements in this range must be <i>mutually
   487      * comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a
   488      * {@code ClassCastException} for any elements {@code e1} and
   489      * {@code e2} in the array).
   490      *
   491      * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
   492      * not be reordered as a result of the sort.
   493      *
   494      * <p>Implementation note: This implementation is a stable, adaptive,
   495      * iterative mergesort that requires far fewer than n lg(n) comparisons
   496      * when the input array is partially sorted, while offering the
   497      * performance of a traditional mergesort when the input array is
   498      * randomly ordered.  If the input array is nearly sorted, the
   499      * implementation requires approximately n comparisons.  Temporary
   500      * storage requirements vary from a small constant for nearly sorted
   501      * input arrays to n/2 object references for randomly ordered input
   502      * arrays.
   503      *
   504      * <p>The implementation takes equal advantage of ascending and
   505      * descending order in its input array, and can take advantage of
   506      * ascending and descending order in different parts of the the same
   507      * input array.  It is well-suited to merging two or more sorted arrays:
   508      * simply concatenate the arrays and sort the resulting array.
   509      *
   510      * <p>The implementation was adapted from Tim Peters's list sort for Python
   511      * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
   512      * TimSort</a>).  It uses techiques from Peter McIlroy's "Optimistic
   513      * Sorting and Information Theoretic Complexity", in Proceedings of the
   514      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
   515      * January 1993.
   516      *
   517      * @param a the array to be sorted
   518      * @param fromIndex the index of the first element (inclusive) to be
   519      *        sorted
   520      * @param toIndex the index of the last element (exclusive) to be sorted
   521      * @throws IllegalArgumentException if {@code fromIndex > toIndex} or
   522      *         (optional) if the natural ordering of the array elements is
   523      *         found to violate the {@link Comparable} contract
   524      * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
   525      *         {@code toIndex > a.length}
   526      * @throws ClassCastException if the array contains elements that are
   527      *         not <i>mutually comparable</i> (for example, strings and
   528      *         integers).
   529      */
   530     public static void sort(Object[] a, int fromIndex, int toIndex) {
   531         if (LegacyMergeSort.userRequested)
   532             legacyMergeSort(a, fromIndex, toIndex);
   533         else
   534             ComparableTimSort.sort(a, fromIndex, toIndex);
   535     }
   536 
   537     /** To be removed in a future release. */
   538     private static void legacyMergeSort(Object[] a,
   539                                         int fromIndex, int toIndex) {
   540         rangeCheck(a.length, fromIndex, toIndex);
   541         Object[] aux = copyOfRange(a, fromIndex, toIndex);
   542         mergeSort(aux, a, fromIndex, toIndex, -fromIndex);
   543     }
   544 
   545     /**
   546      * Tuning parameter: list size at or below which insertion sort will be
   547      * used in preference to mergesort.
   548      * To be removed in a future release.
   549      */
   550     private static final int INSERTIONSORT_THRESHOLD = 7;
   551 
   552     /**
   553      * Src is the source array that starts at index 0
   554      * Dest is the (possibly larger) array destination with a possible offset
   555      * low is the index in dest to start sorting
   556      * high is the end index in dest to end sorting
   557      * off is the offset to generate corresponding low, high in src
   558      * To be removed in a future release.
   559      */
   560     private static void mergeSort(Object[] src,
   561                                   Object[] dest,
   562                                   int low,
   563                                   int high,
   564                                   int off) {
   565         int length = high - low;
   566 
   567         // Insertion sort on smallest arrays
   568         if (length < INSERTIONSORT_THRESHOLD) {
   569             for (int i=low; i<high; i++)
   570                 for (int j=i; j>low &&
   571                          ((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)
   572                     swap(dest, j, j-1);
   573             return;
   574         }
   575 
   576         // Recursively sort halves of dest into src
   577         int destLow  = low;
   578         int destHigh = high;
   579         low  += off;
   580         high += off;
   581         int mid = (low + high) >>> 1;
   582         mergeSort(dest, src, low, mid, -off);
   583         mergeSort(dest, src, mid, high, -off);
   584 
   585         // If list is already sorted, just copy from src to dest.  This is an
   586         // optimization that results in faster sorts for nearly ordered lists.
   587         if (((Comparable)src[mid-1]).compareTo(src[mid]) <= 0) {
   588             System.arraycopy(src, low, dest, destLow, length);
   589             return;
   590         }
   591 
   592         // Merge sorted halves (now in src) into dest
   593         for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
   594             if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0)
   595                 dest[i] = src[p++];
   596             else
   597                 dest[i] = src[q++];
   598         }
   599     }
   600 
   601     /**
   602      * Swaps x[a] with x[b].
   603      */
   604     private static void swap(Object[] x, int a, int b) {
   605         Object t = x[a];
   606         x[a] = x[b];
   607         x[b] = t;
   608     }
   609 
   610     /**
   611      * Sorts the specified array of objects according to the order induced by
   612      * the specified comparator.  All elements in the array must be
   613      * <i>mutually comparable</i> by the specified comparator (that is,
   614      * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
   615      * for any elements {@code e1} and {@code e2} in the array).
   616      *
   617      * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
   618      * not be reordered as a result of the sort.
   619      *
   620      * <p>Implementation note: This implementation is a stable, adaptive,
   621      * iterative mergesort that requires far fewer than n lg(n) comparisons
   622      * when the input array is partially sorted, while offering the
   623      * performance of a traditional mergesort when the input array is
   624      * randomly ordered.  If the input array is nearly sorted, the
   625      * implementation requires approximately n comparisons.  Temporary
   626      * storage requirements vary from a small constant for nearly sorted
   627      * input arrays to n/2 object references for randomly ordered input
   628      * arrays.
   629      *
   630      * <p>The implementation takes equal advantage of ascending and
   631      * descending order in its input array, and can take advantage of
   632      * ascending and descending order in different parts of the the same
   633      * input array.  It is well-suited to merging two or more sorted arrays:
   634      * simply concatenate the arrays and sort the resulting array.
   635      *
   636      * <p>The implementation was adapted from Tim Peters's list sort for Python
   637      * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
   638      * TimSort</a>).  It uses techiques from Peter McIlroy's "Optimistic
   639      * Sorting and Information Theoretic Complexity", in Proceedings of the
   640      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
   641      * January 1993.
   642      *
   643      * @param a the array to be sorted
   644      * @param c the comparator to determine the order of the array.  A
   645      *        {@code null} value indicates that the elements'
   646      *        {@linkplain Comparable natural ordering} should be used.
   647      * @throws ClassCastException if the array contains elements that are
   648      *         not <i>mutually comparable</i> using the specified comparator
   649      * @throws IllegalArgumentException (optional) if the comparator is
   650      *         found to violate the {@link Comparator} contract
   651      */
   652     public static <T> void sort(T[] a, Comparator<? super T> c) {
   653         if (LegacyMergeSort.userRequested)
   654             legacyMergeSort(a, c);
   655         else
   656             TimSort.sort(a, c);
   657     }
   658 
   659     /** To be removed in a future release. */
   660     private static <T> void legacyMergeSort(T[] a, Comparator<? super T> c) {
   661         T[] aux = a.clone();
   662         if (c==null)
   663             mergeSort(aux, a, 0, a.length, 0);
   664         else
   665             mergeSort(aux, a, 0, a.length, 0, c);
   666     }
   667 
   668     /**
   669      * Sorts the specified range of the specified array of objects according
   670      * to the order induced by the specified comparator.  The range to be
   671      * sorted extends from index {@code fromIndex}, inclusive, to index
   672      * {@code toIndex}, exclusive.  (If {@code fromIndex==toIndex}, the
   673      * range to be sorted is empty.)  All elements in the range must be
   674      * <i>mutually comparable</i> by the specified comparator (that is,
   675      * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
   676      * for any elements {@code e1} and {@code e2} in the range).
   677      *
   678      * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
   679      * not be reordered as a result of the sort.
   680      *
   681      * <p>Implementation note: This implementation is a stable, adaptive,
   682      * iterative mergesort that requires far fewer than n lg(n) comparisons
   683      * when the input array is partially sorted, while offering the
   684      * performance of a traditional mergesort when the input array is
   685      * randomly ordered.  If the input array is nearly sorted, the
   686      * implementation requires approximately n comparisons.  Temporary
   687      * storage requirements vary from a small constant for nearly sorted
   688      * input arrays to n/2 object references for randomly ordered input
   689      * arrays.
   690      *
   691      * <p>The implementation takes equal advantage of ascending and
   692      * descending order in its input array, and can take advantage of
   693      * ascending and descending order in different parts of the the same
   694      * input array.  It is well-suited to merging two or more sorted arrays:
   695      * simply concatenate the arrays and sort the resulting array.
   696      *
   697      * <p>The implementation was adapted from Tim Peters's list sort for Python
   698      * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
   699      * TimSort</a>).  It uses techiques from Peter McIlroy's "Optimistic
   700      * Sorting and Information Theoretic Complexity", in Proceedings of the
   701      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
   702      * January 1993.
   703      *
   704      * @param a the array to be sorted
   705      * @param fromIndex the index of the first element (inclusive) to be
   706      *        sorted
   707      * @param toIndex the index of the last element (exclusive) to be sorted
   708      * @param c the comparator to determine the order of the array.  A
   709      *        {@code null} value indicates that the elements'
   710      *        {@linkplain Comparable natural ordering} should be used.
   711      * @throws ClassCastException if the array contains elements that are not
   712      *         <i>mutually comparable</i> using the specified comparator.
   713      * @throws IllegalArgumentException if {@code fromIndex > toIndex} or
   714      *         (optional) if the comparator is found to violate the
   715      *         {@link Comparator} contract
   716      * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
   717      *         {@code toIndex > a.length}
   718      */
   719     public static <T> void sort(T[] a, int fromIndex, int toIndex,
   720                                 Comparator<? super T> c) {
   721         if (LegacyMergeSort.userRequested)
   722             legacyMergeSort(a, fromIndex, toIndex, c);
   723         else
   724             TimSort.sort(a, fromIndex, toIndex, c);
   725     }
   726 
   727     /** To be removed in a future release. */
   728     private static <T> void legacyMergeSort(T[] a, int fromIndex, int toIndex,
   729                                             Comparator<? super T> c) {
   730         rangeCheck(a.length, fromIndex, toIndex);
   731         T[] aux = copyOfRange(a, fromIndex, toIndex);
   732         if (c==null)
   733             mergeSort(aux, a, fromIndex, toIndex, -fromIndex);
   734         else
   735             mergeSort(aux, a, fromIndex, toIndex, -fromIndex, c);
   736     }
   737 
   738     /**
   739      * Src is the source array that starts at index 0
   740      * Dest is the (possibly larger) array destination with a possible offset
   741      * low is the index in dest to start sorting
   742      * high is the end index in dest to end sorting
   743      * off is the offset into src corresponding to low in dest
   744      * To be removed in a future release.
   745      */
   746     private static void mergeSort(Object[] src,
   747                                   Object[] dest,
   748                                   int low, int high, int off,
   749                                   Comparator c) {
   750         int length = high - low;
   751 
   752         // Insertion sort on smallest arrays
   753         if (length < INSERTIONSORT_THRESHOLD) {
   754             for (int i=low; i<high; i++)
   755                 for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)
   756                     swap(dest, j, j-1);
   757             return;
   758         }
   759 
   760         // Recursively sort halves of dest into src
   761         int destLow  = low;
   762         int destHigh = high;
   763         low  += off;
   764         high += off;
   765         int mid = (low + high) >>> 1;
   766         mergeSort(dest, src, low, mid, -off, c);
   767         mergeSort(dest, src, mid, high, -off, c);
   768 
   769         // If list is already sorted, just copy from src to dest.  This is an
   770         // optimization that results in faster sorts for nearly ordered lists.
   771         if (c.compare(src[mid-1], src[mid]) <= 0) {
   772            System.arraycopy(src, low, dest, destLow, length);
   773            return;
   774         }
   775 
   776         // Merge sorted halves (now in src) into dest
   777         for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
   778             if (q >= high || p < mid && c.compare(src[p], src[q]) <= 0)
   779                 dest[i] = src[p++];
   780             else
   781                 dest[i] = src[q++];
   782         }
   783     }
   784 
   785     /**
   786      * Checks that {@code fromIndex} and {@code toIndex} are in
   787      * the range and throws an appropriate exception, if they aren't.
   788      */
   789     private static void rangeCheck(int length, int fromIndex, int toIndex) {
   790         if (fromIndex > toIndex) {
   791             throw new IllegalArgumentException(
   792                 "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
   793         }
   794         if (fromIndex < 0) {
   795             throw new ArrayIndexOutOfBoundsException(fromIndex);
   796         }
   797         if (toIndex > length) {
   798             throw new ArrayIndexOutOfBoundsException(toIndex);
   799         }
   800     }
   801 
   802     // Searching
   803 
   804     /**
   805      * Searches the specified array of longs for the specified value using the
   806      * binary search algorithm.  The array must be sorted (as
   807      * by the {@link #sort(long[])} method) prior to making this call.  If it
   808      * is not sorted, the results are undefined.  If the array contains
   809      * multiple elements with the specified value, there is no guarantee which
   810      * one will be found.
   811      *
   812      * @param a the array to be searched
   813      * @param key the value to be searched for
   814      * @return index of the search key, if it is contained in the array;
   815      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
   816      *         <i>insertion point</i> is defined as the point at which the
   817      *         key would be inserted into the array: the index of the first
   818      *         element greater than the key, or <tt>a.length</tt> if all
   819      *         elements in the array are less than the specified key.  Note
   820      *         that this guarantees that the return value will be &gt;= 0 if
   821      *         and only if the key is found.
   822      */
   823     public static int binarySearch(long[] a, long key) {
   824         return binarySearch0(a, 0, a.length, key);
   825     }
   826 
   827     /**
   828      * Searches a range of
   829      * the specified array of longs for the specified value using the
   830      * binary search algorithm.
   831      * The range must be sorted (as
   832      * by the {@link #sort(long[], int, int)} method)
   833      * prior to making this call.  If it
   834      * is not sorted, the results are undefined.  If the range contains
   835      * multiple elements with the specified value, there is no guarantee which
   836      * one will be found.
   837      *
   838      * @param a the array to be searched
   839      * @param fromIndex the index of the first element (inclusive) to be
   840      *          searched
   841      * @param toIndex the index of the last element (exclusive) to be searched
   842      * @param key the value to be searched for
   843      * @return index of the search key, if it is contained in the array
   844      *         within the specified range;
   845      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
   846      *         <i>insertion point</i> is defined as the point at which the
   847      *         key would be inserted into the array: the index of the first
   848      *         element in the range greater than the key,
   849      *         or <tt>toIndex</tt> if all
   850      *         elements in the range are less than the specified key.  Note
   851      *         that this guarantees that the return value will be &gt;= 0 if
   852      *         and only if the key is found.
   853      * @throws IllegalArgumentException
   854      *         if {@code fromIndex > toIndex}
   855      * @throws ArrayIndexOutOfBoundsException
   856      *         if {@code fromIndex < 0 or toIndex > a.length}
   857      * @since 1.6
   858      */
   859     public static int binarySearch(long[] a, int fromIndex, int toIndex,
   860                                    long key) {
   861         rangeCheck(a.length, fromIndex, toIndex);
   862         return binarySearch0(a, fromIndex, toIndex, key);
   863     }
   864 
   865     // Like public version, but without range checks.
   866     private static int binarySearch0(long[] a, int fromIndex, int toIndex,
   867                                      long key) {
   868         int low = fromIndex;
   869         int high = toIndex - 1;
   870 
   871         while (low <= high) {
   872             int mid = (low + high) >>> 1;
   873             long midVal = a[mid];
   874 
   875             if (midVal < key)
   876                 low = mid + 1;
   877             else if (midVal > key)
   878                 high = mid - 1;
   879             else
   880                 return mid; // key found
   881         }
   882         return -(low + 1);  // key not found.
   883     }
   884 
   885     /**
   886      * Searches the specified array of ints for the specified value using the
   887      * binary search algorithm.  The array must be sorted (as
   888      * by the {@link #sort(int[])} method) prior to making this call.  If it
   889      * is not sorted, the results are undefined.  If the array contains
   890      * multiple elements with the specified value, there is no guarantee which
   891      * one will be found.
   892      *
   893      * @param a the array to be searched
   894      * @param key the value to be searched for
   895      * @return index of the search key, if it is contained in the array;
   896      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
   897      *         <i>insertion point</i> is defined as the point at which the
   898      *         key would be inserted into the array: the index of the first
   899      *         element greater than the key, or <tt>a.length</tt> if all
   900      *         elements in the array are less than the specified key.  Note
   901      *         that this guarantees that the return value will be &gt;= 0 if
   902      *         and only if the key is found.
   903      */
   904     public static int binarySearch(int[] a, int key) {
   905         return binarySearch0(a, 0, a.length, key);
   906     }
   907 
   908     /**
   909      * Searches a range of
   910      * the specified array of ints for the specified value using the
   911      * binary search algorithm.
   912      * The range must be sorted (as
   913      * by the {@link #sort(int[], int, int)} method)
   914      * prior to making this call.  If it
   915      * is not sorted, the results are undefined.  If the range contains
   916      * multiple elements with the specified value, there is no guarantee which
   917      * one will be found.
   918      *
   919      * @param a the array to be searched
   920      * @param fromIndex the index of the first element (inclusive) to be
   921      *          searched
   922      * @param toIndex the index of the last element (exclusive) to be searched
   923      * @param key the value to be searched for
   924      * @return index of the search key, if it is contained in the array
   925      *         within the specified range;
   926      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
   927      *         <i>insertion point</i> is defined as the point at which the
   928      *         key would be inserted into the array: the index of the first
   929      *         element in the range greater than the key,
   930      *         or <tt>toIndex</tt> if all
   931      *         elements in the range are less than the specified key.  Note
   932      *         that this guarantees that the return value will be &gt;= 0 if
   933      *         and only if the key is found.
   934      * @throws IllegalArgumentException
   935      *         if {@code fromIndex > toIndex}
   936      * @throws ArrayIndexOutOfBoundsException
   937      *         if {@code fromIndex < 0 or toIndex > a.length}
   938      * @since 1.6
   939      */
   940     public static int binarySearch(int[] a, int fromIndex, int toIndex,
   941                                    int key) {
   942         rangeCheck(a.length, fromIndex, toIndex);
   943         return binarySearch0(a, fromIndex, toIndex, key);
   944     }
   945 
   946     // Like public version, but without range checks.
   947     private static int binarySearch0(int[] a, int fromIndex, int toIndex,
   948                                      int key) {
   949         int low = fromIndex;
   950         int high = toIndex - 1;
   951 
   952         while (low <= high) {
   953             int mid = (low + high) >>> 1;
   954             int midVal = a[mid];
   955 
   956             if (midVal < key)
   957                 low = mid + 1;
   958             else if (midVal > key)
   959                 high = mid - 1;
   960             else
   961                 return mid; // key found
   962         }
   963         return -(low + 1);  // key not found.
   964     }
   965 
   966     /**
   967      * Searches the specified array of shorts for the specified value using
   968      * the binary search algorithm.  The array must be sorted
   969      * (as by the {@link #sort(short[])} method) prior to making this call.  If
   970      * it is not sorted, the results are undefined.  If the array contains
   971      * multiple elements with the specified value, there is no guarantee which
   972      * one will be found.
   973      *
   974      * @param a the array to be searched
   975      * @param key the value to be searched for
   976      * @return index of the search key, if it is contained in the array;
   977      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
   978      *         <i>insertion point</i> is defined as the point at which the
   979      *         key would be inserted into the array: the index of the first
   980      *         element greater than the key, or <tt>a.length</tt> if all
   981      *         elements in the array are less than the specified key.  Note
   982      *         that this guarantees that the return value will be &gt;= 0 if
   983      *         and only if the key is found.
   984      */
   985     public static int binarySearch(short[] a, short key) {
   986         return binarySearch0(a, 0, a.length, key);
   987     }
   988 
   989     /**
   990      * Searches a range of
   991      * the specified array of shorts for the specified value using
   992      * the binary search algorithm.
   993      * The range must be sorted
   994      * (as by the {@link #sort(short[], int, int)} method)
   995      * prior to making this call.  If
   996      * it is not sorted, the results are undefined.  If the range contains
   997      * multiple elements with the specified value, there is no guarantee which
   998      * one will be found.
   999      *
  1000      * @param a the array to be searched
  1001      * @param fromIndex the index of the first element (inclusive) to be
  1002      *          searched
  1003      * @param toIndex the index of the last element (exclusive) to be searched
  1004      * @param key the value to be searched for
  1005      * @return index of the search key, if it is contained in the array
  1006      *         within the specified range;
  1007      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
  1008      *         <i>insertion point</i> is defined as the point at which the
  1009      *         key would be inserted into the array: the index of the first
  1010      *         element in the range greater than the key,
  1011      *         or <tt>toIndex</tt> if all
  1012      *         elements in the range are less than the specified key.  Note
  1013      *         that this guarantees that the return value will be &gt;= 0 if
  1014      *         and only if the key is found.
  1015      * @throws IllegalArgumentException
  1016      *         if {@code fromIndex > toIndex}
  1017      * @throws ArrayIndexOutOfBoundsException
  1018      *         if {@code fromIndex < 0 or toIndex > a.length}
  1019      * @since 1.6
  1020      */
  1021     public static int binarySearch(short[] a, int fromIndex, int toIndex,
  1022                                    short key) {
  1023         rangeCheck(a.length, fromIndex, toIndex);
  1024         return binarySearch0(a, fromIndex, toIndex, key);
  1025     }
  1026 
  1027     // Like public version, but without range checks.
  1028     private static int binarySearch0(short[] a, int fromIndex, int toIndex,
  1029                                      short key) {
  1030         int low = fromIndex;
  1031         int high = toIndex - 1;
  1032 
  1033         while (low <= high) {
  1034             int mid = (low + high) >>> 1;
  1035             short midVal = a[mid];
  1036 
  1037             if (midVal < key)
  1038                 low = mid + 1;
  1039             else if (midVal > key)
  1040                 high = mid - 1;
  1041             else
  1042                 return mid; // key found
  1043         }
  1044         return -(low + 1);  // key not found.
  1045     }
  1046 
  1047     /**
  1048      * Searches the specified array of chars for the specified value using the
  1049      * binary search algorithm.  The array must be sorted (as
  1050      * by the {@link #sort(char[])} method) prior to making this call.  If it
  1051      * is not sorted, the results are undefined.  If the array contains
  1052      * multiple elements with the specified value, there is no guarantee which
  1053      * one will be found.
  1054      *
  1055      * @param a the array to be searched
  1056      * @param key the value to be searched for
  1057      * @return index of the search key, if it is contained in the array;
  1058      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
  1059      *         <i>insertion point</i> is defined as the point at which the
  1060      *         key would be inserted into the array: the index of the first
  1061      *         element greater than the key, or <tt>a.length</tt> if all
  1062      *         elements in the array are less than the specified key.  Note
  1063      *         that this guarantees that the return value will be &gt;= 0 if
  1064      *         and only if the key is found.
  1065      */
  1066     public static int binarySearch(char[] a, char key) {
  1067         return binarySearch0(a, 0, a.length, key);
  1068     }
  1069 
  1070     /**
  1071      * Searches a range of
  1072      * the specified array of chars for the specified value using the
  1073      * binary search algorithm.
  1074      * The range must be sorted (as
  1075      * by the {@link #sort(char[], int, int)} method)
  1076      * prior to making this call.  If it
  1077      * is not sorted, the results are undefined.  If the range contains
  1078      * multiple elements with the specified value, there is no guarantee which
  1079      * one will be found.
  1080      *
  1081      * @param a the array to be searched
  1082      * @param fromIndex the index of the first element (inclusive) to be
  1083      *          searched
  1084      * @param toIndex the index of the last element (exclusive) to be searched
  1085      * @param key the value to be searched for
  1086      * @return index of the search key, if it is contained in the array
  1087      *         within the specified range;
  1088      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
  1089      *         <i>insertion point</i> is defined as the point at which the
  1090      *         key would be inserted into the array: the index of the first
  1091      *         element in the range greater than the key,
  1092      *         or <tt>toIndex</tt> if all
  1093      *         elements in the range are less than the specified key.  Note
  1094      *         that this guarantees that the return value will be &gt;= 0 if
  1095      *         and only if the key is found.
  1096      * @throws IllegalArgumentException
  1097      *         if {@code fromIndex > toIndex}
  1098      * @throws ArrayIndexOutOfBoundsException
  1099      *         if {@code fromIndex < 0 or toIndex > a.length}
  1100      * @since 1.6
  1101      */
  1102     public static int binarySearch(char[] a, int fromIndex, int toIndex,
  1103                                    char key) {
  1104         rangeCheck(a.length, fromIndex, toIndex);
  1105         return binarySearch0(a, fromIndex, toIndex, key);
  1106     }
  1107 
  1108     // Like public version, but without range checks.
  1109     private static int binarySearch0(char[] a, int fromIndex, int toIndex,
  1110                                      char key) {
  1111         int low = fromIndex;
  1112         int high = toIndex - 1;
  1113 
  1114         while (low <= high) {
  1115             int mid = (low + high) >>> 1;
  1116             char midVal = a[mid];
  1117 
  1118             if (midVal < key)
  1119                 low = mid + 1;
  1120             else if (midVal > key)
  1121                 high = mid - 1;
  1122             else
  1123                 return mid; // key found
  1124         }
  1125         return -(low + 1);  // key not found.
  1126     }
  1127 
  1128     /**
  1129      * Searches the specified array of bytes for the specified value using the
  1130      * binary search algorithm.  The array must be sorted (as
  1131      * by the {@link #sort(byte[])} method) prior to making this call.  If it
  1132      * is not sorted, the results are undefined.  If the array contains
  1133      * multiple elements with the specified value, there is no guarantee which
  1134      * one will be found.
  1135      *
  1136      * @param a the array to be searched
  1137      * @param key the value to be searched for
  1138      * @return index of the search key, if it is contained in the array;
  1139      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
  1140      *         <i>insertion point</i> is defined as the point at which the
  1141      *         key would be inserted into the array: the index of the first
  1142      *         element greater than the key, or <tt>a.length</tt> if all
  1143      *         elements in the array are less than the specified key.  Note
  1144      *         that this guarantees that the return value will be &gt;= 0 if
  1145      *         and only if the key is found.
  1146      */
  1147     public static int binarySearch(byte[] a, byte key) {
  1148         return binarySearch0(a, 0, a.length, key);
  1149     }
  1150 
  1151     /**
  1152      * Searches a range of
  1153      * the specified array of bytes for the specified value using the
  1154      * binary search algorithm.
  1155      * The range must be sorted (as
  1156      * by the {@link #sort(byte[], int, int)} method)
  1157      * prior to making this call.  If it
  1158      * is not sorted, the results are undefined.  If the range contains
  1159      * multiple elements with the specified value, there is no guarantee which
  1160      * one will be found.
  1161      *
  1162      * @param a the array to be searched
  1163      * @param fromIndex the index of the first element (inclusive) to be
  1164      *          searched
  1165      * @param toIndex the index of the last element (exclusive) to be searched
  1166      * @param key the value to be searched for
  1167      * @return index of the search key, if it is contained in the array
  1168      *         within the specified range;
  1169      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
  1170      *         <i>insertion point</i> is defined as the point at which the
  1171      *         key would be inserted into the array: the index of the first
  1172      *         element in the range greater than the key,
  1173      *         or <tt>toIndex</tt> if all
  1174      *         elements in the range are less than the specified key.  Note
  1175      *         that this guarantees that the return value will be &gt;= 0 if
  1176      *         and only if the key is found.
  1177      * @throws IllegalArgumentException
  1178      *         if {@code fromIndex > toIndex}
  1179      * @throws ArrayIndexOutOfBoundsException
  1180      *         if {@code fromIndex < 0 or toIndex > a.length}
  1181      * @since 1.6
  1182      */
  1183     public static int binarySearch(byte[] a, int fromIndex, int toIndex,
  1184                                    byte key) {
  1185         rangeCheck(a.length, fromIndex, toIndex);
  1186         return binarySearch0(a, fromIndex, toIndex, key);
  1187     }
  1188 
  1189     // Like public version, but without range checks.
  1190     private static int binarySearch0(byte[] a, int fromIndex, int toIndex,
  1191                                      byte key) {
  1192         int low = fromIndex;
  1193         int high = toIndex - 1;
  1194 
  1195         while (low <= high) {
  1196             int mid = (low + high) >>> 1;
  1197             byte midVal = a[mid];
  1198 
  1199             if (midVal < key)
  1200                 low = mid + 1;
  1201             else if (midVal > key)
  1202                 high = mid - 1;
  1203             else
  1204                 return mid; // key found
  1205         }
  1206         return -(low + 1);  // key not found.
  1207     }
  1208 
  1209     /**
  1210      * Searches the specified array of doubles for the specified value using
  1211      * the binary search algorithm.  The array must be sorted
  1212      * (as by the {@link #sort(double[])} method) prior to making this call.
  1213      * If it is not sorted, the results are undefined.  If the array contains
  1214      * multiple elements with the specified value, there is no guarantee which
  1215      * one will be found.  This method considers all NaN values to be
  1216      * equivalent and equal.
  1217      *
  1218      * @param a the array to be searched
  1219      * @param key the value to be searched for
  1220      * @return index of the search key, if it is contained in the array;
  1221      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
  1222      *         <i>insertion point</i> is defined as the point at which the
  1223      *         key would be inserted into the array: the index of the first
  1224      *         element greater than the key, or <tt>a.length</tt> if all
  1225      *         elements in the array are less than the specified key.  Note
  1226      *         that this guarantees that the return value will be &gt;= 0 if
  1227      *         and only if the key is found.
  1228      */
  1229     public static int binarySearch(double[] a, double key) {
  1230         return binarySearch0(a, 0, a.length, key);
  1231     }
  1232 
  1233     /**
  1234      * Searches a range of
  1235      * the specified array of doubles for the specified value using
  1236      * the binary search algorithm.
  1237      * The range must be sorted
  1238      * (as by the {@link #sort(double[], int, int)} method)
  1239      * prior to making this call.
  1240      * If it is not sorted, the results are undefined.  If the range contains
  1241      * multiple elements with the specified value, there is no guarantee which
  1242      * one will be found.  This method considers all NaN values to be
  1243      * equivalent and equal.
  1244      *
  1245      * @param a the array to be searched
  1246      * @param fromIndex the index of the first element (inclusive) to be
  1247      *          searched
  1248      * @param toIndex the index of the last element (exclusive) to be searched
  1249      * @param key the value to be searched for
  1250      * @return index of the search key, if it is contained in the array
  1251      *         within the specified range;
  1252      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
  1253      *         <i>insertion point</i> is defined as the point at which the
  1254      *         key would be inserted into the array: the index of the first
  1255      *         element in the range greater than the key,
  1256      *         or <tt>toIndex</tt> if all
  1257      *         elements in the range are less than the specified key.  Note
  1258      *         that this guarantees that the return value will be &gt;= 0 if
  1259      *         and only if the key is found.
  1260      * @throws IllegalArgumentException
  1261      *         if {@code fromIndex > toIndex}
  1262      * @throws ArrayIndexOutOfBoundsException
  1263      *         if {@code fromIndex < 0 or toIndex > a.length}
  1264      * @since 1.6
  1265      */
  1266     public static int binarySearch(double[] a, int fromIndex, int toIndex,
  1267                                    double key) {
  1268         rangeCheck(a.length, fromIndex, toIndex);
  1269         return binarySearch0(a, fromIndex, toIndex, key);
  1270     }
  1271 
  1272     // Like public version, but without range checks.
  1273     private static int binarySearch0(double[] a, int fromIndex, int toIndex,
  1274                                      double key) {
  1275         int low = fromIndex;
  1276         int high = toIndex - 1;
  1277 
  1278         while (low <= high) {
  1279             int mid = (low + high) >>> 1;
  1280             double midVal = a[mid];
  1281 
  1282             if (midVal < key)
  1283                 low = mid + 1;  // Neither val is NaN, thisVal is smaller
  1284             else if (midVal > key)
  1285                 high = mid - 1; // Neither val is NaN, thisVal is larger
  1286             else {
  1287                 long midBits = Double.doubleToLongBits(midVal);
  1288                 long keyBits = Double.doubleToLongBits(key);
  1289                 if (midBits == keyBits)     // Values are equal
  1290                     return mid;             // Key found
  1291                 else if (midBits < keyBits) // (-0.0, 0.0) or (!NaN, NaN)
  1292                     low = mid + 1;
  1293                 else                        // (0.0, -0.0) or (NaN, !NaN)
  1294                     high = mid - 1;
  1295             }
  1296         }
  1297         return -(low + 1);  // key not found.
  1298     }
  1299 
  1300     /**
  1301      * Searches the specified array of floats for the specified value using
  1302      * the binary search algorithm. The array must be sorted
  1303      * (as by the {@link #sort(float[])} method) prior to making this call. If
  1304      * it is not sorted, the results are undefined. If the array contains
  1305      * multiple elements with the specified value, there is no guarantee which
  1306      * one will be found. This method considers all NaN values to be
  1307      * equivalent and equal.
  1308      *
  1309      * @param a the array to be searched
  1310      * @param key the value to be searched for
  1311      * @return index of the search key, if it is contained in the array;
  1312      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
  1313      *         <i>insertion point</i> is defined as the point at which the
  1314      *         key would be inserted into the array: the index of the first
  1315      *         element greater than the key, or <tt>a.length</tt> if all
  1316      *         elements in the array are less than the specified key. Note
  1317      *         that this guarantees that the return value will be &gt;= 0 if
  1318      *         and only if the key is found.
  1319      */
  1320     public static int binarySearch(float[] a, float key) {
  1321         return binarySearch0(a, 0, a.length, key);
  1322     }
  1323 
  1324     /**
  1325      * Searches a range of
  1326      * the specified array of floats for the specified value using
  1327      * the binary search algorithm.
  1328      * The range must be sorted
  1329      * (as by the {@link #sort(float[], int, int)} method)
  1330      * prior to making this call. If
  1331      * it is not sorted, the results are undefined. If the range contains
  1332      * multiple elements with the specified value, there is no guarantee which
  1333      * one will be found. This method considers all NaN values to be
  1334      * equivalent and equal.
  1335      *
  1336      * @param a the array to be searched
  1337      * @param fromIndex the index of the first element (inclusive) to be
  1338      *          searched
  1339      * @param toIndex the index of the last element (exclusive) to be searched
  1340      * @param key the value to be searched for
  1341      * @return index of the search key, if it is contained in the array
  1342      *         within the specified range;
  1343      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
  1344      *         <i>insertion point</i> is defined as the point at which the
  1345      *         key would be inserted into the array: the index of the first
  1346      *         element in the range greater than the key,
  1347      *         or <tt>toIndex</tt> if all
  1348      *         elements in the range are less than the specified key. Note
  1349      *         that this guarantees that the return value will be &gt;= 0 if
  1350      *         and only if the key is found.
  1351      * @throws IllegalArgumentException
  1352      *         if {@code fromIndex > toIndex}
  1353      * @throws ArrayIndexOutOfBoundsException
  1354      *         if {@code fromIndex < 0 or toIndex > a.length}
  1355      * @since 1.6
  1356      */
  1357     public static int binarySearch(float[] a, int fromIndex, int toIndex,
  1358                                    float key) {
  1359         rangeCheck(a.length, fromIndex, toIndex);
  1360         return binarySearch0(a, fromIndex, toIndex, key);
  1361     }
  1362 
  1363     // Like public version, but without range checks.
  1364     private static int binarySearch0(float[] a, int fromIndex, int toIndex,
  1365                                      float key) {
  1366         int low = fromIndex;
  1367         int high = toIndex - 1;
  1368 
  1369         while (low <= high) {
  1370             int mid = (low + high) >>> 1;
  1371             float midVal = a[mid];
  1372 
  1373             if (midVal < key)
  1374                 low = mid + 1;  // Neither val is NaN, thisVal is smaller
  1375             else if (midVal > key)
  1376                 high = mid - 1; // Neither val is NaN, thisVal is larger
  1377             else {
  1378                 int midBits = Float.floatToIntBits(midVal);
  1379                 int keyBits = Float.floatToIntBits(key);
  1380                 if (midBits == keyBits)     // Values are equal
  1381                     return mid;             // Key found
  1382                 else if (midBits < keyBits) // (-0.0, 0.0) or (!NaN, NaN)
  1383                     low = mid + 1;
  1384                 else                        // (0.0, -0.0) or (NaN, !NaN)
  1385                     high = mid - 1;
  1386             }
  1387         }
  1388         return -(low + 1);  // key not found.
  1389     }
  1390 
  1391     /**
  1392      * Searches the specified array for the specified object using the binary
  1393      * search algorithm. The array must be sorted into ascending order
  1394      * according to the
  1395      * {@linkplain Comparable natural ordering}
  1396      * of its elements (as by the
  1397      * {@link #sort(Object[])} method) prior to making this call.
  1398      * If it is not sorted, the results are undefined.
  1399      * (If the array contains elements that are not mutually comparable (for
  1400      * example, strings and integers), it <i>cannot</i> be sorted according
  1401      * to the natural ordering of its elements, hence results are undefined.)
  1402      * If the array contains multiple
  1403      * elements equal to the specified object, there is no guarantee which
  1404      * one will be found.
  1405      *
  1406      * @param a the array to be searched
  1407      * @param key the value to be searched for
  1408      * @return index of the search key, if it is contained in the array;
  1409      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
  1410      *         <i>insertion point</i> is defined as the point at which the
  1411      *         key would be inserted into the array: the index of the first
  1412      *         element greater than the key, or <tt>a.length</tt> if all
  1413      *         elements in the array are less than the specified key.  Note
  1414      *         that this guarantees that the return value will be &gt;= 0 if
  1415      *         and only if the key is found.
  1416      * @throws ClassCastException if the search key is not comparable to the
  1417      *         elements of the array.
  1418      */
  1419     public static int binarySearch(Object[] a, Object key) {
  1420         return binarySearch0(a, 0, a.length, key);
  1421     }
  1422 
  1423     /**
  1424      * Searches a range of
  1425      * the specified array for the specified object using the binary
  1426      * search algorithm.
  1427      * The range must be sorted into ascending order
  1428      * according to the
  1429      * {@linkplain Comparable natural ordering}
  1430      * of its elements (as by the
  1431      * {@link #sort(Object[], int, int)} method) prior to making this
  1432      * call.  If it is not sorted, the results are undefined.
  1433      * (If the range contains elements that are not mutually comparable (for
  1434      * example, strings and integers), it <i>cannot</i> be sorted according
  1435      * to the natural ordering of its elements, hence results are undefined.)
  1436      * If the range contains multiple
  1437      * elements equal to the specified object, there is no guarantee which
  1438      * one will be found.
  1439      *
  1440      * @param a the array to be searched
  1441      * @param fromIndex the index of the first element (inclusive) to be
  1442      *          searched
  1443      * @param toIndex the index of the last element (exclusive) to be searched
  1444      * @param key the value to be searched for
  1445      * @return index of the search key, if it is contained in the array
  1446      *         within the specified range;
  1447      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
  1448      *         <i>insertion point</i> is defined as the point at which the
  1449      *         key would be inserted into the array: the index of the first
  1450      *         element in the range greater than the key,
  1451      *         or <tt>toIndex</tt> if all
  1452      *         elements in the range are less than the specified key.  Note
  1453      *         that this guarantees that the return value will be &gt;= 0 if
  1454      *         and only if the key is found.
  1455      * @throws ClassCastException if the search key is not comparable to the
  1456      *         elements of the array within the specified range.
  1457      * @throws IllegalArgumentException
  1458      *         if {@code fromIndex > toIndex}
  1459      * @throws ArrayIndexOutOfBoundsException
  1460      *         if {@code fromIndex < 0 or toIndex > a.length}
  1461      * @since 1.6
  1462      */
  1463     public static int binarySearch(Object[] a, int fromIndex, int toIndex,
  1464                                    Object key) {
  1465         rangeCheck(a.length, fromIndex, toIndex);
  1466         return binarySearch0(a, fromIndex, toIndex, key);
  1467     }
  1468 
  1469     // Like public version, but without range checks.
  1470     private static int binarySearch0(Object[] a, int fromIndex, int toIndex,
  1471                                      Object key) {
  1472         int low = fromIndex;
  1473         int high = toIndex - 1;
  1474 
  1475         while (low <= high) {
  1476             int mid = (low + high) >>> 1;
  1477             Comparable midVal = (Comparable)a[mid];
  1478             int cmp = midVal.compareTo(key);
  1479 
  1480             if (cmp < 0)
  1481                 low = mid + 1;
  1482             else if (cmp > 0)
  1483                 high = mid - 1;
  1484             else
  1485                 return mid; // key found
  1486         }
  1487         return -(low + 1);  // key not found.
  1488     }
  1489 
  1490     /**
  1491      * Searches the specified array for the specified object using the binary
  1492      * search algorithm.  The array must be sorted into ascending order
  1493      * according to the specified comparator (as by the
  1494      * {@link #sort(Object[], Comparator) sort(T[], Comparator)}
  1495      * method) prior to making this call.  If it is
  1496      * not sorted, the results are undefined.
  1497      * If the array contains multiple
  1498      * elements equal to the specified object, there is no guarantee which one
  1499      * will be found.
  1500      *
  1501      * @param a the array to be searched
  1502      * @param key the value to be searched for
  1503      * @param c the comparator by which the array is ordered.  A
  1504      *        <tt>null</tt> value indicates that the elements'
  1505      *        {@linkplain Comparable natural ordering} should be used.
  1506      * @return index of the search key, if it is contained in the array;
  1507      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
  1508      *         <i>insertion point</i> is defined as the point at which the
  1509      *         key would be inserted into the array: the index of the first
  1510      *         element greater than the key, or <tt>a.length</tt> if all
  1511      *         elements in the array are less than the specified key.  Note
  1512      *         that this guarantees that the return value will be &gt;= 0 if
  1513      *         and only if the key is found.
  1514      * @throws ClassCastException if the array contains elements that are not
  1515      *         <i>mutually comparable</i> using the specified comparator,
  1516      *         or the search key is not comparable to the
  1517      *         elements of the array using this comparator.
  1518      */
  1519     public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c) {
  1520         return binarySearch0(a, 0, a.length, key, c);
  1521     }
  1522 
  1523     /**
  1524      * Searches a range of
  1525      * the specified array for the specified object using the binary
  1526      * search algorithm.
  1527      * The range must be sorted into ascending order
  1528      * according to the specified comparator (as by the
  1529      * {@link #sort(Object[], int, int, Comparator)
  1530      * sort(T[], int, int, Comparator)}
  1531      * method) prior to making this call.
  1532      * If it is not sorted, the results are undefined.
  1533      * If the range contains multiple elements equal to the specified object,
  1534      * there is no guarantee which one will be found.
  1535      *
  1536      * @param a the array to be searched
  1537      * @param fromIndex the index of the first element (inclusive) to be
  1538      *          searched
  1539      * @param toIndex the index of the last element (exclusive) to be searched
  1540      * @param key the value to be searched for
  1541      * @param c the comparator by which the array is ordered.  A
  1542      *        <tt>null</tt> value indicates that the elements'
  1543      *        {@linkplain Comparable natural ordering} should be used.
  1544      * @return index of the search key, if it is contained in the array
  1545      *         within the specified range;
  1546      *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
  1547      *         <i>insertion point</i> is defined as the point at which the
  1548      *         key would be inserted into the array: the index of the first
  1549      *         element in the range greater than the key,
  1550      *         or <tt>toIndex</tt> if all
  1551      *         elements in the range are less than the specified key.  Note
  1552      *         that this guarantees that the return value will be &gt;= 0 if
  1553      *         and only if the key is found.
  1554      * @throws ClassCastException if the range contains elements that are not
  1555      *         <i>mutually comparable</i> using the specified comparator,
  1556      *         or the search key is not comparable to the
  1557      *         elements in the range using this comparator.
  1558      * @throws IllegalArgumentException
  1559      *         if {@code fromIndex > toIndex}
  1560      * @throws ArrayIndexOutOfBoundsException
  1561      *         if {@code fromIndex < 0 or toIndex > a.length}
  1562      * @since 1.6
  1563      */
  1564     public static <T> int binarySearch(T[] a, int fromIndex, int toIndex,
  1565                                        T key, Comparator<? super T> c) {
  1566         rangeCheck(a.length, fromIndex, toIndex);
  1567         return binarySearch0(a, fromIndex, toIndex, key, c);
  1568     }
  1569 
  1570     // Like public version, but without range checks.
  1571     private static <T> int binarySearch0(T[] a, int fromIndex, int toIndex,
  1572                                          T key, Comparator<? super T> c) {
  1573         if (c == null) {
  1574             return binarySearch0(a, fromIndex, toIndex, key);
  1575         }
  1576         int low = fromIndex;
  1577         int high = toIndex - 1;
  1578 
  1579         while (low <= high) {
  1580             int mid = (low + high) >>> 1;
  1581             T midVal = a[mid];
  1582             int cmp = c.compare(midVal, key);
  1583             if (cmp < 0)
  1584                 low = mid + 1;
  1585             else if (cmp > 0)
  1586                 high = mid - 1;
  1587             else
  1588                 return mid; // key found
  1589         }
  1590         return -(low + 1);  // key not found.
  1591     }
  1592 
  1593     // Equality Testing
  1594 
  1595     /**
  1596      * Returns <tt>true</tt> if the two specified arrays of longs are
  1597      * <i>equal</i> to one another.  Two arrays are considered equal if both
  1598      * arrays contain the same number of elements, and all corresponding pairs
  1599      * of elements in the two arrays are equal.  In other words, two arrays
  1600      * are equal if they contain the same elements in the same order.  Also,
  1601      * two array references are considered equal if both are <tt>null</tt>.<p>
  1602      *
  1603      * @param a one array to be tested for equality
  1604      * @param a2 the other array to be tested for equality
  1605      * @return <tt>true</tt> if the two arrays are equal
  1606      */
  1607     public static boolean equals(long[] a, long[] a2) {
  1608         if (a==a2)
  1609             return true;
  1610         if (a==null || a2==null)
  1611             return false;
  1612 
  1613         int length = a.length;
  1614         if (a2.length != length)
  1615             return false;
  1616 
  1617         for (int i=0; i<length; i++)
  1618             if (a[i] != a2[i])
  1619                 return false;
  1620 
  1621         return true;
  1622     }
  1623 
  1624     /**
  1625      * Returns <tt>true</tt> if the two specified arrays of ints are
  1626      * <i>equal</i> to one another.  Two arrays are considered equal if both
  1627      * arrays contain the same number of elements, and all corresponding pairs
  1628      * of elements in the two arrays are equal.  In other words, two arrays
  1629      * are equal if they contain the same elements in the same order.  Also,
  1630      * two array references are considered equal if both are <tt>null</tt>.<p>
  1631      *
  1632      * @param a one array to be tested for equality
  1633      * @param a2 the other array to be tested for equality
  1634      * @return <tt>true</tt> if the two arrays are equal
  1635      */
  1636     public static boolean equals(int[] a, int[] a2) {
  1637         if (a==a2)
  1638             return true;
  1639         if (a==null || a2==null)
  1640             return false;
  1641 
  1642         int length = a.length;
  1643         if (a2.length != length)
  1644             return false;
  1645 
  1646         for (int i=0; i<length; i++)
  1647             if (a[i] != a2[i])
  1648                 return false;
  1649 
  1650         return true;
  1651     }
  1652 
  1653     /**
  1654      * Returns <tt>true</tt> if the two specified arrays of shorts are
  1655      * <i>equal</i> to one another.  Two arrays are considered equal if both
  1656      * arrays contain the same number of elements, and all corresponding pairs
  1657      * of elements in the two arrays are equal.  In other words, two arrays
  1658      * are equal if they contain the same elements in the same order.  Also,
  1659      * two array references are considered equal if both are <tt>null</tt>.<p>
  1660      *
  1661      * @param a one array to be tested for equality
  1662      * @param a2 the other array to be tested for equality
  1663      * @return <tt>true</tt> if the two arrays are equal
  1664      */
  1665     public static boolean equals(short[] a, short a2[]) {
  1666         if (a==a2)
  1667             return true;
  1668         if (a==null || a2==null)
  1669             return false;
  1670 
  1671         int length = a.length;
  1672         if (a2.length != length)
  1673             return false;
  1674 
  1675         for (int i=0; i<length; i++)
  1676             if (a[i] != a2[i])
  1677                 return false;
  1678 
  1679         return true;
  1680     }
  1681 
  1682     /**
  1683      * Returns <tt>true</tt> if the two specified arrays of chars are
  1684      * <i>equal</i> to one another.  Two arrays are considered equal if both
  1685      * arrays contain the same number of elements, and all corresponding pairs
  1686      * of elements in the two arrays are equal.  In other words, two arrays
  1687      * are equal if they contain the same elements in the same order.  Also,
  1688      * two array references are considered equal if both are <tt>null</tt>.<p>
  1689      *
  1690      * @param a one array to be tested for equality
  1691      * @param a2 the other array to be tested for equality
  1692      * @return <tt>true</tt> if the two arrays are equal
  1693      */
  1694     public static boolean equals(char[] a, char[] a2) {
  1695         if (a==a2)
  1696             return true;
  1697         if (a==null || a2==null)
  1698             return false;
  1699 
  1700         int length = a.length;
  1701         if (a2.length != length)
  1702             return false;
  1703 
  1704         for (int i=0; i<length; i++)
  1705             if (a[i] != a2[i])
  1706                 return false;
  1707 
  1708         return true;
  1709     }
  1710 
  1711     /**
  1712      * Returns <tt>true</tt> if the two specified arrays of bytes are
  1713      * <i>equal</i> to one another.  Two arrays are considered equal if both
  1714      * arrays contain the same number of elements, and all corresponding pairs
  1715      * of elements in the two arrays are equal.  In other words, two arrays
  1716      * are equal if they contain the same elements in the same order.  Also,
  1717      * two array references are considered equal if both are <tt>null</tt>.<p>
  1718      *
  1719      * @param a one array to be tested for equality
  1720      * @param a2 the other array to be tested for equality
  1721      * @return <tt>true</tt> if the two arrays are equal
  1722      */
  1723     public static boolean equals(byte[] a, byte[] a2) {
  1724         if (a==a2)
  1725             return true;
  1726         if (a==null || a2==null)
  1727             return false;
  1728 
  1729         int length = a.length;
  1730         if (a2.length != length)
  1731             return false;
  1732 
  1733         for (int i=0; i<length; i++)
  1734             if (a[i] != a2[i])
  1735                 return false;
  1736 
  1737         return true;
  1738     }
  1739 
  1740     /**
  1741      * Returns <tt>true</tt> if the two specified arrays of booleans are
  1742      * <i>equal</i> to one another.  Two arrays are considered equal if both
  1743      * arrays contain the same number of elements, and all corresponding pairs
  1744      * of elements in the two arrays are equal.  In other words, two arrays
  1745      * are equal if they contain the same elements in the same order.  Also,
  1746      * two array references are considered equal if both are <tt>null</tt>.<p>
  1747      *
  1748      * @param a one array to be tested for equality
  1749      * @param a2 the other array to be tested for equality
  1750      * @return <tt>true</tt> if the two arrays are equal
  1751      */
  1752     public static boolean equals(boolean[] a, boolean[] a2) {
  1753         if (a==a2)
  1754             return true;
  1755         if (a==null || a2==null)
  1756             return false;
  1757 
  1758         int length = a.length;
  1759         if (a2.length != length)
  1760             return false;
  1761 
  1762         for (int i=0; i<length; i++)
  1763             if (a[i] != a2[i])
  1764                 return false;
  1765 
  1766         return true;
  1767     }
  1768 
  1769     /**
  1770      * Returns <tt>true</tt> if the two specified arrays of doubles are
  1771      * <i>equal</i> to one another.  Two arrays are considered equal if both
  1772      * arrays contain the same number of elements, and all corresponding pairs
  1773      * of elements in the two arrays are equal.  In other words, two arrays
  1774      * are equal if they contain the same elements in the same order.  Also,
  1775      * two array references are considered equal if both are <tt>null</tt>.<p>
  1776      *
  1777      * Two doubles <tt>d1</tt> and <tt>d2</tt> are considered equal if:
  1778      * <pre>    <tt>new Double(d1).equals(new Double(d2))</tt></pre>
  1779      * (Unlike the <tt>==</tt> operator, this method considers
  1780      * <tt>NaN</tt> equals to itself, and 0.0d unequal to -0.0d.)
  1781      *
  1782      * @param a one array to be tested for equality
  1783      * @param a2 the other array to be tested for equality
  1784      * @return <tt>true</tt> if the two arrays are equal
  1785      * @see Double#equals(Object)
  1786      */
  1787     public static boolean equals(double[] a, double[] a2) {
  1788         if (a==a2)
  1789             return true;
  1790         if (a==null || a2==null)
  1791             return false;
  1792 
  1793         int length = a.length;
  1794         if (a2.length != length)
  1795             return false;
  1796 
  1797         for (int i=0; i<length; i++)
  1798             if (Double.doubleToLongBits(a[i])!=Double.doubleToLongBits(a2[i]))
  1799                 return false;
  1800 
  1801         return true;
  1802     }
  1803 
  1804     /**
  1805      * Returns <tt>true</tt> if the two specified arrays of floats are
  1806      * <i>equal</i> to one another.  Two arrays are considered equal if both
  1807      * arrays contain the same number of elements, and all corresponding pairs
  1808      * of elements in the two arrays are equal.  In other words, two arrays
  1809      * are equal if they contain the same elements in the same order.  Also,
  1810      * two array references are considered equal if both are <tt>null</tt>.<p>
  1811      *
  1812      * Two floats <tt>f1</tt> and <tt>f2</tt> are considered equal if:
  1813      * <pre>    <tt>new Float(f1).equals(new Float(f2))</tt></pre>
  1814      * (Unlike the <tt>==</tt> operator, this method considers
  1815      * <tt>NaN</tt> equals to itself, and 0.0f unequal to -0.0f.)
  1816      *
  1817      * @param a one array to be tested for equality
  1818      * @param a2 the other array to be tested for equality
  1819      * @return <tt>true</tt> if the two arrays are equal
  1820      * @see Float#equals(Object)
  1821      */
  1822     public static boolean equals(float[] a, float[] a2) {
  1823         if (a==a2)
  1824             return true;
  1825         if (a==null || a2==null)
  1826             return false;
  1827 
  1828         int length = a.length;
  1829         if (a2.length != length)
  1830             return false;
  1831 
  1832         for (int i=0; i<length; i++)
  1833             if (Float.floatToIntBits(a[i])!=Float.floatToIntBits(a2[i]))
  1834                 return false;
  1835 
  1836         return true;
  1837     }
  1838 
  1839     /**
  1840      * Returns <tt>true</tt> if the two specified arrays of Objects are
  1841      * <i>equal</i> to one another.  The two arrays are considered equal if
  1842      * both arrays contain the same number of elements, and all corresponding
  1843      * pairs of elements in the two arrays are equal.  Two objects <tt>e1</tt>
  1844      * and <tt>e2</tt> are considered <i>equal</i> if <tt>(e1==null ? e2==null
  1845      * : e1.equals(e2))</tt>.  In other words, the two arrays are equal if
  1846      * they contain the same elements in the same order.  Also, two array
  1847      * references are considered equal if both are <tt>null</tt>.<p>
  1848      *
  1849      * @param a one array to be tested for equality
  1850      * @param a2 the other array to be tested for equality
  1851      * @return <tt>true</tt> if the two arrays are equal
  1852      */
  1853     public static boolean equals(Object[] a, Object[] a2) {
  1854         if (a==a2)
  1855             return true;
  1856         if (a==null || a2==null)
  1857             return false;
  1858 
  1859         int length = a.length;
  1860         if (a2.length != length)
  1861             return false;
  1862 
  1863         for (int i=0; i<length; i++) {
  1864             Object o1 = a[i];
  1865             Object o2 = a2[i];
  1866             if (!(o1==null ? o2==null : o1.equals(o2)))
  1867                 return false;
  1868         }
  1869 
  1870         return true;
  1871     }
  1872 
  1873     // Filling
  1874 
  1875     /**
  1876      * Assigns the specified long value to each element of the specified array
  1877      * of longs.
  1878      *
  1879      * @param a the array to be filled
  1880      * @param val the value to be stored in all elements of the array
  1881      */
  1882     public static void fill(long[] a, long val) {
  1883         for (int i = 0, len = a.length; i < len; i++)
  1884             a[i] = val;
  1885     }
  1886 
  1887     /**
  1888      * Assigns the specified long value to each element of the specified
  1889      * range of the specified array of longs.  The range to be filled
  1890      * extends from index <tt>fromIndex</tt>, inclusive, to index
  1891      * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
  1892      * range to be filled is empty.)
  1893      *
  1894      * @param a the array to be filled
  1895      * @param fromIndex the index of the first element (inclusive) to be
  1896      *        filled with the specified value
  1897      * @param toIndex the index of the last element (exclusive) to be
  1898      *        filled with the specified value
  1899      * @param val the value to be stored in all elements of the array
  1900      * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
  1901      * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
  1902      *         <tt>toIndex &gt; a.length</tt>
  1903      */
  1904     public static void fill(long[] a, int fromIndex, int toIndex, long val) {
  1905         rangeCheck(a.length, fromIndex, toIndex);
  1906         for (int i = fromIndex; i < toIndex; i++)
  1907             a[i] = val;
  1908     }
  1909 
  1910     /**
  1911      * Assigns the specified int value to each element of the specified array
  1912      * of ints.
  1913      *
  1914      * @param a the array to be filled
  1915      * @param val the value to be stored in all elements of the array
  1916      */
  1917     public static void fill(int[] a, int val) {
  1918         for (int i = 0, len = a.length; i < len; i++)
  1919             a[i] = val;
  1920     }
  1921 
  1922     /**
  1923      * Assigns the specified int value to each element of the specified
  1924      * range of the specified array of ints.  The range to be filled
  1925      * extends from index <tt>fromIndex</tt>, inclusive, to index
  1926      * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
  1927      * range to be filled is empty.)
  1928      *
  1929      * @param a the array to be filled
  1930      * @param fromIndex the index of the first element (inclusive) to be
  1931      *        filled with the specified value
  1932      * @param toIndex the index of the last element (exclusive) to be
  1933      *        filled with the specified value
  1934      * @param val the value to be stored in all elements of the array
  1935      * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
  1936      * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
  1937      *         <tt>toIndex &gt; a.length</tt>
  1938      */
  1939     public static void fill(int[] a, int fromIndex, int toIndex, int val) {
  1940         rangeCheck(a.length, fromIndex, toIndex);
  1941         for (int i = fromIndex; i < toIndex; i++)
  1942             a[i] = val;
  1943     }
  1944 
  1945     /**
  1946      * Assigns the specified short value to each element of the specified array
  1947      * of shorts.
  1948      *
  1949      * @param a the array to be filled
  1950      * @param val the value to be stored in all elements of the array
  1951      */
  1952     public static void fill(short[] a, short val) {
  1953         for (int i = 0, len = a.length; i < len; i++)
  1954             a[i] = val;
  1955     }
  1956 
  1957     /**
  1958      * Assigns the specified short value to each element of the specified
  1959      * range of the specified array of shorts.  The range to be filled
  1960      * extends from index <tt>fromIndex</tt>, inclusive, to index
  1961      * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
  1962      * range to be filled is empty.)
  1963      *
  1964      * @param a the array to be filled
  1965      * @param fromIndex the index of the first element (inclusive) to be
  1966      *        filled with the specified value
  1967      * @param toIndex the index of the last element (exclusive) to be
  1968      *        filled with the specified value
  1969      * @param val the value to be stored in all elements of the array
  1970      * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
  1971      * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
  1972      *         <tt>toIndex &gt; a.length</tt>
  1973      */
  1974     public static void fill(short[] a, int fromIndex, int toIndex, short val) {
  1975         rangeCheck(a.length, fromIndex, toIndex);
  1976         for (int i = fromIndex; i < toIndex; i++)
  1977             a[i] = val;
  1978     }
  1979 
  1980     /**
  1981      * Assigns the specified char value to each element of the specified array
  1982      * of chars.
  1983      *
  1984      * @param a the array to be filled
  1985      * @param val the value to be stored in all elements of the array
  1986      */
  1987     public static void fill(char[] a, char val) {
  1988         for (int i = 0, len = a.length; i < len; i++)
  1989             a[i] = val;
  1990     }
  1991 
  1992     /**
  1993      * Assigns the specified char value to each element of the specified
  1994      * range of the specified array of chars.  The range to be filled
  1995      * extends from index <tt>fromIndex</tt>, inclusive, to index
  1996      * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
  1997      * range to be filled is empty.)
  1998      *
  1999      * @param a the array to be filled
  2000      * @param fromIndex the index of the first element (inclusive) to be
  2001      *        filled with the specified value
  2002      * @param toIndex the index of the last element (exclusive) to be
  2003      *        filled with the specified value
  2004      * @param val the value to be stored in all elements of the array
  2005      * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
  2006      * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
  2007      *         <tt>toIndex &gt; a.length</tt>
  2008      */
  2009     public static void fill(char[] a, int fromIndex, int toIndex, char val) {
  2010         rangeCheck(a.length, fromIndex, toIndex);
  2011         for (int i = fromIndex; i < toIndex; i++)
  2012             a[i] = val;
  2013     }
  2014 
  2015     /**
  2016      * Assigns the specified byte value to each element of the specified array
  2017      * of bytes.
  2018      *
  2019      * @param a the array to be filled
  2020      * @param val the value to be stored in all elements of the array
  2021      */
  2022     public static void fill(byte[] a, byte val) {
  2023         for (int i = 0, len = a.length; i < len; i++)
  2024             a[i] = val;
  2025     }
  2026 
  2027     /**
  2028      * Assigns the specified byte value to each element of the specified
  2029      * range of the specified array of bytes.  The range to be filled
  2030      * extends from index <tt>fromIndex</tt>, inclusive, to index
  2031      * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
  2032      * range to be filled is empty.)
  2033      *
  2034      * @param a the array to be filled
  2035      * @param fromIndex the index of the first element (inclusive) to be
  2036      *        filled with the specified value
  2037      * @param toIndex the index of the last element (exclusive) to be
  2038      *        filled with the specified value
  2039      * @param val the value to be stored in all elements of the array
  2040      * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
  2041      * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
  2042      *         <tt>toIndex &gt; a.length</tt>
  2043      */
  2044     public static void fill(byte[] a, int fromIndex, int toIndex, byte val) {
  2045         rangeCheck(a.length, fromIndex, toIndex);
  2046         for (int i = fromIndex; i < toIndex; i++)
  2047             a[i] = val;
  2048     }
  2049 
  2050     /**
  2051      * Assigns the specified boolean value to each element of the specified
  2052      * array of booleans.
  2053      *
  2054      * @param a the array to be filled
  2055      * @param val the value to be stored in all elements of the array
  2056      */
  2057     public static void fill(boolean[] a, boolean val) {
  2058         for (int i = 0, len = a.length; i < len; i++)
  2059             a[i] = val;
  2060     }
  2061 
  2062     /**
  2063      * Assigns the specified boolean value to each element of the specified
  2064      * range of the specified array of booleans.  The range to be filled
  2065      * extends from index <tt>fromIndex</tt>, inclusive, to index
  2066      * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
  2067      * range to be filled is empty.)
  2068      *
  2069      * @param a the array to be filled
  2070      * @param fromIndex the index of the first element (inclusive) to be
  2071      *        filled with the specified value
  2072      * @param toIndex the index of the last element (exclusive) to be
  2073      *        filled with the specified value
  2074      * @param val the value to be stored in all elements of the array
  2075      * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
  2076      * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
  2077      *         <tt>toIndex &gt; a.length</tt>
  2078      */
  2079     public static void fill(boolean[] a, int fromIndex, int toIndex,
  2080                             boolean val) {
  2081         rangeCheck(a.length, fromIndex, toIndex);
  2082         for (int i = fromIndex; i < toIndex; i++)
  2083             a[i] = val;
  2084     }
  2085 
  2086     /**
  2087      * Assigns the specified double value to each element of the specified
  2088      * array of doubles.
  2089      *
  2090      * @param a the array to be filled
  2091      * @param val the value to be stored in all elements of the array
  2092      */
  2093     public static void fill(double[] a, double val) {
  2094         for (int i = 0, len = a.length; i < len; i++)
  2095             a[i] = val;
  2096     }
  2097 
  2098     /**
  2099      * Assigns the specified double value to each element of the specified
  2100      * range of the specified array of doubles.  The range to be filled
  2101      * extends from index <tt>fromIndex</tt>, inclusive, to index
  2102      * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
  2103      * range to be filled is empty.)
  2104      *
  2105      * @param a the array to be filled
  2106      * @param fromIndex the index of the first element (inclusive) to be
  2107      *        filled with the specified value
  2108      * @param toIndex the index of the last element (exclusive) to be
  2109      *        filled with the specified value
  2110      * @param val the value to be stored in all elements of the array
  2111      * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
  2112      * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
  2113      *         <tt>toIndex &gt; a.length</tt>
  2114      */
  2115     public static void fill(double[] a, int fromIndex, int toIndex,double val){
  2116         rangeCheck(a.length, fromIndex, toIndex);
  2117         for (int i = fromIndex; i < toIndex; i++)
  2118             a[i] = val;
  2119     }
  2120 
  2121     /**
  2122      * Assigns the specified float value to each element of the specified array
  2123      * of floats.
  2124      *
  2125      * @param a the array to be filled
  2126      * @param val the value to be stored in all elements of the array
  2127      */
  2128     public static void fill(float[] a, float val) {
  2129         for (int i = 0, len = a.length; i < len; i++)
  2130             a[i] = val;
  2131     }
  2132 
  2133     /**
  2134      * Assigns the specified float value to each element of the specified
  2135      * range of the specified array of floats.  The range to be filled
  2136      * extends from index <tt>fromIndex</tt>, inclusive, to index
  2137      * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
  2138      * range to be filled is empty.)
  2139      *
  2140      * @param a the array to be filled
  2141      * @param fromIndex the index of the first element (inclusive) to be
  2142      *        filled with the specified value
  2143      * @param toIndex the index of the last element (exclusive) to be
  2144      *        filled with the specified value
  2145      * @param val the value to be stored in all elements of the array
  2146      * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
  2147      * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
  2148      *         <tt>toIndex &gt; a.length</tt>
  2149      */
  2150     public static void fill(float[] a, int fromIndex, int toIndex, float val) {
  2151         rangeCheck(a.length, fromIndex, toIndex);
  2152         for (int i = fromIndex; i < toIndex; i++)
  2153             a[i] = val;
  2154     }
  2155 
  2156     /**
  2157      * Assigns the specified Object reference to each element of the specified
  2158      * array of Objects.
  2159      *
  2160      * @param a the array to be filled
  2161      * @param val the value to be stored in all elements of the array
  2162      * @throws ArrayStoreException if the specified value is not of a
  2163      *         runtime type that can be stored in the specified array
  2164      */
  2165     public static void fill(Object[] a, Object val) {
  2166         for (int i = 0, len = a.length; i < len; i++)
  2167             a[i] = val;
  2168     }
  2169 
  2170     /**
  2171      * Assigns the specified Object reference to each element of the specified
  2172      * range of the specified array of Objects.  The range to be filled
  2173      * extends from index <tt>fromIndex</tt>, inclusive, to index
  2174      * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
  2175      * range to be filled is empty.)
  2176      *
  2177      * @param a the array to be filled
  2178      * @param fromIndex the index of the first element (inclusive) to be
  2179      *        filled with the specified value
  2180      * @param toIndex the index of the last element (exclusive) to be
  2181      *        filled with the specified value
  2182      * @param val the value to be stored in all elements of the array
  2183      * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
  2184      * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
  2185      *         <tt>toIndex &gt; a.length</tt>
  2186      * @throws ArrayStoreException if the specified value is not of a
  2187      *         runtime type that can be stored in the specified array
  2188      */
  2189     public static void fill(Object[] a, int fromIndex, int toIndex, Object val) {
  2190         rangeCheck(a.length, fromIndex, toIndex);
  2191         for (int i = fromIndex; i < toIndex; i++)
  2192             a[i] = val;
  2193     }
  2194 
  2195     // Cloning
  2196 
  2197     /**
  2198      * Copies the specified array, truncating or padding with nulls (if necessary)
  2199      * so the copy has the specified length.  For all indices that are
  2200      * valid in both the original array and the copy, the two arrays will
  2201      * contain identical values.  For any indices that are valid in the
  2202      * copy but not the original, the copy will contain <tt>null</tt>.
  2203      * Such indices will exist if and only if the specified length
  2204      * is greater than that of the original array.
  2205      * The resulting array is of exactly the same class as the original array.
  2206      *
  2207      * @param original the array to be copied
  2208      * @param newLength the length of the copy to be returned
  2209      * @return a copy of the original array, truncated or padded with nulls
  2210      *     to obtain the specified length
  2211      * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
  2212      * @throws NullPointerException if <tt>original</tt> is null
  2213      * @since 1.6
  2214      */
  2215     public static <T> T[] copyOf(T[] original, int newLength) {
  2216         return (T[]) copyOf(original, newLength, original.getClass());
  2217     }
  2218 
  2219     /**
  2220      * Copies the specified array, truncating or padding with nulls (if necessary)
  2221      * so the copy has the specified length.  For all indices that are
  2222      * valid in both the original array and the copy, the two arrays will
  2223      * contain identical values.  For any indices that are valid in the
  2224      * copy but not the original, the copy will contain <tt>null</tt>.
  2225      * Such indices will exist if and only if the specified length
  2226      * is greater than that of the original array.
  2227      * The resulting array is of the class <tt>newType</tt>.
  2228      *
  2229      * @param original the array to be copied
  2230      * @param newLength the length of the copy to be returned
  2231      * @param newType the class of the copy to be returned
  2232      * @return a copy of the original array, truncated or padded with nulls
  2233      *     to obtain the specified length
  2234      * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
  2235      * @throws NullPointerException if <tt>original</tt> is null
  2236      * @throws ArrayStoreException if an element copied from
  2237      *     <tt>original</tt> is not of a runtime type that can be stored in
  2238      *     an array of class <tt>newType</tt>
  2239      * @since 1.6
  2240      */
  2241     public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
  2242         T[] copy = ((Object)newType == (Object)Object[].class)
  2243             ? (T[]) new Object[newLength]
  2244             : (T[]) Array.newInstance(newType.getComponentType(), newLength);
  2245         System.arraycopy(original, 0, copy, 0,
  2246                          Math.min(original.length, newLength));
  2247         return copy;
  2248     }
  2249 
  2250     /**
  2251      * Copies the specified array, truncating or padding with zeros (if necessary)
  2252      * so the copy has the specified length.  For all indices that are
  2253      * valid in both the original array and the copy, the two arrays will
  2254      * contain identical values.  For any indices that are valid in the
  2255      * copy but not the original, the copy will contain <tt>(byte)0</tt>.
  2256      * Such indices will exist if and only if the specified length
  2257      * is greater than that of the original array.
  2258      *
  2259      * @param original the array to be copied
  2260      * @param newLength the length of the copy to be returned
  2261      * @return a copy of the original array, truncated or padded with zeros
  2262      *     to obtain the specified length
  2263      * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
  2264      * @throws NullPointerException if <tt>original</tt> is null
  2265      * @since 1.6
  2266      */
  2267     public static byte[] copyOf(byte[] original, int newLength) {
  2268         byte[] copy = new byte[newLength];
  2269         System.arraycopy(original, 0, copy, 0,
  2270                          Math.min(original.length, newLength));
  2271         return copy;
  2272     }
  2273 
  2274     /**
  2275      * Copies the specified array, truncating or padding with zeros (if necessary)
  2276      * so the copy has the specified length.  For all indices that are
  2277      * valid in both the original array and the copy, the two arrays will
  2278      * contain identical values.  For any indices that are valid in the
  2279      * copy but not the original, the copy will contain <tt>(short)0</tt>.
  2280      * Such indices will exist if and only if the specified length
  2281      * is greater than that of the original array.
  2282      *
  2283      * @param original the array to be copied
  2284      * @param newLength the length of the copy to be returned
  2285      * @return a copy of the original array, truncated or padded with zeros
  2286      *     to obtain the specified length
  2287      * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
  2288      * @throws NullPointerException if <tt>original</tt> is null
  2289      * @since 1.6
  2290      */
  2291     public static short[] copyOf(short[] original, int newLength) {
  2292         short[] copy = new short[newLength];
  2293         System.arraycopy(original, 0, copy, 0,
  2294                          Math.min(original.length, newLength));
  2295         return copy;
  2296     }
  2297 
  2298     /**
  2299      * Copies the specified array, truncating or padding with zeros (if necessary)
  2300      * so the copy has the specified length.  For all indices that are
  2301      * valid in both the original array and the copy, the two arrays will
  2302      * contain identical values.  For any indices that are valid in the
  2303      * copy but not the original, the copy will contain <tt>0</tt>.
  2304      * Such indices will exist if and only if the specified length
  2305      * is greater than that of the original array.
  2306      *
  2307      * @param original the array to be copied
  2308      * @param newLength the length of the copy to be returned
  2309      * @return a copy of the original array, truncated or padded with zeros
  2310      *     to obtain the specified length
  2311      * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
  2312      * @throws NullPointerException if <tt>original</tt> is null
  2313      * @since 1.6
  2314      */
  2315     public static int[] copyOf(int[] original, int newLength) {
  2316         int[] copy = new int[newLength];
  2317         System.arraycopy(original, 0, copy, 0,
  2318                          Math.min(original.length, newLength));
  2319         return copy;
  2320     }
  2321 
  2322     /**
  2323      * Copies the specified array, truncating or padding with zeros (if necessary)
  2324      * so the copy has the specified length.  For all indices that are
  2325      * valid in both the original array and the copy, the two arrays will
  2326      * contain identical values.  For any indices that are valid in the
  2327      * copy but not the original, the copy will contain <tt>0L</tt>.
  2328      * Such indices will exist if and only if the specified length
  2329      * is greater than that of the original array.
  2330      *
  2331      * @param original the array to be copied
  2332      * @param newLength the length of the copy to be returned
  2333      * @return a copy of the original array, truncated or padded with zeros
  2334      *     to obtain the specified length
  2335      * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
  2336      * @throws NullPointerException if <tt>original</tt> is null
  2337      * @since 1.6
  2338      */
  2339     public static long[] copyOf(long[] original, int newLength) {
  2340         long[] copy = new long[newLength];
  2341         System.arraycopy(original, 0, copy, 0,
  2342                          Math.min(original.length, newLength));
  2343         return copy;
  2344     }
  2345 
  2346     /**
  2347      * Copies the specified array, truncating or padding with null characters (if necessary)
  2348      * so the copy has the specified length.  For all indices that are valid
  2349      * in both the original array and the copy, the two arrays will contain
  2350      * identical values.  For any indices that are valid in the copy but not
  2351      * the original, the copy will contain <tt>'\\u000'</tt>.  Such indices
  2352      * will exist if and only if the specified length is greater than that of
  2353      * the original array.
  2354      *
  2355      * @param original the array to be copied
  2356      * @param newLength the length of the copy to be returned
  2357      * @return a copy of the original array, truncated or padded with null characters
  2358      *     to obtain the specified length
  2359      * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
  2360      * @throws NullPointerException if <tt>original</tt> is null
  2361      * @since 1.6
  2362      */
  2363     public static char[] copyOf(char[] original, int newLength) {
  2364         char[] copy = new char[newLength];
  2365         System.arraycopy(original, 0, copy, 0,
  2366                          Math.min(original.length, newLength));
  2367         return copy;
  2368     }
  2369 
  2370     /**
  2371      * Copies the specified array, truncating or padding with zeros (if necessary)
  2372      * so the copy has the specified length.  For all indices that are
  2373      * valid in both the original array and the copy, the two arrays will
  2374      * contain identical values.  For any indices that are valid in the
  2375      * copy but not the original, the copy will contain <tt>0f</tt>.
  2376      * Such indices will exist if and only if the specified length
  2377      * is greater than that of the original array.
  2378      *
  2379      * @param original the array to be copied
  2380      * @param newLength the length of the copy to be returned
  2381      * @return a copy of the original array, truncated or padded with zeros
  2382      *     to obtain the specified length
  2383      * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
  2384      * @throws NullPointerException if <tt>original</tt> is null
  2385      * @since 1.6
  2386      */
  2387     public static float[] copyOf(float[] original, int newLength) {
  2388         float[] copy = new float[newLength];
  2389         System.arraycopy(original, 0, copy, 0,
  2390                          Math.min(original.length, newLength));
  2391         return copy;
  2392     }
  2393 
  2394     /**
  2395      * Copies the specified array, truncating or padding with zeros (if necessary)
  2396      * so the copy has the specified length.  For all indices that are
  2397      * valid in both the original array and the copy, the two arrays will
  2398      * contain identical values.  For any indices that are valid in the
  2399      * copy but not the original, the copy will contain <tt>0d</tt>.
  2400      * Such indices will exist if and only if the specified length
  2401      * is greater than that of the original array.
  2402      *
  2403      * @param original the array to be copied
  2404      * @param newLength the length of the copy to be returned
  2405      * @return a copy of the original array, truncated or padded with zeros
  2406      *     to obtain the specified length
  2407      * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
  2408      * @throws NullPointerException if <tt>original</tt> is null
  2409      * @since 1.6
  2410      */
  2411     public static double[] copyOf(double[] original, int newLength) {
  2412         double[] copy = new double[newLength];
  2413         System.arraycopy(original, 0, copy, 0,
  2414                          Math.min(original.length, newLength));
  2415         return copy;
  2416     }
  2417 
  2418     /**
  2419      * Copies the specified array, truncating or padding with <tt>false</tt> (if necessary)
  2420      * so the copy has the specified length.  For all indices that are
  2421      * valid in both the original array and the copy, the two arrays will
  2422      * contain identical values.  For any indices that are valid in the
  2423      * copy but not the original, the copy will contain <tt>false</tt>.
  2424      * Such indices will exist if and only if the specified length
  2425      * is greater than that of the original array.
  2426      *
  2427      * @param original the array to be copied
  2428      * @param newLength the length of the copy to be returned
  2429      * @return a copy of the original array, truncated or padded with false elements
  2430      *     to obtain the specified length
  2431      * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
  2432      * @throws NullPointerException if <tt>original</tt> is null
  2433      * @since 1.6
  2434      */
  2435     public static boolean[] copyOf(boolean[] original, int newLength) {
  2436         boolean[] copy = new boolean[newLength];
  2437         System.arraycopy(original, 0, copy, 0,
  2438                          Math.min(original.length, newLength));
  2439         return copy;
  2440     }
  2441 
  2442     /**
  2443      * Copies the specified range of the specified array into a new array.
  2444      * The initial index of the range (<tt>from</tt>) must lie between zero
  2445      * and <tt>original.length</tt>, inclusive.  The value at
  2446      * <tt>original[from]</tt> is placed into the initial element of the copy
  2447      * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
  2448      * Values from subsequent elements in the original array are placed into
  2449      * subsequent elements in the copy.  The final index of the range
  2450      * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
  2451      * may be greater than <tt>original.length</tt>, in which case
  2452      * <tt>null</tt> is placed in all elements of the copy whose index is
  2453      * greater than or equal to <tt>original.length - from</tt>.  The length
  2454      * of the returned array will be <tt>to - from</tt>.
  2455      * <p>
  2456      * The resulting array is of exactly the same class as the original array.
  2457      *
  2458      * @param original the array from which a range is to be copied
  2459      * @param from the initial index of the range to be copied, inclusive
  2460      * @param to the final index of the range to be copied, exclusive.
  2461      *     (This index may lie outside the array.)
  2462      * @return a new array containing the specified range from the original array,
  2463      *     truncated or padded with nulls to obtain the required length
  2464      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
  2465      *     or {@code from > original.length}
  2466      * @throws IllegalArgumentException if <tt>from &gt; to</tt>
  2467      * @throws NullPointerException if <tt>original</tt> is null
  2468      * @since 1.6
  2469      */
  2470     public static <T> T[] copyOfRange(T[] original, int from, int to) {
  2471         return copyOfRange(original, from, to, (Class<T[]>) original.getClass());
  2472     }
  2473 
  2474     /**
  2475      * Copies the specified range of the specified array into a new array.
  2476      * The initial index of the range (<tt>from</tt>) must lie between zero
  2477      * and <tt>original.length</tt>, inclusive.  The value at
  2478      * <tt>original[from]</tt> is placed into the initial element of the copy
  2479      * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
  2480      * Values from subsequent elements in the original array are placed into
  2481      * subsequent elements in the copy.  The final index of the range
  2482      * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
  2483      * may be greater than <tt>original.length</tt>, in which case
  2484      * <tt>null</tt> is placed in all elements of the copy whose index is
  2485      * greater than or equal to <tt>original.length - from</tt>.  The length
  2486      * of the returned array will be <tt>to - from</tt>.
  2487      * The resulting array is of the class <tt>newType</tt>.
  2488      *
  2489      * @param original the array from which a range is to be copied
  2490      * @param from the initial index of the range to be copied, inclusive
  2491      * @param to the final index of the range to be copied, exclusive.
  2492      *     (This index may lie outside the array.)
  2493      * @param newType the class of the copy to be returned
  2494      * @return a new array containing the specified range from the original array,
  2495      *     truncated or padded with nulls to obtain the required length
  2496      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
  2497      *     or {@code from > original.length}
  2498      * @throws IllegalArgumentException if <tt>from &gt; to</tt>
  2499      * @throws NullPointerException if <tt>original</tt> is null
  2500      * @throws ArrayStoreException if an element copied from
  2501      *     <tt>original</tt> is not of a runtime type that can be stored in
  2502      *     an array of class <tt>newType</tt>.
  2503      * @since 1.6
  2504      */
  2505     public static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {
  2506         int newLength = to - from;
  2507         if (newLength < 0)
  2508             throw new IllegalArgumentException(from + " > " + to);
  2509         T[] copy = ((Object)newType == (Object)Object[].class)
  2510             ? (T[]) new Object[newLength]
  2511             : (T[]) Array.newInstance(newType.getComponentType(), newLength);
  2512         System.arraycopy(original, from, copy, 0,
  2513                          Math.min(original.length - from, newLength));
  2514         return copy;
  2515     }
  2516 
  2517     /**
  2518      * Copies the specified range of the specified array into a new array.
  2519      * The initial index of the range (<tt>from</tt>) must lie between zero
  2520      * and <tt>original.length</tt>, inclusive.  The value at
  2521      * <tt>original[from]</tt> is placed into the initial element of the copy
  2522      * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
  2523      * Values from subsequent elements in the original array are placed into
  2524      * subsequent elements in the copy.  The final index of the range
  2525      * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
  2526      * may be greater than <tt>original.length</tt>, in which case
  2527      * <tt>(byte)0</tt> is placed in all elements of the copy whose index is
  2528      * greater than or equal to <tt>original.length - from</tt>.  The length
  2529      * of the returned array will be <tt>to - from</tt>.
  2530      *
  2531      * @param original the array from which a range is to be copied
  2532      * @param from the initial index of the range to be copied, inclusive
  2533      * @param to the final index of the range to be copied, exclusive.
  2534      *     (This index may lie outside the array.)
  2535      * @return a new array containing the specified range from the original array,
  2536      *     truncated or padded with zeros to obtain the required length
  2537      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
  2538      *     or {@code from > original.length}
  2539      * @throws IllegalArgumentException if <tt>from &gt; to</tt>
  2540      * @throws NullPointerException if <tt>original</tt> is null
  2541      * @since 1.6
  2542      */
  2543     public static byte[] copyOfRange(byte[] original, int from, int to) {
  2544         int newLength = to - from;
  2545         if (newLength < 0)
  2546             throw new IllegalArgumentException(from + " > " + to);
  2547         byte[] copy = new byte[newLength];
  2548         System.arraycopy(original, from, copy, 0,
  2549                          Math.min(original.length - from, newLength));
  2550         return copy;
  2551     }
  2552 
  2553     /**
  2554      * Copies the specified range of the specified array into a new array.
  2555      * The initial index of the range (<tt>from</tt>) must lie between zero
  2556      * and <tt>original.length</tt>, inclusive.  The value at
  2557      * <tt>original[from]</tt> is placed into the initial element of the copy
  2558      * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
  2559      * Values from subsequent elements in the original array are placed into
  2560      * subsequent elements in the copy.  The final index of the range
  2561      * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
  2562      * may be greater than <tt>original.length</tt>, in which case
  2563      * <tt>(short)0</tt> is placed in all elements of the copy whose index is
  2564      * greater than or equal to <tt>original.length - from</tt>.  The length
  2565      * of the returned array will be <tt>to - from</tt>.
  2566      *
  2567      * @param original the array from which a range is to be copied
  2568      * @param from the initial index of the range to be copied, inclusive
  2569      * @param to the final index of the range to be copied, exclusive.
  2570      *     (This index may lie outside the array.)
  2571      * @return a new array containing the specified range from the original array,
  2572      *     truncated or padded with zeros to obtain the required length
  2573      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
  2574      *     or {@code from > original.length}
  2575      * @throws IllegalArgumentException if <tt>from &gt; to</tt>
  2576      * @throws NullPointerException if <tt>original</tt> is null
  2577      * @since 1.6
  2578      */
  2579     public static short[] copyOfRange(short[] original, int from, int to) {
  2580         int newLength = to - from;
  2581         if (newLength < 0)
  2582             throw new IllegalArgumentException(from + " > " + to);
  2583         short[] copy = new short[newLength];
  2584         System.arraycopy(original, from, copy, 0,
  2585                          Math.min(original.length - from, newLength));
  2586         return copy;
  2587     }
  2588 
  2589     /**
  2590      * Copies the specified range of the specified array into a new array.
  2591      * The initial index of the range (<tt>from</tt>) must lie between zero
  2592      * and <tt>original.length</tt>, inclusive.  The value at
  2593      * <tt>original[from]</tt> is placed into the initial element of the copy
  2594      * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
  2595      * Values from subsequent elements in the original array are placed into
  2596      * subsequent elements in the copy.  The final index of the range
  2597      * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
  2598      * may be greater than <tt>original.length</tt>, in which case
  2599      * <tt>0</tt> is placed in all elements of the copy whose index is
  2600      * greater than or equal to <tt>original.length - from</tt>.  The length
  2601      * of the returned array will be <tt>to - from</tt>.
  2602      *
  2603      * @param original the array from which a range is to be copied
  2604      * @param from the initial index of the range to be copied, inclusive
  2605      * @param to the final index of the range to be copied, exclusive.
  2606      *     (This index may lie outside the array.)
  2607      * @return a new array containing the specified range from the original array,
  2608      *     truncated or padded with zeros to obtain the required length
  2609      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
  2610      *     or {@code from > original.length}
  2611      * @throws IllegalArgumentException if <tt>from &gt; to</tt>
  2612      * @throws NullPointerException if <tt>original</tt> is null
  2613      * @since 1.6
  2614      */
  2615     public static int[] copyOfRange(int[] original, int from, int to) {
  2616         int newLength = to - from;
  2617         if (newLength < 0)
  2618             throw new IllegalArgumentException(from + " > " + to);
  2619         int[] copy = new int[newLength];
  2620         System.arraycopy(original, from, copy, 0,
  2621                          Math.min(original.length - from, newLength));
  2622         return copy;
  2623     }
  2624 
  2625     /**
  2626      * Copies the specified range of the specified array into a new array.
  2627      * The initial index of the range (<tt>from</tt>) must lie between zero
  2628      * and <tt>original.length</tt>, inclusive.  The value at
  2629      * <tt>original[from]</tt> is placed into the initial element of the copy
  2630      * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
  2631      * Values from subsequent elements in the original array are placed into
  2632      * subsequent elements in the copy.  The final index of the range
  2633      * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
  2634      * may be greater than <tt>original.length</tt>, in which case
  2635      * <tt>0L</tt> is placed in all elements of the copy whose index is
  2636      * greater than or equal to <tt>original.length - from</tt>.  The length
  2637      * of the returned array will be <tt>to - from</tt>.
  2638      *
  2639      * @param original the array from which a range is to be copied
  2640      * @param from the initial index of the range to be copied, inclusive
  2641      * @param to the final index of the range to be copied, exclusive.
  2642      *     (This index may lie outside the array.)
  2643      * @return a new array containing the specified range from the original array,
  2644      *     truncated or padded with zeros to obtain the required length
  2645      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
  2646      *     or {@code from > original.length}
  2647      * @throws IllegalArgumentException if <tt>from &gt; to</tt>
  2648      * @throws NullPointerException if <tt>original</tt> is null
  2649      * @since 1.6
  2650      */
  2651     public static long[] copyOfRange(long[] original, int from, int to) {
  2652         int newLength = to - from;
  2653         if (newLength < 0)
  2654             throw new IllegalArgumentException(from + " > " + to);
  2655         long[] copy = new long[newLength];
  2656         System.arraycopy(original, from, copy, 0,
  2657                          Math.min(original.length - from, newLength));
  2658         return copy;
  2659     }
  2660 
  2661     /**
  2662      * Copies the specified range of the specified array into a new array.
  2663      * The initial index of the range (<tt>from</tt>) must lie between zero
  2664      * and <tt>original.length</tt>, inclusive.  The value at
  2665      * <tt>original[from]</tt> is placed into the initial element of the copy
  2666      * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
  2667      * Values from subsequent elements in the original array are placed into
  2668      * subsequent elements in the copy.  The final index of the range
  2669      * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
  2670      * may be greater than <tt>original.length</tt>, in which case
  2671      * <tt>'\\u000'</tt> is placed in all elements of the copy whose index is
  2672      * greater than or equal to <tt>original.length - from</tt>.  The length
  2673      * of the returned array will be <tt>to - from</tt>.
  2674      *
  2675      * @param original the array from which a range is to be copied
  2676      * @param from the initial index of the range to be copied, inclusive
  2677      * @param to the final index of the range to be copied, exclusive.
  2678      *     (This index may lie outside the array.)
  2679      * @return a new array containing the specified range from the original array,
  2680      *     truncated or padded with null characters to obtain the required length
  2681      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
  2682      *     or {@code from > original.length}
  2683      * @throws IllegalArgumentException if <tt>from &gt; to</tt>
  2684      * @throws NullPointerException if <tt>original</tt> is null
  2685      * @since 1.6
  2686      */
  2687     public static char[] copyOfRange(char[] original, int from, int to) {
  2688         int newLength = to - from;
  2689         if (newLength < 0)
  2690             throw new IllegalArgumentException(from + " > " + to);
  2691         char[] copy = new char[newLength];
  2692         System.arraycopy(original, from, copy, 0,
  2693                          Math.min(original.length - from, newLength));
  2694         return copy;
  2695     }
  2696 
  2697     /**
  2698      * Copies the specified range of the specified array into a new array.
  2699      * The initial index of the range (<tt>from</tt>) must lie between zero
  2700      * and <tt>original.length</tt>, inclusive.  The value at
  2701      * <tt>original[from]</tt> is placed into the initial element of the copy
  2702      * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
  2703      * Values from subsequent elements in the original array are placed into
  2704      * subsequent elements in the copy.  The final index of the range
  2705      * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
  2706      * may be greater than <tt>original.length</tt>, in which case
  2707      * <tt>0f</tt> is placed in all elements of the copy whose index is
  2708      * greater than or equal to <tt>original.length - from</tt>.  The length
  2709      * of the returned array will be <tt>to - from</tt>.
  2710      *
  2711      * @param original the array from which a range is to be copied
  2712      * @param from the initial index of the range to be copied, inclusive
  2713      * @param to the final index of the range to be copied, exclusive.
  2714      *     (This index may lie outside the array.)
  2715      * @return a new array containing the specified range from the original array,
  2716      *     truncated or padded with zeros to obtain the required length
  2717      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
  2718      *     or {@code from > original.length}
  2719      * @throws IllegalArgumentException if <tt>from &gt; to</tt>
  2720      * @throws NullPointerException if <tt>original</tt> is null
  2721      * @since 1.6
  2722      */
  2723     public static float[] copyOfRange(float[] original, int from, int to) {
  2724         int newLength = to - from;
  2725         if (newLength < 0)
  2726             throw new IllegalArgumentException(from + " > " + to);
  2727         float[] copy = new float[newLength];
  2728         System.arraycopy(original, from, copy, 0,
  2729                          Math.min(original.length - from, newLength));
  2730         return copy;
  2731     }
  2732 
  2733     /**
  2734      * Copies the specified range of the specified array into a new array.
  2735      * The initial index of the range (<tt>from</tt>) must lie between zero
  2736      * and <tt>original.length</tt>, inclusive.  The value at
  2737      * <tt>original[from]</tt> is placed into the initial element of the copy
  2738      * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
  2739      * Values from subsequent elements in the original array are placed into
  2740      * subsequent elements in the copy.  The final index of the range
  2741      * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
  2742      * may be greater than <tt>original.length</tt>, in which case
  2743      * <tt>0d</tt> is placed in all elements of the copy whose index is
  2744      * greater than or equal to <tt>original.length - from</tt>.  The length
  2745      * of the returned array will be <tt>to - from</tt>.
  2746      *
  2747      * @param original the array from which a range is to be copied
  2748      * @param from the initial index of the range to be copied, inclusive
  2749      * @param to the final index of the range to be copied, exclusive.
  2750      *     (This index may lie outside the array.)
  2751      * @return a new array containing the specified range from the original array,
  2752      *     truncated or padded with zeros to obtain the required length
  2753      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
  2754      *     or {@code from > original.length}
  2755      * @throws IllegalArgumentException if <tt>from &gt; to</tt>
  2756      * @throws NullPointerException if <tt>original</tt> is null
  2757      * @since 1.6
  2758      */
  2759     public static double[] copyOfRange(double[] original, int from, int to) {
  2760         int newLength = to - from;
  2761         if (newLength < 0)
  2762             throw new IllegalArgumentException(from + " > " + to);
  2763         double[] copy = new double[newLength];
  2764         System.arraycopy(original, from, copy, 0,
  2765                          Math.min(original.length - from, newLength));
  2766         return copy;
  2767     }
  2768 
  2769     /**
  2770      * Copies the specified range of the specified array into a new array.
  2771      * The initial index of the range (<tt>from</tt>) must lie between zero
  2772      * and <tt>original.length</tt>, inclusive.  The value at
  2773      * <tt>original[from]</tt> is placed into the initial element of the copy
  2774      * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
  2775      * Values from subsequent elements in the original array are placed into
  2776      * subsequent elements in the copy.  The final index of the range
  2777      * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
  2778      * may be greater than <tt>original.length</tt>, in which case
  2779      * <tt>false</tt> is placed in all elements of the copy whose index is
  2780      * greater than or equal to <tt>original.length - from</tt>.  The length
  2781      * of the returned array will be <tt>to - from</tt>.
  2782      *
  2783      * @param original the array from which a range is to be copied
  2784      * @param from the initial index of the range to be copied, inclusive
  2785      * @param to the final index of the range to be copied, exclusive.
  2786      *     (This index may lie outside the array.)
  2787      * @return a new array containing the specified range from the original array,
  2788      *     truncated or padded with false elements to obtain the required length
  2789      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
  2790      *     or {@code from > original.length}
  2791      * @throws IllegalArgumentException if <tt>from &gt; to</tt>
  2792      * @throws NullPointerException if <tt>original</tt> is null
  2793      * @since 1.6
  2794      */
  2795     public static boolean[] copyOfRange(boolean[] original, int from, int to) {
  2796         int newLength = to - from;
  2797         if (newLength < 0)
  2798             throw new IllegalArgumentException(from + " > " + to);
  2799         boolean[] copy = new boolean[newLength];
  2800         System.arraycopy(original, from, copy, 0,
  2801                          Math.min(original.length - from, newLength));
  2802         return copy;
  2803     }
  2804 
  2805     // Misc
  2806 
  2807     /**
  2808      * Returns a fixed-size list backed by the specified array.  (Changes to
  2809      * the returned list "write through" to the array.)  This method acts
  2810      * as bridge between array-based and collection-based APIs, in
  2811      * combination with {@link Collection#toArray}.  The returned list is
  2812      * serializable and implements {@link RandomAccess}.
  2813      *
  2814      * <p>This method also provides a convenient way to create a fixed-size
  2815      * list initialized to contain several elements:
  2816      * <pre>
  2817      *     List&lt;String&gt; stooges = Arrays.asList("Larry", "Moe", "Curly");
  2818      * </pre>
  2819      *
  2820      * @param a the array by which the list will be backed
  2821      * @return a list view of the specified array
  2822      */
  2823     @SafeVarargs
  2824     public static <T> List<T> asList(T... a) {
  2825         return new ArrayList<>(a);
  2826     }
  2827 
  2828     /**
  2829      * @serial include
  2830      */
  2831     private static class ArrayList<E> extends AbstractList<E>
  2832         implements RandomAccess, java.io.Serializable
  2833     {
  2834         private static final long serialVersionUID = -2764017481108945198L;
  2835         private final E[] a;
  2836 
  2837         ArrayList(E[] array) {
  2838             if (array==null)
  2839                 throw new NullPointerException();
  2840             a = array;
  2841         }
  2842 
  2843         public int size() {
  2844             return a.length;
  2845         }
  2846 
  2847         public Object[] toArray() {
  2848             return a.clone();
  2849         }
  2850 
  2851         public <T> T[] toArray(T[] a) {
  2852             int size = size();
  2853             if (a.length < size)
  2854                 return Arrays.copyOf(this.a, size,
  2855                                      (Class<? extends T[]>) a.getClass());
  2856             System.arraycopy(this.a, 0, a, 0, size);
  2857             if (a.length > size)
  2858                 a[size] = null;
  2859             return a;
  2860         }
  2861 
  2862         public E get(int index) {
  2863             return a[index];
  2864         }
  2865 
  2866         public E set(int index, E element) {
  2867             E oldValue = a[index];
  2868             a[index] = element;
  2869             return oldValue;
  2870         }
  2871 
  2872         public int indexOf(Object o) {
  2873             if (o==null) {
  2874                 for (int i=0; i<a.length; i++)
  2875                     if (a[i]==null)
  2876                         return i;
  2877             } else {
  2878                 for (int i=0; i<a.length; i++)
  2879                     if (o.equals(a[i]))
  2880                         return i;
  2881             }
  2882             return -1;
  2883         }
  2884 
  2885         public boolean contains(Object o) {
  2886             return indexOf(o) != -1;
  2887         }
  2888     }
  2889 
  2890     /**
  2891      * Returns a hash code based on the contents of the specified array.
  2892      * For any two <tt>long</tt> arrays <tt>a</tt> and <tt>b</tt>
  2893      * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
  2894      * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
  2895      *
  2896      * <p>The value returned by this method is the same value that would be
  2897      * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
  2898      * method on a {@link List} containing a sequence of {@link Long}
  2899      * instances representing the elements of <tt>a</tt> in the same order.
  2900      * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
  2901      *
  2902      * @param a the array whose hash value to compute
  2903      * @return a content-based hash code for <tt>a</tt>
  2904      * @since 1.5
  2905      */
  2906     public static int hashCode(long a[]) {
  2907         if (a == null)
  2908             return 0;
  2909 
  2910         int result = 1;
  2911         for (long element : a) {
  2912             int elementHash = (int)(element ^ (element >>> 32));
  2913             result = 31 * result + elementHash;
  2914         }
  2915 
  2916         return result;
  2917     }
  2918 
  2919     /**
  2920      * Returns a hash code based on the contents of the specified array.
  2921      * For any two non-null <tt>int</tt> arrays <tt>a</tt> and <tt>b</tt>
  2922      * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
  2923      * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
  2924      *
  2925      * <p>The value returned by this method is the same value that would be
  2926      * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
  2927      * method on a {@link List} containing a sequence of {@link Integer}
  2928      * instances representing the elements of <tt>a</tt> in the same order.
  2929      * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
  2930      *
  2931      * @param a the array whose hash value to compute
  2932      * @return a content-based hash code for <tt>a</tt>
  2933      * @since 1.5
  2934      */
  2935     public static int hashCode(int a[]) {
  2936         if (a == null)
  2937             return 0;
  2938 
  2939         int result = 1;
  2940         for (int element : a)
  2941             result = 31 * result + element;
  2942 
  2943         return result;
  2944     }
  2945 
  2946     /**
  2947      * Returns a hash code based on the contents of the specified array.
  2948      * For any two <tt>short</tt> arrays <tt>a</tt> and <tt>b</tt>
  2949      * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
  2950      * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
  2951      *
  2952      * <p>The value returned by this method is the same value that would be
  2953      * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
  2954      * method on a {@link List} containing a sequence of {@link Short}
  2955      * instances representing the elements of <tt>a</tt> in the same order.
  2956      * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
  2957      *
  2958      * @param a the array whose hash value to compute
  2959      * @return a content-based hash code for <tt>a</tt>
  2960      * @since 1.5
  2961      */
  2962     public static int hashCode(short a[]) {
  2963         if (a == null)
  2964             return 0;
  2965 
  2966         int result = 1;
  2967         for (short element : a)
  2968             result = 31 * result + element;
  2969 
  2970         return result;
  2971     }
  2972 
  2973     /**
  2974      * Returns a hash code based on the contents of the specified array.
  2975      * For any two <tt>char</tt> arrays <tt>a</tt> and <tt>b</tt>
  2976      * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
  2977      * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
  2978      *
  2979      * <p>The value returned by this method is the same value that would be
  2980      * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
  2981      * method on a {@link List} containing a sequence of {@link Character}
  2982      * instances representing the elements of <tt>a</tt> in the same order.
  2983      * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
  2984      *
  2985      * @param a the array whose hash value to compute
  2986      * @return a content-based hash code for <tt>a</tt>
  2987      * @since 1.5
  2988      */
  2989     public static int hashCode(char a[]) {
  2990         if (a == null)
  2991             return 0;
  2992 
  2993         int result = 1;
  2994         for (char element : a)
  2995             result = 31 * result + element;
  2996 
  2997         return result;
  2998     }
  2999 
  3000     /**
  3001      * Returns a hash code based on the contents of the specified array.
  3002      * For any two <tt>byte</tt> arrays <tt>a</tt> and <tt>b</tt>
  3003      * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
  3004      * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
  3005      *
  3006      * <p>The value returned by this method is the same value that would be
  3007      * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
  3008      * method on a {@link List} containing a sequence of {@link Byte}
  3009      * instances representing the elements of <tt>a</tt> in the same order.
  3010      * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
  3011      *
  3012      * @param a the array whose hash value to compute
  3013      * @return a content-based hash code for <tt>a</tt>
  3014      * @since 1.5
  3015      */
  3016     public static int hashCode(byte a[]) {
  3017         if (a == null)
  3018             return 0;
  3019 
  3020         int result = 1;
  3021         for (byte element : a)
  3022             result = 31 * result + element;
  3023 
  3024         return result;
  3025     }
  3026 
  3027     /**
  3028      * Returns a hash code based on the contents of the specified array.
  3029      * For any two <tt>boolean</tt> arrays <tt>a</tt> and <tt>b</tt>
  3030      * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
  3031      * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
  3032      *
  3033      * <p>The value returned by this method is the same value that would be
  3034      * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
  3035      * method on a {@link List} containing a sequence of {@link Boolean}
  3036      * instances representing the elements of <tt>a</tt> in the same order.
  3037      * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
  3038      *
  3039      * @param a the array whose hash value to compute
  3040      * @return a content-based hash code for <tt>a</tt>
  3041      * @since 1.5
  3042      */
  3043     public static int hashCode(boolean a[]) {
  3044         if (a == null)
  3045             return 0;
  3046 
  3047         int result = 1;
  3048         for (boolean element : a)
  3049             result = 31 * result + (element ? 1231 : 1237);
  3050 
  3051         return result;
  3052     }
  3053 
  3054     /**
  3055      * Returns a hash code based on the contents of the specified array.
  3056      * For any two <tt>float</tt> arrays <tt>a</tt> and <tt>b</tt>
  3057      * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
  3058      * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
  3059      *
  3060      * <p>The value returned by this method is the same value that would be
  3061      * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
  3062      * method on a {@link List} containing a sequence of {@link Float}
  3063      * instances representing the elements of <tt>a</tt> in the same order.
  3064      * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
  3065      *
  3066      * @param a the array whose hash value to compute
  3067      * @return a content-based hash code for <tt>a</tt>
  3068      * @since 1.5
  3069      */
  3070     public static int hashCode(float a[]) {
  3071         if (a == null)
  3072             return 0;
  3073 
  3074         int result = 1;
  3075         for (float element : a)
  3076             result = 31 * result + Float.floatToIntBits(element);
  3077 
  3078         return result;
  3079     }
  3080 
  3081     /**
  3082      * Returns a hash code based on the contents of the specified array.
  3083      * For any two <tt>double</tt> arrays <tt>a</tt> and <tt>b</tt>
  3084      * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
  3085      * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
  3086      *
  3087      * <p>The value returned by this method is the same value that would be
  3088      * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
  3089      * method on a {@link List} containing a sequence of {@link Double}
  3090      * instances representing the elements of <tt>a</tt> in the same order.
  3091      * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
  3092      *
  3093      * @param a the array whose hash value to compute
  3094      * @return a content-based hash code for <tt>a</tt>
  3095      * @since 1.5
  3096      */
  3097     public static int hashCode(double a[]) {
  3098         if (a == null)
  3099             return 0;
  3100 
  3101         int result = 1;
  3102         for (double element : a) {
  3103             long bits = Double.doubleToLongBits(element);
  3104             result = 31 * result + (int)(bits ^ (bits >>> 32));
  3105         }
  3106         return result;
  3107     }
  3108 
  3109     /**
  3110      * Returns a hash code based on the contents of the specified array.  If
  3111      * the array contains other arrays as elements, the hash code is based on
  3112      * their identities rather than their contents.  It is therefore
  3113      * acceptable to invoke this method on an array that contains itself as an
  3114      * element,  either directly or indirectly through one or more levels of
  3115      * arrays.
  3116      *
  3117      * <p>For any two arrays <tt>a</tt> and <tt>b</tt> such that
  3118      * <tt>Arrays.equals(a, b)</tt>, it is also the case that
  3119      * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
  3120      *
  3121      * <p>The value returned by this method is equal to the value that would
  3122      * be returned by <tt>Arrays.asList(a).hashCode()</tt>, unless <tt>a</tt>
  3123      * is <tt>null</tt>, in which case <tt>0</tt> is returned.
  3124      *
  3125      * @param a the array whose content-based hash code to compute
  3126      * @return a content-based hash code for <tt>a</tt>
  3127      * @see #deepHashCode(Object[])
  3128      * @since 1.5
  3129      */
  3130     public static int hashCode(Object a[]) {
  3131         if (a == null)
  3132             return 0;
  3133 
  3134         int result = 1;
  3135 
  3136         for (Object element : a)
  3137             result = 31 * result + (element == null ? 0 : element.hashCode());
  3138 
  3139         return result;
  3140     }
  3141 
  3142     /**
  3143      * Returns a hash code based on the "deep contents" of the specified
  3144      * array.  If the array contains other arrays as elements, the
  3145      * hash code is based on their contents and so on, ad infinitum.
  3146      * It is therefore unacceptable to invoke this method on an array that
  3147      * contains itself as an element, either directly or indirectly through
  3148      * one or more levels of arrays.  The behavior of such an invocation is
  3149      * undefined.
  3150      *
  3151      * <p>For any two arrays <tt>a</tt> and <tt>b</tt> such that
  3152      * <tt>Arrays.deepEquals(a, b)</tt>, it is also the case that
  3153      * <tt>Arrays.deepHashCode(a) == Arrays.deepHashCode(b)</tt>.
  3154      *
  3155      * <p>The computation of the value returned by this method is similar to
  3156      * that of the value returned by {@link List#hashCode()} on a list
  3157      * containing the same elements as <tt>a</tt> in the same order, with one
  3158      * difference: If an element <tt>e</tt> of <tt>a</tt> is itself an array,
  3159      * its hash code is computed not by calling <tt>e.hashCode()</tt>, but as
  3160      * by calling the appropriate overloading of <tt>Arrays.hashCode(e)</tt>
  3161      * if <tt>e</tt> is an array of a primitive type, or as by calling
  3162      * <tt>Arrays.deepHashCode(e)</tt> recursively if <tt>e</tt> is an array
  3163      * of a reference type.  If <tt>a</tt> is <tt>null</tt>, this method
  3164      * returns 0.
  3165      *
  3166      * @param a the array whose deep-content-based hash code to compute
  3167      * @return a deep-content-based hash code for <tt>a</tt>
  3168      * @see #hashCode(Object[])
  3169      * @since 1.5
  3170      */
  3171     public static int deepHashCode(Object a[]) {
  3172         if (a == null)
  3173             return 0;
  3174 
  3175         int result = 1;
  3176 
  3177         for (Object element : a) {
  3178             int elementHash = 0;
  3179             if (element instanceof Object[])
  3180                 elementHash = deepHashCode((Object[]) element);
  3181             else if (element instanceof byte[])
  3182                 elementHash = hashCode((byte[]) element);
  3183             else if (element instanceof short[])
  3184                 elementHash = hashCode((short[]) element);
  3185             else if (element instanceof int[])
  3186                 elementHash = hashCode((int[]) element);
  3187             else if (element instanceof long[])
  3188                 elementHash = hashCode((long[]) element);
  3189             else if (element instanceof char[])
  3190                 elementHash = hashCode((char[]) element);
  3191             else if (element instanceof float[])
  3192                 elementHash = hashCode((float[]) element);
  3193             else if (element instanceof double[])
  3194                 elementHash = hashCode((double[]) element);
  3195             else if (element instanceof boolean[])
  3196                 elementHash = hashCode((boolean[]) element);
  3197             else if (element != null)
  3198                 elementHash = element.hashCode();
  3199 
  3200             result = 31 * result + elementHash;
  3201         }
  3202 
  3203         return result;
  3204     }
  3205 
  3206     /**
  3207      * Returns <tt>true</tt> if the two specified arrays are <i>deeply
  3208      * equal</i> to one another.  Unlike the {@link #equals(Object[],Object[])}
  3209      * method, this method is appropriate for use with nested arrays of
  3210      * arbitrary depth.
  3211      *
  3212      * <p>Two array references are considered deeply equal if both
  3213      * are <tt>null</tt>, or if they refer to arrays that contain the same
  3214      * number of elements and all corresponding pairs of elements in the two
  3215      * arrays are deeply equal.
  3216      *
  3217      * <p>Two possibly <tt>null</tt> elements <tt>e1</tt> and <tt>e2</tt> are
  3218      * deeply equal if any of the following conditions hold:
  3219      * <ul>
  3220      *    <li> <tt>e1</tt> and <tt>e2</tt> are both arrays of object reference
  3221      *         types, and <tt>Arrays.deepEquals(e1, e2) would return true</tt>
  3222      *    <li> <tt>e1</tt> and <tt>e2</tt> are arrays of the same primitive
  3223      *         type, and the appropriate overloading of
  3224      *         <tt>Arrays.equals(e1, e2)</tt> would return true.
  3225      *    <li> <tt>e1 == e2</tt>
  3226      *    <li> <tt>e1.equals(e2)</tt> would return true.
  3227      * </ul>
  3228      * Note that this definition permits <tt>null</tt> elements at any depth.
  3229      *
  3230      * <p>If either of the specified arrays contain themselves as elements
  3231      * either directly or indirectly through one or more levels of arrays,
  3232      * the behavior of this method is undefined.
  3233      *
  3234      * @param a1 one array to be tested for equality
  3235      * @param a2 the other array to be tested for equality
  3236      * @return <tt>true</tt> if the two arrays are equal
  3237      * @see #equals(Object[],Object[])
  3238      * @see Objects#deepEquals(Object, Object)
  3239      * @since 1.5
  3240      */
  3241     public static boolean deepEquals(Object[] a1, Object[] a2) {
  3242         if (a1 == a2)
  3243             return true;
  3244         if (a1 == null || a2==null)
  3245             return false;
  3246         int length = a1.length;
  3247         if (a2.length != length)
  3248             return false;
  3249 
  3250         for (int i = 0; i < length; i++) {
  3251             Object e1 = a1[i];
  3252             Object e2 = a2[i];
  3253 
  3254             if (e1 == e2)
  3255                 continue;
  3256             if (e1 == null)
  3257                 return false;
  3258 
  3259             // Figure out whether the two elements are equal
  3260             boolean eq = deepEquals0(e1, e2);
  3261 
  3262             if (!eq)
  3263                 return false;
  3264         }
  3265         return true;
  3266     }
  3267 
  3268     static boolean deepEquals0(Object e1, Object e2) {
  3269         assert e1 != null;
  3270         boolean eq;
  3271         if (e1 instanceof Object[] && e2 instanceof Object[])
  3272             eq = deepEquals ((Object[]) e1, (Object[]) e2);
  3273         else if (e1 instanceof byte[] && e2 instanceof byte[])
  3274             eq = equals((byte[]) e1, (byte[]) e2);
  3275         else if (e1 instanceof short[] && e2 instanceof short[])
  3276             eq = equals((short[]) e1, (short[]) e2);
  3277         else if (e1 instanceof int[] && e2 instanceof int[])
  3278             eq = equals((int[]) e1, (int[]) e2);
  3279         else if (e1 instanceof long[] && e2 instanceof long[])
  3280             eq = equals((long[]) e1, (long[]) e2);
  3281         else if (e1 instanceof char[] && e2 instanceof char[])
  3282             eq = equals((char[]) e1, (char[]) e2);
  3283         else if (e1 instanceof float[] && e2 instanceof float[])
  3284             eq = equals((float[]) e1, (float[]) e2);
  3285         else if (e1 instanceof double[] && e2 instanceof double[])
  3286             eq = equals((double[]) e1, (double[]) e2);
  3287         else if (e1 instanceof boolean[] && e2 instanceof boolean[])
  3288             eq = equals((boolean[]) e1, (boolean[]) e2);
  3289         else
  3290             eq = e1.equals(e2);
  3291         return eq;
  3292     }
  3293 
  3294     /**
  3295      * Returns a string representation of the contents of the specified array.
  3296      * The string representation consists of a list of the array's elements,
  3297      * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are
  3298      * separated by the characters <tt>", "</tt> (a comma followed by a
  3299      * space).  Elements are converted to strings as by
  3300      * <tt>String.valueOf(long)</tt>.  Returns <tt>"null"</tt> if <tt>a</tt>
  3301      * is <tt>null</tt>.
  3302      *
  3303      * @param a the array whose string representation to return
  3304      * @return a string representation of <tt>a</tt>
  3305      * @since 1.5
  3306      */
  3307     public static String toString(long[] a) {
  3308         if (a == null)
  3309             return "null";
  3310         int iMax = a.length - 1;
  3311         if (iMax == -1)
  3312             return "[]";
  3313 
  3314         StringBuilder b = new StringBuilder();
  3315         b.append('[');
  3316         for (int i = 0; ; i++) {
  3317             b.append(a[i]);
  3318             if (i == iMax)
  3319                 return b.append(']').toString();
  3320             b.append(", ");
  3321         }
  3322     }
  3323 
  3324     /**
  3325      * Returns a string representation of the contents of the specified array.
  3326      * The string representation consists of a list of the array's elements,
  3327      * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are
  3328      * separated by the characters <tt>", "</tt> (a comma followed by a
  3329      * space).  Elements are converted to strings as by
  3330      * <tt>String.valueOf(int)</tt>.  Returns <tt>"null"</tt> if <tt>a</tt> is
  3331      * <tt>null</tt>.
  3332      *
  3333      * @param a the array whose string representation to return
  3334      * @return a string representation of <tt>a</tt>
  3335      * @since 1.5
  3336      */
  3337     public static String toString(int[] a) {
  3338         if (a == null)
  3339             return "null";
  3340         int iMax = a.length - 1;
  3341         if (iMax == -1)
  3342             return "[]";
  3343 
  3344         StringBuilder b = new StringBuilder();
  3345         b.append('[');
  3346         for (int i = 0; ; i++) {
  3347             b.append(a[i]);
  3348             if (i == iMax)
  3349                 return b.append(']').toString();
  3350             b.append(", ");
  3351         }
  3352     }
  3353 
  3354     /**
  3355      * Returns a string representation of the contents of the specified array.
  3356      * The string representation consists of a list of the array's elements,
  3357      * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are
  3358      * separated by the characters <tt>", "</tt> (a comma followed by a
  3359      * space).  Elements are converted to strings as by
  3360      * <tt>String.valueOf(short)</tt>.  Returns <tt>"null"</tt> if <tt>a</tt>
  3361      * is <tt>null</tt>.
  3362      *
  3363      * @param a the array whose string representation to return
  3364      * @return a string representation of <tt>a</tt>
  3365      * @since 1.5
  3366      */
  3367     public static String toString(short[] a) {
  3368         if (a == null)
  3369             return "null";
  3370         int iMax = a.length - 1;
  3371         if (iMax == -1)
  3372             return "[]";
  3373 
  3374         StringBuilder b = new StringBuilder();
  3375         b.append('[');
  3376         for (int i = 0; ; i++) {
  3377             b.append(a[i]);
  3378             if (i == iMax)
  3379                 return b.append(']').toString();
  3380             b.append(", ");
  3381         }
  3382     }
  3383 
  3384     /**
  3385      * Returns a string representation of the contents of the specified array.
  3386      * The string representation consists of a list of the array's elements,
  3387      * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are
  3388      * separated by the characters <tt>", "</tt> (a comma followed by a
  3389      * space).  Elements are converted to strings as by
  3390      * <tt>String.valueOf(char)</tt>.  Returns <tt>"null"</tt> if <tt>a</tt>
  3391      * is <tt>null</tt>.
  3392      *
  3393      * @param a the array whose string representation to return
  3394      * @return a string representation of <tt>a</tt>
  3395      * @since 1.5
  3396      */
  3397     public static String toString(char[] a) {
  3398         if (a == null)
  3399             return "null";
  3400         int iMax = a.length - 1;
  3401         if (iMax == -1)
  3402             return "[]";
  3403 
  3404         StringBuilder b = new StringBuilder();
  3405         b.append('[');
  3406         for (int i = 0; ; i++) {
  3407             b.append(a[i]);
  3408             if (i == iMax)
  3409                 return b.append(']').toString();
  3410             b.append(", ");
  3411         }
  3412     }
  3413 
  3414     /**
  3415      * Returns a string representation of the contents of the specified array.
  3416      * The string representation consists of a list of the array's elements,
  3417      * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements
  3418      * are separated by the characters <tt>", "</tt> (a comma followed
  3419      * by a space).  Elements are converted to strings as by
  3420      * <tt>String.valueOf(byte)</tt>.  Returns <tt>"null"</tt> if
  3421      * <tt>a</tt> is <tt>null</tt>.
  3422      *
  3423      * @param a the array whose string representation to return
  3424      * @return a string representation of <tt>a</tt>
  3425      * @since 1.5
  3426      */
  3427     public static String toString(byte[] a) {
  3428         if (a == null)
  3429             return "null";
  3430         int iMax = a.length - 1;
  3431         if (iMax == -1)
  3432             return "[]";
  3433 
  3434         StringBuilder b = new StringBuilder();
  3435         b.append('[');
  3436         for (int i = 0; ; i++) {
  3437             b.append(a[i]);
  3438             if (i == iMax)
  3439                 return b.append(']').toString();
  3440             b.append(", ");
  3441         }
  3442     }
  3443 
  3444     /**
  3445      * Returns a string representation of the contents of the specified array.
  3446      * The string representation consists of a list of the array's elements,
  3447      * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are
  3448      * separated by the characters <tt>", "</tt> (a comma followed by a
  3449      * space).  Elements are converted to strings as by
  3450      * <tt>String.valueOf(boolean)</tt>.  Returns <tt>"null"</tt> if
  3451      * <tt>a</tt> is <tt>null</tt>.
  3452      *
  3453      * @param a the array whose string representation to return
  3454      * @return a string representation of <tt>a</tt>
  3455      * @since 1.5
  3456      */
  3457     public static String toString(boolean[] a) {
  3458         if (a == null)
  3459             return "null";
  3460         int iMax = a.length - 1;
  3461         if (iMax == -1)
  3462             return "[]";
  3463 
  3464         StringBuilder b = new StringBuilder();
  3465         b.append('[');
  3466         for (int i = 0; ; i++) {
  3467             b.append(a[i]);
  3468             if (i == iMax)
  3469                 return b.append(']').toString();
  3470             b.append(", ");
  3471         }
  3472     }
  3473 
  3474     /**
  3475      * Returns a string representation of the contents of the specified array.
  3476      * The string representation consists of a list of the array's elements,
  3477      * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are
  3478      * separated by the characters <tt>", "</tt> (a comma followed by a
  3479      * space).  Elements are converted to strings as by
  3480      * <tt>String.valueOf(float)</tt>.  Returns <tt>"null"</tt> if <tt>a</tt>
  3481      * is <tt>null</tt>.
  3482      *
  3483      * @param a the array whose string representation to return
  3484      * @return a string representation of <tt>a</tt>
  3485      * @since 1.5
  3486      */
  3487     public static String toString(float[] a) {
  3488         if (a == null)
  3489             return "null";
  3490 
  3491         int iMax = a.length - 1;
  3492         if (iMax == -1)
  3493             return "[]";
  3494 
  3495         StringBuilder b = new StringBuilder();
  3496         b.append('[');
  3497         for (int i = 0; ; i++) {
  3498             b.append(a[i]);
  3499             if (i == iMax)
  3500                 return b.append(']').toString();
  3501             b.append(", ");
  3502         }
  3503     }
  3504 
  3505     /**
  3506      * Returns a string representation of the contents of the specified array.
  3507      * The string representation consists of a list of the array's elements,
  3508      * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are
  3509      * separated by the characters <tt>", "</tt> (a comma followed by a
  3510      * space).  Elements are converted to strings as by
  3511      * <tt>String.valueOf(double)</tt>.  Returns <tt>"null"</tt> if <tt>a</tt>
  3512      * is <tt>null</tt>.
  3513      *
  3514      * @param a the array whose string representation to return
  3515      * @return a string representation of <tt>a</tt>
  3516      * @since 1.5
  3517      */
  3518     public static String toString(double[] a) {
  3519         if (a == null)
  3520             return "null";
  3521         int iMax = a.length - 1;
  3522         if (iMax == -1)
  3523             return "[]";
  3524 
  3525         StringBuilder b = new StringBuilder();
  3526         b.append('[');
  3527         for (int i = 0; ; i++) {
  3528             b.append(a[i]);
  3529             if (i == iMax)
  3530                 return b.append(']').toString();
  3531             b.append(", ");
  3532         }
  3533     }
  3534 
  3535     /**
  3536      * Returns a string representation of the contents of the specified array.
  3537      * If the array contains other arrays as elements, they are converted to
  3538      * strings by the {@link Object#toString} method inherited from
  3539      * <tt>Object</tt>, which describes their <i>identities</i> rather than
  3540      * their contents.
  3541      *
  3542      * <p>The value returned by this method is equal to the value that would
  3543      * be returned by <tt>Arrays.asList(a).toString()</tt>, unless <tt>a</tt>
  3544      * is <tt>null</tt>, in which case <tt>"null"</tt> is returned.
  3545      *
  3546      * @param a the array whose string representation to return
  3547      * @return a string representation of <tt>a</tt>
  3548      * @see #deepToString(Object[])
  3549      * @since 1.5
  3550      */
  3551     public static String toString(Object[] a) {
  3552         if (a == null)
  3553             return "null";
  3554 
  3555         int iMax = a.length - 1;
  3556         if (iMax == -1)
  3557             return "[]";
  3558 
  3559         StringBuilder b = new StringBuilder();
  3560         b.append('[');
  3561         for (int i = 0; ; i++) {
  3562             b.append(String.valueOf(a[i]));
  3563             if (i == iMax)
  3564                 return b.append(']').toString();
  3565             b.append(", ");
  3566         }
  3567     }
  3568 
  3569     /**
  3570      * Returns a string representation of the "deep contents" of the specified
  3571      * array.  If the array contains other arrays as elements, the string
  3572      * representation contains their contents and so on.  This method is
  3573      * designed for converting multidimensional arrays to strings.
  3574      *
  3575      * <p>The string representation consists of a list of the array's
  3576      * elements, enclosed in square brackets (<tt>"[]"</tt>).  Adjacent
  3577      * elements are separated by the characters <tt>", "</tt> (a comma
  3578      * followed by a space).  Elements are converted to strings as by
  3579      * <tt>String.valueOf(Object)</tt>, unless they are themselves
  3580      * arrays.
  3581      *
  3582      * <p>If an element <tt>e</tt> is an array of a primitive type, it is
  3583      * converted to a string as by invoking the appropriate overloading of
  3584      * <tt>Arrays.toString(e)</tt>.  If an element <tt>e</tt> is an array of a
  3585      * reference type, it is converted to a string as by invoking
  3586      * this method recursively.
  3587      *
  3588      * <p>To avoid infinite recursion, if the specified array contains itself
  3589      * as an element, or contains an indirect reference to itself through one
  3590      * or more levels of arrays, the self-reference is converted to the string
  3591      * <tt>"[...]"</tt>.  For example, an array containing only a reference
  3592      * to itself would be rendered as <tt>"[[...]]"</tt>.
  3593      *
  3594      * <p>This method returns <tt>"null"</tt> if the specified array
  3595      * is <tt>null</tt>.
  3596      *
  3597      * @param a the array whose string representation to return
  3598      * @return a string representation of <tt>a</tt>
  3599      * @see #toString(Object[])
  3600      * @since 1.5
  3601      */
  3602     public static String deepToString(Object[] a) {
  3603         if (a == null)
  3604             return "null";
  3605 
  3606         int bufLen = 20 * a.length;
  3607         if (a.length != 0 && bufLen <= 0)
  3608             bufLen = Integer.MAX_VALUE;
  3609         StringBuilder buf = new StringBuilder(bufLen);
  3610         deepToString(a, buf, new HashSet<Object[]>());
  3611         return buf.toString();
  3612     }
  3613 
  3614     private static void deepToString(Object[] a, StringBuilder buf,
  3615                                      Set<Object[]> dejaVu) {
  3616         if (a == null) {
  3617             buf.append("null");
  3618             return;
  3619         }
  3620         int iMax = a.length - 1;
  3621         if (iMax == -1) {
  3622             buf.append("[]");
  3623             return;
  3624         }
  3625 
  3626         dejaVu.add(a);
  3627         buf.append('[');
  3628         for (int i = 0; ; i++) {
  3629 
  3630             Object element = a[i];
  3631             if (element == null) {
  3632                 buf.append("null");
  3633             } else {
  3634                 Class eClass = element.getClass();
  3635 
  3636                 if (eClass.isArray()) {
  3637                     if (eClass == byte[].class)
  3638                         buf.append(toString((byte[]) element));
  3639                     else if (eClass == short[].class)
  3640                         buf.append(toString((short[]) element));
  3641                     else if (eClass == int[].class)
  3642                         buf.append(toString((int[]) element));
  3643                     else if (eClass == long[].class)
  3644                         buf.append(toString((long[]) element));
  3645                     else if (eClass == char[].class)
  3646                         buf.append(toString((char[]) element));
  3647                     else if (eClass == float[].class)
  3648                         buf.append(toString((float[]) element));
  3649                     else if (eClass == double[].class)
  3650                         buf.append(toString((double[]) element));
  3651                     else if (eClass == boolean[].class)
  3652                         buf.append(toString((boolean[]) element));
  3653                     else { // element is an array of object references
  3654                         if (dejaVu.contains(element))
  3655                             buf.append("[...]");
  3656                         else
  3657                             deepToString((Object[])element, buf, dejaVu);
  3658                     }
  3659                 } else {  // element is non-null and not an array
  3660                     buf.append(element.toString());
  3661                 }
  3662             }
  3663             if (i == iMax)
  3664                 break;
  3665             buf.append(", ");
  3666         }
  3667         buf.append(']');
  3668         dejaVu.remove(a);
  3669     }
  3670 }