Arrays.java revision 9eca269fb2932fb9fd99b6e898600e7a21ade0e0
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.  Oracle designates this
9 * particular file as subject to the "Classpath" exception as provided
10 * by Oracle in the LICENSE file that accompanied this code.
11 *
12 * This code is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 * version 2 for more details (a copy is included in the LICENSE file that
16 * accompanied this code).
17 *
18 * You should have received a copy of the GNU General Public License version
19 * 2 along with this work; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23 * or visit www.oracle.com if you need additional information or have any
24 * questions.
25 */
26
27package java.util;
28
29import java.lang.reflect.Array;
30import java.util.concurrent.ForkJoinPool;
31import java.util.function.BinaryOperator;
32import java.util.function.Consumer;
33import java.util.function.DoubleBinaryOperator;
34import java.util.function.IntBinaryOperator;
35import java.util.function.IntFunction;
36import java.util.function.IntToDoubleFunction;
37import java.util.function.IntToLongFunction;
38import java.util.function.IntUnaryOperator;
39import java.util.function.LongBinaryOperator;
40import java.util.function.UnaryOperator;
41import java.util.stream.DoubleStream;
42import java.util.stream.IntStream;
43import java.util.stream.LongStream;
44import java.util.stream.Stream;
45import java.util.stream.StreamSupport;
46
47/**
48 * This class contains various methods for manipulating arrays (such as
49 * sorting and searching). This class also contains a static factory
50 * that allows arrays to be viewed as lists.
51 *
52 * <p>The methods in this class all throw a {@code NullPointerException},
53 * if the specified array reference is null, except where noted.
54 *
55 * <p>The documentation for the methods contained in this class includes
56 * briefs description of the <i>implementations</i>. Such descriptions should
57 * be regarded as <i>implementation notes</i>, rather than parts of the
58 * <i>specification</i>. Implementors should feel free to substitute other
59 * algorithms, so long as the specification itself is adhered to. (For
60 * example, the algorithm used by {@code sort(Object[])} does not have to be
61 * a MergeSort, but it does have to be <i>stable</i>.)
62 *
63 * <p>This class is a member of the
64 * <a href="{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/collections/index.html">
65 * Java Collections Framework</a>.
66 *
67 * @author Josh Bloch
68 * @author Neal Gafter
69 * @author John Rose
70 * @since  1.2
71 */
72public class Arrays {
73
74    /**
75     * The minimum array length below which a parallel sorting
76     * algorithm will not further partition the sorting task. Using
77     * smaller sizes typically results in memory contention across
78     * tasks that makes parallel speedups unlikely.
79     * @hide
80     */
81    // Android-changed: make public (used by harmony ArraysTest)
82    public static final int MIN_ARRAY_SORT_GRAN = 1 << 13;
83
84    // Suppresses default constructor, ensuring non-instantiability.
85    private Arrays() {}
86
87    /**
88     * A comparator that implements the natural ordering of a group of
89     * mutually comparable elements. May be used when a supplied
90     * comparator is null. To simplify code-sharing within underlying
91     * implementations, the compare method only declares type Object
92     * for its second argument.
93     *
94     * Arrays class implementor's note: It is an empirical matter
95     * whether ComparableTimSort offers any performance benefit over
96     * TimSort used with this comparator.  If not, you are better off
97     * deleting or bypassing ComparableTimSort.  There is currently no
98     * empirical case for separating them for parallel sorting, so all
99     * public Object parallelSort methods use the same comparator
100     * based implementation.
101     */
102    static final class NaturalOrder implements Comparator<Object> {
103        @SuppressWarnings("unchecked")
104        public int compare(Object first, Object second) {
105            return ((Comparable<Object>)first).compareTo(second);
106        }
107        static final NaturalOrder INSTANCE = new NaturalOrder();
108    }
109
110    /**
111     * Checks that {@code fromIndex} and {@code toIndex} are in
112     * the range and throws an exception if they aren't.
113     */
114    private static void rangeCheck(int arrayLength, int fromIndex, int toIndex) {
115        if (fromIndex > toIndex) {
116            throw new IllegalArgumentException(
117                    "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
118        }
119        if (fromIndex < 0) {
120            throw new ArrayIndexOutOfBoundsException(fromIndex);
121        }
122        if (toIndex > arrayLength) {
123            throw new ArrayIndexOutOfBoundsException(toIndex);
124        }
125    }
126
127    // BEGIN Android-added: checkOffsetAndCount() helper method for AIOOBE enforcement.
128    /**
129     * Checks that the range described by {@code offset} and {@code count} doesn't exceed
130     * {@code arrayLength}.
131     * @hide
132     */
133    public static void checkOffsetAndCount(int arrayLength, int offset, int count) {
134        if ((offset | count) < 0 || offset > arrayLength || arrayLength - offset < count) {
135            throw new ArrayIndexOutOfBoundsException(arrayLength, offset,
136                    count);
137        }
138    }
139    // END Android-added: checkOffsetAndCount() helper method for AIOOBE enforcement.
140
141    /*
142     * Sorting methods. Note that all public "sort" methods take the
143     * same form: Performing argument checks if necessary, and then
144     * expanding arguments into those required for the internal
145     * implementation methods residing in other package-private
146     * classes (except for legacyMergeSort, included in this class).
147     */
148
149    /**
150     * Sorts the specified array into ascending numerical order.
151     *
152     * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
153     * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
154     * offers O(n log(n)) performance on many data sets that cause other
155     * quicksorts to degrade to quadratic performance, and is typically
156     * faster than traditional (one-pivot) Quicksort implementations.
157     *
158     * @param a the array to be sorted
159     */
160    public static void sort(int[] a) {
161        DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
162    }
163
164    /**
165     * Sorts the specified range of the array into ascending order. The range
166     * to be sorted extends from the index {@code fromIndex}, inclusive, to
167     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
168     * the range to be sorted is empty.
169     *
170     * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
171     * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
172     * offers O(n log(n)) performance on many data sets that cause other
173     * quicksorts to degrade to quadratic performance, and is typically
174     * faster than traditional (one-pivot) Quicksort implementations.
175     *
176     * @param a the array to be sorted
177     * @param fromIndex the index of the first element, inclusive, to be sorted
178     * @param toIndex the index of the last element, exclusive, to be sorted
179     *
180     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
181     * @throws ArrayIndexOutOfBoundsException
182     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
183     */
184    public static void sort(int[] a, int fromIndex, int toIndex) {
185        rangeCheck(a.length, fromIndex, toIndex);
186        DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);
187    }
188
189    /**
190     * Sorts the specified array into ascending numerical order.
191     *
192     * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
193     * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
194     * offers O(n log(n)) performance on many data sets that cause other
195     * quicksorts to degrade to quadratic performance, and is typically
196     * faster than traditional (one-pivot) Quicksort implementations.
197     *
198     * @param a the array to be sorted
199     */
200    public static void sort(long[] a) {
201        DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
202    }
203
204    /**
205     * Sorts the specified range of the array into ascending order. The range
206     * to be sorted extends from the index {@code fromIndex}, inclusive, to
207     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
208     * the range to be sorted is empty.
209     *
210     * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
211     * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
212     * offers O(n log(n)) performance on many data sets that cause other
213     * quicksorts to degrade to quadratic performance, and is typically
214     * faster than traditional (one-pivot) Quicksort implementations.
215     *
216     * @param a the array to be sorted
217     * @param fromIndex the index of the first element, inclusive, to be sorted
218     * @param toIndex the index of the last element, exclusive, to be sorted
219     *
220     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
221     * @throws ArrayIndexOutOfBoundsException
222     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
223     */
224    public static void sort(long[] a, int fromIndex, int toIndex) {
225        rangeCheck(a.length, fromIndex, toIndex);
226        DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);
227    }
228
229    /**
230     * Sorts the specified array into ascending numerical order.
231     *
232     * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
233     * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
234     * offers O(n log(n)) performance on many data sets that cause other
235     * quicksorts to degrade to quadratic performance, and is typically
236     * faster than traditional (one-pivot) Quicksort implementations.
237     *
238     * @param a the array to be sorted
239     */
240    public static void sort(short[] a) {
241        DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
242    }
243
244    /**
245     * Sorts the specified range of the array into ascending order. The range
246     * to be sorted extends from the index {@code fromIndex}, inclusive, to
247     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
248     * the range to be sorted is empty.
249     *
250     * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
251     * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
252     * offers O(n log(n)) performance on many data sets that cause other
253     * quicksorts to degrade to quadratic performance, and is typically
254     * faster than traditional (one-pivot) Quicksort implementations.
255     *
256     * @param a the array to be sorted
257     * @param fromIndex the index of the first element, inclusive, to be sorted
258     * @param toIndex the index of the last element, exclusive, to be sorted
259     *
260     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
261     * @throws ArrayIndexOutOfBoundsException
262     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
263     */
264    public static void sort(short[] a, int fromIndex, int toIndex) {
265        rangeCheck(a.length, fromIndex, toIndex);
266        DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);
267    }
268
269    /**
270     * Sorts the specified array into ascending numerical order.
271     *
272     * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
273     * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
274     * offers O(n log(n)) performance on many data sets that cause other
275     * quicksorts to degrade to quadratic performance, and is typically
276     * faster than traditional (one-pivot) Quicksort implementations.
277     *
278     * @param a the array to be sorted
279     */
280    public static void sort(char[] a) {
281        DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
282    }
283
284    /**
285     * Sorts the specified range of the array into ascending order. The range
286     * to be sorted extends from the index {@code fromIndex}, inclusive, to
287     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
288     * the range to be sorted is empty.
289     *
290     * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
291     * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
292     * offers O(n log(n)) performance on many data sets that cause other
293     * quicksorts to degrade to quadratic performance, and is typically
294     * faster than traditional (one-pivot) Quicksort implementations.
295     *
296     * @param a the array to be sorted
297     * @param fromIndex the index of the first element, inclusive, to be sorted
298     * @param toIndex the index of the last element, exclusive, to be sorted
299     *
300     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
301     * @throws ArrayIndexOutOfBoundsException
302     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
303     */
304    public static void sort(char[] a, int fromIndex, int toIndex) {
305        rangeCheck(a.length, fromIndex, toIndex);
306        DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);
307    }
308
309    /**
310     * Sorts the specified array into ascending numerical order.
311     *
312     * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
313     * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
314     * offers O(n log(n)) performance on many data sets that cause other
315     * quicksorts to degrade to quadratic performance, and is typically
316     * faster than traditional (one-pivot) Quicksort implementations.
317     *
318     * @param a the array to be sorted
319     */
320    public static void sort(byte[] a) {
321        DualPivotQuicksort.sort(a, 0, a.length - 1);
322    }
323
324    /**
325     * Sorts the specified range of the array into ascending order. The range
326     * to be sorted extends from the index {@code fromIndex}, inclusive, to
327     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
328     * the range to be sorted is empty.
329     *
330     * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
331     * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
332     * offers O(n log(n)) performance on many data sets that cause other
333     * quicksorts to degrade to quadratic performance, and is typically
334     * faster than traditional (one-pivot) Quicksort implementations.
335     *
336     * @param a the array to be sorted
337     * @param fromIndex the index of the first element, inclusive, to be sorted
338     * @param toIndex the index of the last element, exclusive, to be sorted
339     *
340     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
341     * @throws ArrayIndexOutOfBoundsException
342     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
343     */
344    public static void sort(byte[] a, int fromIndex, int toIndex) {
345        rangeCheck(a.length, fromIndex, toIndex);
346        DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
347    }
348
349    /**
350     * Sorts the specified array into ascending numerical order.
351     *
352     * <p>The {@code <} relation does not provide a total order on all float
353     * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
354     * value compares neither less than, greater than, nor equal to any value,
355     * even itself. This method uses the total order imposed by the method
356     * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
357     * {@code 0.0f} and {@code Float.NaN} is considered greater than any
358     * other value and all {@code Float.NaN} values are considered equal.
359     *
360     * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
361     * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
362     * offers O(n log(n)) performance on many data sets that cause other
363     * quicksorts to degrade to quadratic performance, and is typically
364     * faster than traditional (one-pivot) Quicksort implementations.
365     *
366     * @param a the array to be sorted
367     */
368    public static void sort(float[] a) {
369        DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
370    }
371
372    /**
373     * Sorts the specified range of the array into ascending order. The range
374     * to be sorted extends from the index {@code fromIndex}, inclusive, to
375     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
376     * the range to be sorted is empty.
377     *
378     * <p>The {@code <} relation does not provide a total order on all float
379     * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
380     * value compares neither less than, greater than, nor equal to any value,
381     * even itself. This method uses the total order imposed by the method
382     * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
383     * {@code 0.0f} and {@code Float.NaN} is considered greater than any
384     * other value and all {@code Float.NaN} values are considered equal.
385     *
386     * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
387     * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
388     * offers O(n log(n)) performance on many data sets that cause other
389     * quicksorts to degrade to quadratic performance, and is typically
390     * faster than traditional (one-pivot) Quicksort implementations.
391     *
392     * @param a the array to be sorted
393     * @param fromIndex the index of the first element, inclusive, to be sorted
394     * @param toIndex the index of the last element, exclusive, to be sorted
395     *
396     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
397     * @throws ArrayIndexOutOfBoundsException
398     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
399     */
400    public static void sort(float[] a, int fromIndex, int toIndex) {
401        rangeCheck(a.length, fromIndex, toIndex);
402        DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);
403    }
404
405    /**
406     * Sorts the specified array into ascending numerical order.
407     *
408     * <p>The {@code <} relation does not provide a total order on all double
409     * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
410     * value compares neither less than, greater than, nor equal to any value,
411     * even itself. This method uses the total order imposed by the method
412     * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
413     * {@code 0.0d} and {@code Double.NaN} is considered greater than any
414     * other value and all {@code Double.NaN} values are considered equal.
415     *
416     * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
417     * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
418     * offers O(n log(n)) performance on many data sets that cause other
419     * quicksorts to degrade to quadratic performance, and is typically
420     * faster than traditional (one-pivot) Quicksort implementations.
421     *
422     * @param a the array to be sorted
423     */
424    public static void sort(double[] a) {
425        DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
426    }
427
428    /**
429     * Sorts the specified range of the array into ascending order. The range
430     * to be sorted extends from the index {@code fromIndex}, inclusive, to
431     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
432     * the range to be sorted is empty.
433     *
434     * <p>The {@code <} relation does not provide a total order on all double
435     * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
436     * value compares neither less than, greater than, nor equal to any value,
437     * even itself. This method uses the total order imposed by the method
438     * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
439     * {@code 0.0d} and {@code Double.NaN} is considered greater than any
440     * other value and all {@code Double.NaN} values are considered equal.
441     *
442     * <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
443     * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
444     * offers O(n log(n)) performance on many data sets that cause other
445     * quicksorts to degrade to quadratic performance, and is typically
446     * faster than traditional (one-pivot) Quicksort implementations.
447     *
448     * @param a the array to be sorted
449     * @param fromIndex the index of the first element, inclusive, to be sorted
450     * @param toIndex the index of the last element, exclusive, to be sorted
451     *
452     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
453     * @throws ArrayIndexOutOfBoundsException
454     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
455     */
456    public static void sort(double[] a, int fromIndex, int toIndex) {
457        rangeCheck(a.length, fromIndex, toIndex);
458        DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);
459    }
460
461    /**
462     * Sorts the specified array into ascending numerical order.
463     *
464     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
465     * array into sub-arrays that are themselves sorted and then merged. When
466     * the sub-array length reaches a minimum granularity, the sub-array is
467     * sorted using the appropriate {@link Arrays#sort(byte[]) Arrays.sort}
468     * method. If the length of the specified array is less than the minimum
469     * granularity, then it is sorted using the appropriate {@link
470     * Arrays#sort(byte[]) Arrays.sort} method. The algorithm requires a
471     * working space no greater than the size of the original array. The
472     * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to
473     * execute any parallel tasks.
474     *
475     * @param a the array to be sorted
476     *
477     * @since 1.8
478     */
479    public static void parallelSort(byte[] a) {
480        int n = a.length, p, g;
481        if (n <= MIN_ARRAY_SORT_GRAN ||
482            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
483            DualPivotQuicksort.sort(a, 0, n - 1);
484        else
485            new ArraysParallelSortHelpers.FJByte.Sorter
486                (null, a, new byte[n], 0, n, 0,
487                 ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
488                 MIN_ARRAY_SORT_GRAN : g).invoke();
489    }
490
491    /**
492     * Sorts the specified range of the array into ascending numerical order.
493     * The range to be sorted extends from the index {@code fromIndex},
494     * inclusive, to the index {@code toIndex}, exclusive. If
495     * {@code fromIndex == toIndex}, the range to be sorted is empty.
496     *
497     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
498     * array into sub-arrays that are themselves sorted and then merged. When
499     * the sub-array length reaches a minimum granularity, the sub-array is
500     * sorted using the appropriate {@link Arrays#sort(byte[]) Arrays.sort}
501     * method. If the length of the specified array is less than the minimum
502     * granularity, then it is sorted using the appropriate {@link
503     * Arrays#sort(byte[]) Arrays.sort} method. The algorithm requires a working
504     * space no greater than the size of the specified range of the original
505     * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is
506     * used to execute any parallel tasks.
507     *
508     * @param a the array to be sorted
509     * @param fromIndex the index of the first element, inclusive, to be sorted
510     * @param toIndex the index of the last element, exclusive, to be sorted
511     *
512     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
513     * @throws ArrayIndexOutOfBoundsException
514     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
515     *
516     * @since 1.8
517     */
518    public static void parallelSort(byte[] a, int fromIndex, int toIndex) {
519        rangeCheck(a.length, fromIndex, toIndex);
520        int n = toIndex - fromIndex, p, g;
521        if (n <= MIN_ARRAY_SORT_GRAN ||
522            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
523            DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);
524        else
525            new ArraysParallelSortHelpers.FJByte.Sorter
526                (null, a, new byte[n], fromIndex, n, 0,
527                 ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
528                 MIN_ARRAY_SORT_GRAN : g).invoke();
529    }
530
531    /**
532     * Sorts the specified array into ascending numerical order.
533     *
534     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
535     * array into sub-arrays that are themselves sorted and then merged. When
536     * the sub-array length reaches a minimum granularity, the sub-array is
537     * sorted using the appropriate {@link Arrays#sort(char[]) Arrays.sort}
538     * method. If the length of the specified array is less than the minimum
539     * granularity, then it is sorted using the appropriate {@link
540     * Arrays#sort(char[]) Arrays.sort} method. The algorithm requires a
541     * working space no greater than the size of the original array. The
542     * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to
543     * execute any parallel tasks.
544     *
545     * @param a the array to be sorted
546     *
547     * @since 1.8
548     */
549    public static void parallelSort(char[] a) {
550        int n = a.length, p, g;
551        if (n <= MIN_ARRAY_SORT_GRAN ||
552            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
553            DualPivotQuicksort.sort(a, 0, n - 1, null, 0, 0);
554        else
555            new ArraysParallelSortHelpers.FJChar.Sorter
556                (null, a, new char[n], 0, n, 0,
557                 ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
558                 MIN_ARRAY_SORT_GRAN : g).invoke();
559    }
560
561    /**
562     * Sorts the specified range of the array into ascending numerical order.
563     * The range to be sorted extends from the index {@code fromIndex},
564     * inclusive, to the index {@code toIndex}, exclusive. If
565     * {@code fromIndex == toIndex}, the range to be sorted is empty.
566     *
567      @implNote The sorting algorithm is a parallel sort-merge that breaks the
568     * array into sub-arrays that are themselves sorted and then merged. When
569     * the sub-array length reaches a minimum granularity, the sub-array is
570     * sorted using the appropriate {@link Arrays#sort(char[]) Arrays.sort}
571     * method. If the length of the specified array is less than the minimum
572     * granularity, then it is sorted using the appropriate {@link
573     * Arrays#sort(char[]) Arrays.sort} method. The algorithm requires a working
574     * space no greater than the size of the specified range of the original
575     * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is
576     * used to execute any parallel tasks.
577     *
578     * @param a the array to be sorted
579     * @param fromIndex the index of the first element, inclusive, to be sorted
580     * @param toIndex the index of the last element, exclusive, to be sorted
581     *
582     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
583     * @throws ArrayIndexOutOfBoundsException
584     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
585     *
586     * @since 1.8
587     */
588    public static void parallelSort(char[] a, int fromIndex, int toIndex) {
589        rangeCheck(a.length, fromIndex, toIndex);
590        int n = toIndex - fromIndex, p, g;
591        if (n <= MIN_ARRAY_SORT_GRAN ||
592            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
593            DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);
594        else
595            new ArraysParallelSortHelpers.FJChar.Sorter
596                (null, a, new char[n], fromIndex, n, 0,
597                 ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
598                 MIN_ARRAY_SORT_GRAN : g).invoke();
599    }
600
601    /**
602     * Sorts the specified array into ascending numerical order.
603     *
604     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
605     * array into sub-arrays that are themselves sorted and then merged. When
606     * the sub-array length reaches a minimum granularity, the sub-array is
607     * sorted using the appropriate {@link Arrays#sort(short[]) Arrays.sort}
608     * method. If the length of the specified array is less than the minimum
609     * granularity, then it is sorted using the appropriate {@link
610     * Arrays#sort(short[]) Arrays.sort} method. The algorithm requires a
611     * working space no greater than the size of the original array. The
612     * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to
613     * execute any parallel tasks.
614     *
615     * @param a the array to be sorted
616     *
617     * @since 1.8
618     */
619    public static void parallelSort(short[] a) {
620        int n = a.length, p, g;
621        if (n <= MIN_ARRAY_SORT_GRAN ||
622            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
623            DualPivotQuicksort.sort(a, 0, n - 1, null, 0, 0);
624        else
625            new ArraysParallelSortHelpers.FJShort.Sorter
626                (null, a, new short[n], 0, n, 0,
627                 ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
628                 MIN_ARRAY_SORT_GRAN : g).invoke();
629    }
630
631    /**
632     * Sorts the specified range of the array into ascending numerical order.
633     * The range to be sorted extends from the index {@code fromIndex},
634     * inclusive, to the index {@code toIndex}, exclusive. If
635     * {@code fromIndex == toIndex}, the range to be sorted is empty.
636     *
637     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
638     * array into sub-arrays that are themselves sorted and then merged. When
639     * the sub-array length reaches a minimum granularity, the sub-array is
640     * sorted using the appropriate {@link Arrays#sort(short[]) Arrays.sort}
641     * method. If the length of the specified array is less than the minimum
642     * granularity, then it is sorted using the appropriate {@link
643     * Arrays#sort(short[]) Arrays.sort} method. The algorithm requires a working
644     * space no greater than the size of the specified range of the original
645     * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is
646     * used to execute any parallel tasks.
647     *
648     * @param a the array to be sorted
649     * @param fromIndex the index of the first element, inclusive, to be sorted
650     * @param toIndex the index of the last element, exclusive, to be sorted
651     *
652     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
653     * @throws ArrayIndexOutOfBoundsException
654     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
655     *
656     * @since 1.8
657     */
658    public static void parallelSort(short[] a, int fromIndex, int toIndex) {
659        rangeCheck(a.length, fromIndex, toIndex);
660        int n = toIndex - fromIndex, p, g;
661        if (n <= MIN_ARRAY_SORT_GRAN ||
662            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
663            DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);
664        else
665            new ArraysParallelSortHelpers.FJShort.Sorter
666                (null, a, new short[n], fromIndex, n, 0,
667                 ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
668                 MIN_ARRAY_SORT_GRAN : g).invoke();
669    }
670
671    /**
672     * Sorts the specified array into ascending numerical order.
673     *
674     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
675     * array into sub-arrays that are themselves sorted and then merged. When
676     * the sub-array length reaches a minimum granularity, the sub-array is
677     * sorted using the appropriate {@link Arrays#sort(int[]) Arrays.sort}
678     * method. If the length of the specified array is less than the minimum
679     * granularity, then it is sorted using the appropriate {@link
680     * Arrays#sort(int[]) Arrays.sort} method. The algorithm requires a
681     * working space no greater than the size of the original array. The
682     * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to
683     * execute any parallel tasks.
684     *
685     * @param a the array to be sorted
686     *
687     * @since 1.8
688     */
689    public static void parallelSort(int[] a) {
690        int n = a.length, p, g;
691        if (n <= MIN_ARRAY_SORT_GRAN ||
692            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
693            DualPivotQuicksort.sort(a, 0, n - 1, null, 0, 0);
694        else
695            new ArraysParallelSortHelpers.FJInt.Sorter
696                (null, a, new int[n], 0, n, 0,
697                 ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
698                 MIN_ARRAY_SORT_GRAN : g).invoke();
699    }
700
701    /**
702     * Sorts the specified range of the array into ascending numerical order.
703     * The range to be sorted extends from the index {@code fromIndex},
704     * inclusive, to the index {@code toIndex}, exclusive. If
705     * {@code fromIndex == toIndex}, the range to be sorted is empty.
706     *
707     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
708     * array into sub-arrays that are themselves sorted and then merged. When
709     * the sub-array length reaches a minimum granularity, the sub-array is
710     * sorted using the appropriate {@link Arrays#sort(int[]) Arrays.sort}
711     * method. If the length of the specified array is less than the minimum
712     * granularity, then it is sorted using the appropriate {@link
713     * Arrays#sort(int[]) Arrays.sort} method. The algorithm requires a working
714     * space no greater than the size of the specified range of the original
715     * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is
716     * used to execute any parallel tasks.
717     *
718     * @param a the array to be sorted
719     * @param fromIndex the index of the first element, inclusive, to be sorted
720     * @param toIndex the index of the last element, exclusive, to be sorted
721     *
722     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
723     * @throws ArrayIndexOutOfBoundsException
724     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
725     *
726     * @since 1.8
727     */
728    public static void parallelSort(int[] a, int fromIndex, int toIndex) {
729        rangeCheck(a.length, fromIndex, toIndex);
730        int n = toIndex - fromIndex, p, g;
731        if (n <= MIN_ARRAY_SORT_GRAN ||
732            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
733            DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);
734        else
735            new ArraysParallelSortHelpers.FJInt.Sorter
736                (null, a, new int[n], fromIndex, n, 0,
737                 ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
738                 MIN_ARRAY_SORT_GRAN : g).invoke();
739    }
740
741    /**
742     * Sorts the specified array into ascending numerical order.
743     *
744     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
745     * array into sub-arrays that are themselves sorted and then merged. When
746     * the sub-array length reaches a minimum granularity, the sub-array is
747     * sorted using the appropriate {@link Arrays#sort(long[]) Arrays.sort}
748     * method. If the length of the specified array is less than the minimum
749     * granularity, then it is sorted using the appropriate {@link
750     * Arrays#sort(long[]) Arrays.sort} method. The algorithm requires a
751     * working space no greater than the size of the original array. The
752     * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to
753     * execute any parallel tasks.
754     *
755     * @param a the array to be sorted
756     *
757     * @since 1.8
758     */
759    public static void parallelSort(long[] a) {
760        int n = a.length, p, g;
761        if (n <= MIN_ARRAY_SORT_GRAN ||
762            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
763            DualPivotQuicksort.sort(a, 0, n - 1, null, 0, 0);
764        else
765            new ArraysParallelSortHelpers.FJLong.Sorter
766                (null, a, new long[n], 0, n, 0,
767                 ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
768                 MIN_ARRAY_SORT_GRAN : g).invoke();
769    }
770
771    /**
772     * Sorts the specified range of the array into ascending numerical order.
773     * The range to be sorted extends from the index {@code fromIndex},
774     * inclusive, to the index {@code toIndex}, exclusive. If
775     * {@code fromIndex == toIndex}, the range to be sorted is empty.
776     *
777     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
778     * array into sub-arrays that are themselves sorted and then merged. When
779     * the sub-array length reaches a minimum granularity, the sub-array is
780     * sorted using the appropriate {@link Arrays#sort(long[]) Arrays.sort}
781     * method. If the length of the specified array is less than the minimum
782     * granularity, then it is sorted using the appropriate {@link
783     * Arrays#sort(long[]) Arrays.sort} method. The algorithm requires a working
784     * space no greater than the size of the specified range of the original
785     * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is
786     * used to execute any parallel tasks.
787     *
788     * @param a the array to be sorted
789     * @param fromIndex the index of the first element, inclusive, to be sorted
790     * @param toIndex the index of the last element, exclusive, to be sorted
791     *
792     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
793     * @throws ArrayIndexOutOfBoundsException
794     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
795     *
796     * @since 1.8
797     */
798    public static void parallelSort(long[] a, int fromIndex, int toIndex) {
799        rangeCheck(a.length, fromIndex, toIndex);
800        int n = toIndex - fromIndex, p, g;
801        if (n <= MIN_ARRAY_SORT_GRAN ||
802            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
803            DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);
804        else
805            new ArraysParallelSortHelpers.FJLong.Sorter
806                (null, a, new long[n], fromIndex, n, 0,
807                 ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
808                 MIN_ARRAY_SORT_GRAN : g).invoke();
809    }
810
811    /**
812     * Sorts the specified array into ascending numerical order.
813     *
814     * <p>The {@code <} relation does not provide a total order on all float
815     * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
816     * value compares neither less than, greater than, nor equal to any value,
817     * even itself. This method uses the total order imposed by the method
818     * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
819     * {@code 0.0f} and {@code Float.NaN} is considered greater than any
820     * other value and all {@code Float.NaN} values are considered equal.
821     *
822     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
823     * array into sub-arrays that are themselves sorted and then merged. When
824     * the sub-array length reaches a minimum granularity, the sub-array is
825     * sorted using the appropriate {@link Arrays#sort(float[]) Arrays.sort}
826     * method. If the length of the specified array is less than the minimum
827     * granularity, then it is sorted using the appropriate {@link
828     * Arrays#sort(float[]) Arrays.sort} method. The algorithm requires a
829     * working space no greater than the size of the original array. The
830     * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to
831     * execute any parallel tasks.
832     *
833     * @param a the array to be sorted
834     *
835     * @since 1.8
836     */
837    public static void parallelSort(float[] a) {
838        int n = a.length, p, g;
839        if (n <= MIN_ARRAY_SORT_GRAN ||
840            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
841            DualPivotQuicksort.sort(a, 0, n - 1, null, 0, 0);
842        else
843            new ArraysParallelSortHelpers.FJFloat.Sorter
844                (null, a, new float[n], 0, n, 0,
845                 ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
846                 MIN_ARRAY_SORT_GRAN : g).invoke();
847    }
848
849    /**
850     * Sorts the specified range of the array into ascending numerical order.
851     * The range to be sorted extends from the index {@code fromIndex},
852     * inclusive, to the index {@code toIndex}, exclusive. If
853     * {@code fromIndex == toIndex}, the range to be sorted is empty.
854     *
855     * <p>The {@code <} relation does not provide a total order on all float
856     * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
857     * value compares neither less than, greater than, nor equal to any value,
858     * even itself. This method uses the total order imposed by the method
859     * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
860     * {@code 0.0f} and {@code Float.NaN} is considered greater than any
861     * other value and all {@code Float.NaN} values are considered equal.
862     *
863     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
864     * array into sub-arrays that are themselves sorted and then merged. When
865     * the sub-array length reaches a minimum granularity, the sub-array is
866     * sorted using the appropriate {@link Arrays#sort(float[]) Arrays.sort}
867     * method. If the length of the specified array is less than the minimum
868     * granularity, then it is sorted using the appropriate {@link
869     * Arrays#sort(float[]) Arrays.sort} method. The algorithm requires a working
870     * space no greater than the size of the specified range of the original
871     * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is
872     * used to execute any parallel tasks.
873     *
874     * @param a the array to be sorted
875     * @param fromIndex the index of the first element, inclusive, to be sorted
876     * @param toIndex the index of the last element, exclusive, to be sorted
877     *
878     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
879     * @throws ArrayIndexOutOfBoundsException
880     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
881     *
882     * @since 1.8
883     */
884    public static void parallelSort(float[] a, int fromIndex, int toIndex) {
885        rangeCheck(a.length, fromIndex, toIndex);
886        int n = toIndex - fromIndex, p, g;
887        if (n <= MIN_ARRAY_SORT_GRAN ||
888            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
889            DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);
890        else
891            new ArraysParallelSortHelpers.FJFloat.Sorter
892                (null, a, new float[n], fromIndex, n, 0,
893                 ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
894                 MIN_ARRAY_SORT_GRAN : g).invoke();
895    }
896
897    /**
898     * Sorts the specified array into ascending numerical order.
899     *
900     * <p>The {@code <} relation does not provide a total order on all double
901     * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
902     * value compares neither less than, greater than, nor equal to any value,
903     * even itself. This method uses the total order imposed by the method
904     * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
905     * {@code 0.0d} and {@code Double.NaN} is considered greater than any
906     * other value and all {@code Double.NaN} values are considered equal.
907     *
908     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
909     * array into sub-arrays that are themselves sorted and then merged. When
910     * the sub-array length reaches a minimum granularity, the sub-array is
911     * sorted using the appropriate {@link Arrays#sort(double[]) Arrays.sort}
912     * method. If the length of the specified array is less than the minimum
913     * granularity, then it is sorted using the appropriate {@link
914     * Arrays#sort(double[]) Arrays.sort} method. The algorithm requires a
915     * working space no greater than the size of the original array. The
916     * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to
917     * execute any parallel tasks.
918     *
919     * @param a the array to be sorted
920     *
921     * @since 1.8
922     */
923    public static void parallelSort(double[] a) {
924        int n = a.length, p, g;
925        if (n <= MIN_ARRAY_SORT_GRAN ||
926            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
927            DualPivotQuicksort.sort(a, 0, n - 1, null, 0, 0);
928        else
929            new ArraysParallelSortHelpers.FJDouble.Sorter
930                (null, a, new double[n], 0, n, 0,
931                 ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
932                 MIN_ARRAY_SORT_GRAN : g).invoke();
933    }
934
935    /**
936     * Sorts the specified range of the array into ascending numerical order.
937     * The range to be sorted extends from the index {@code fromIndex},
938     * inclusive, to the index {@code toIndex}, exclusive. If
939     * {@code fromIndex == toIndex}, the range to be sorted is empty.
940     *
941     * <p>The {@code <} relation does not provide a total order on all double
942     * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
943     * value compares neither less than, greater than, nor equal to any value,
944     * even itself. This method uses the total order imposed by the method
945     * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
946     * {@code 0.0d} and {@code Double.NaN} is considered greater than any
947     * other value and all {@code Double.NaN} values are considered equal.
948     *
949     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
950     * array into sub-arrays that are themselves sorted and then merged. When
951     * the sub-array length reaches a minimum granularity, the sub-array is
952     * sorted using the appropriate {@link Arrays#sort(double[]) Arrays.sort}
953     * method. If the length of the specified array is less than the minimum
954     * granularity, then it is sorted using the appropriate {@link
955     * Arrays#sort(double[]) Arrays.sort} method. The algorithm requires a working
956     * space no greater than the size of the specified range of the original
957     * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is
958     * used to execute any parallel tasks.
959     *
960     * @param a the array to be sorted
961     * @param fromIndex the index of the first element, inclusive, to be sorted
962     * @param toIndex the index of the last element, exclusive, to be sorted
963     *
964     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
965     * @throws ArrayIndexOutOfBoundsException
966     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
967     *
968     * @since 1.8
969     */
970    public static void parallelSort(double[] a, int fromIndex, int toIndex) {
971        rangeCheck(a.length, fromIndex, toIndex);
972        int n = toIndex - fromIndex, p, g;
973        if (n <= MIN_ARRAY_SORT_GRAN ||
974            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
975            DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);
976        else
977            new ArraysParallelSortHelpers.FJDouble.Sorter
978                (null, a, new double[n], fromIndex, n, 0,
979                 ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
980                 MIN_ARRAY_SORT_GRAN : g).invoke();
981    }
982
983    /**
984     * Sorts the specified array of objects into ascending order, according
985     * to the {@linkplain Comparable natural ordering} of its elements.
986     * All elements in the array must implement the {@link Comparable}
987     * interface.  Furthermore, all elements in the array must be
988     * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)} must
989     * not throw a {@code ClassCastException} for any elements {@code e1}
990     * and {@code e2} in the array).
991     *
992     * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
993     * not be reordered as a result of the sort.
994     *
995     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
996     * array into sub-arrays that are themselves sorted and then merged. When
997     * the sub-array length reaches a minimum granularity, the sub-array is
998     * sorted using the appropriate {@link Arrays#sort(Object[]) Arrays.sort}
999     * method. If the length of the specified array is less than the minimum
1000     * granularity, then it is sorted using the appropriate {@link
1001     * Arrays#sort(Object[]) Arrays.sort} method. The algorithm requires a
1002     * working space no greater than the size of the original array. The
1003     * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to
1004     * execute any parallel tasks.
1005     *
1006     * @param <T> the class of the objects to be sorted
1007     * @param a the array to be sorted
1008     *
1009     * @throws ClassCastException if the array contains elements that are not
1010     *         <i>mutually comparable</i> (for example, strings and integers)
1011     * @throws IllegalArgumentException (optional) if the natural
1012     *         ordering of the array elements is found to violate the
1013     *         {@link Comparable} contract
1014     *
1015     * @since 1.8
1016     */
1017    @SuppressWarnings("unchecked")
1018    public static <T extends Comparable<? super T>> void parallelSort(T[] a) {
1019        int n = a.length, p, g;
1020        if (n <= MIN_ARRAY_SORT_GRAN ||
1021            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
1022            TimSort.sort(a, 0, n, NaturalOrder.INSTANCE, null, 0, 0);
1023        else
1024            new ArraysParallelSortHelpers.FJObject.Sorter<T>
1025                (null, a,
1026                 (T[])Array.newInstance(a.getClass().getComponentType(), n),
1027                 0, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
1028                 MIN_ARRAY_SORT_GRAN : g, NaturalOrder.INSTANCE).invoke();
1029    }
1030
1031    /**
1032     * Sorts the specified range of the specified array of objects into
1033     * ascending order, according to the
1034     * {@linkplain Comparable natural ordering} of its
1035     * elements.  The range to be sorted extends from index
1036     * {@code fromIndex}, inclusive, to index {@code toIndex}, exclusive.
1037     * (If {@code fromIndex==toIndex}, the range to be sorted is empty.)  All
1038     * elements in this range must implement the {@link Comparable}
1039     * interface.  Furthermore, all elements in this range must be <i>mutually
1040     * comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a
1041     * {@code ClassCastException} for any elements {@code e1} and
1042     * {@code e2} in the array).
1043     *
1044     * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
1045     * not be reordered as a result of the sort.
1046     *
1047     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
1048     * array into sub-arrays that are themselves sorted and then merged. When
1049     * the sub-array length reaches a minimum granularity, the sub-array is
1050     * sorted using the appropriate {@link Arrays#sort(Object[]) Arrays.sort}
1051     * method. If the length of the specified array is less than the minimum
1052     * granularity, then it is sorted using the appropriate {@link
1053     * Arrays#sort(Object[]) Arrays.sort} method. The algorithm requires a working
1054     * space no greater than the size of the specified range of the original
1055     * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is
1056     * used to execute any parallel tasks.
1057     *
1058     * @param <T> the class of the objects to be sorted
1059     * @param a the array to be sorted
1060     * @param fromIndex the index of the first element (inclusive) to be
1061     *        sorted
1062     * @param toIndex the index of the last element (exclusive) to be sorted
1063     * @throws IllegalArgumentException if {@code fromIndex > toIndex} or
1064     *         (optional) if the natural ordering of the array elements is
1065     *         found to violate the {@link Comparable} contract
1066     * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
1067     *         {@code toIndex > a.length}
1068     * @throws ClassCastException if the array contains elements that are
1069     *         not <i>mutually comparable</i> (for example, strings and
1070     *         integers).
1071     *
1072     * @since 1.8
1073     */
1074    @SuppressWarnings("unchecked")
1075    public static <T extends Comparable<? super T>>
1076    void parallelSort(T[] a, int fromIndex, int toIndex) {
1077        rangeCheck(a.length, fromIndex, toIndex);
1078        int n = toIndex - fromIndex, p, g;
1079        if (n <= MIN_ARRAY_SORT_GRAN ||
1080            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
1081            TimSort.sort(a, fromIndex, toIndex, NaturalOrder.INSTANCE, null, 0, 0);
1082        else
1083            new ArraysParallelSortHelpers.FJObject.Sorter<T>
1084                (null, a,
1085                 (T[])Array.newInstance(a.getClass().getComponentType(), n),
1086                 fromIndex, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
1087                 MIN_ARRAY_SORT_GRAN : g, NaturalOrder.INSTANCE).invoke();
1088    }
1089
1090    /**
1091     * Sorts the specified array of objects according to the order induced by
1092     * the specified comparator.  All elements in the array must be
1093     * <i>mutually comparable</i> by the specified comparator (that is,
1094     * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
1095     * for any elements {@code e1} and {@code e2} in the array).
1096     *
1097     * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
1098     * not be reordered as a result of the sort.
1099     *
1100     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
1101     * array into sub-arrays that are themselves sorted and then merged. When
1102     * the sub-array length reaches a minimum granularity, the sub-array is
1103     * sorted using the appropriate {@link Arrays#sort(Object[]) Arrays.sort}
1104     * method. If the length of the specified array is less than the minimum
1105     * granularity, then it is sorted using the appropriate {@link
1106     * Arrays#sort(Object[]) Arrays.sort} method. The algorithm requires a
1107     * working space no greater than the size of the original array. The
1108     * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to
1109     * execute any parallel tasks.
1110     *
1111     * @param <T> the class of the objects to be sorted
1112     * @param a the array to be sorted
1113     * @param cmp the comparator to determine the order of the array.  A
1114     *        {@code null} value indicates that the elements'
1115     *        {@linkplain Comparable natural ordering} should be used.
1116     * @throws ClassCastException if the array contains elements that are
1117     *         not <i>mutually comparable</i> using the specified comparator
1118     * @throws IllegalArgumentException (optional) if the comparator is
1119     *         found to violate the {@link java.util.Comparator} contract
1120     *
1121     * @since 1.8
1122     */
1123    @SuppressWarnings("unchecked")
1124    public static <T> void parallelSort(T[] a, Comparator<? super T> cmp) {
1125        if (cmp == null)
1126            cmp = NaturalOrder.INSTANCE;
1127        int n = a.length, p, g;
1128        if (n <= MIN_ARRAY_SORT_GRAN ||
1129            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
1130            TimSort.sort(a, 0, n, cmp, null, 0, 0);
1131        else
1132            new ArraysParallelSortHelpers.FJObject.Sorter<T>
1133                (null, a,
1134                 (T[])Array.newInstance(a.getClass().getComponentType(), n),
1135                 0, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
1136                 MIN_ARRAY_SORT_GRAN : g, cmp).invoke();
1137    }
1138
1139    /**
1140     * Sorts the specified range of the specified array of objects according
1141     * to the order induced by the specified comparator.  The range to be
1142     * sorted extends from index {@code fromIndex}, inclusive, to index
1143     * {@code toIndex}, exclusive.  (If {@code fromIndex==toIndex}, the
1144     * range to be sorted is empty.)  All elements in the range must be
1145     * <i>mutually comparable</i> by the specified comparator (that is,
1146     * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
1147     * for any elements {@code e1} and {@code e2} in the range).
1148     *
1149     * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
1150     * not be reordered as a result of the sort.
1151     *
1152     * @implNote The sorting algorithm is a parallel sort-merge that breaks the
1153     * array into sub-arrays that are themselves sorted and then merged. When
1154     * the sub-array length reaches a minimum granularity, the sub-array is
1155     * sorted using the appropriate {@link Arrays#sort(Object[]) Arrays.sort}
1156     * method. If the length of the specified array is less than the minimum
1157     * granularity, then it is sorted using the appropriate {@link
1158     * Arrays#sort(Object[]) Arrays.sort} method. The algorithm requires a working
1159     * space no greater than the size of the specified range of the original
1160     * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is
1161     * used to execute any parallel tasks.
1162     *
1163     * @param <T> the class of the objects to be sorted
1164     * @param a the array to be sorted
1165     * @param fromIndex the index of the first element (inclusive) to be
1166     *        sorted
1167     * @param toIndex the index of the last element (exclusive) to be sorted
1168     * @param cmp the comparator to determine the order of the array.  A
1169     *        {@code null} value indicates that the elements'
1170     *        {@linkplain Comparable natural ordering} should be used.
1171     * @throws IllegalArgumentException if {@code fromIndex > toIndex} or
1172     *         (optional) if the natural ordering of the array elements is
1173     *         found to violate the {@link Comparable} contract
1174     * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
1175     *         {@code toIndex > a.length}
1176     * @throws ClassCastException if the array contains elements that are
1177     *         not <i>mutually comparable</i> (for example, strings and
1178     *         integers).
1179     *
1180     * @since 1.8
1181     */
1182    @SuppressWarnings("unchecked")
1183    public static <T> void parallelSort(T[] a, int fromIndex, int toIndex,
1184                                        Comparator<? super T> cmp) {
1185        rangeCheck(a.length, fromIndex, toIndex);
1186        if (cmp == null)
1187            cmp = NaturalOrder.INSTANCE;
1188        int n = toIndex - fromIndex, p, g;
1189        if (n <= MIN_ARRAY_SORT_GRAN ||
1190            (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
1191            TimSort.sort(a, fromIndex, toIndex, cmp, null, 0, 0);
1192        else
1193            new ArraysParallelSortHelpers.FJObject.Sorter<T>
1194                (null, a,
1195                 (T[])Array.newInstance(a.getClass().getComponentType(), n),
1196                 fromIndex, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
1197                 MIN_ARRAY_SORT_GRAN : g, cmp).invoke();
1198    }
1199
1200    /*
1201     * Sorting of complex type arrays.
1202     */
1203
1204    /**
1205     * Sorts the specified array of objects into ascending order, according
1206     * to the {@linkplain Comparable natural ordering} of its elements.
1207     * All elements in the array must implement the {@link Comparable}
1208     * interface.  Furthermore, all elements in the array must be
1209     * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)} must
1210     * not throw a {@code ClassCastException} for any elements {@code e1}
1211     * and {@code e2} in the array).
1212     *
1213     * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
1214     * not be reordered as a result of the sort.
1215     *
1216     * <p>Implementation note: This implementation is a stable, adaptive,
1217     * iterative mergesort that requires far fewer than n lg(n) comparisons
1218     * when the input array is partially sorted, while offering the
1219     * performance of a traditional mergesort when the input array is
1220     * randomly ordered.  If the input array is nearly sorted, the
1221     * implementation requires approximately n comparisons.  Temporary
1222     * storage requirements vary from a small constant for nearly sorted
1223     * input arrays to n/2 object references for randomly ordered input
1224     * arrays.
1225     *
1226     * <p>The implementation takes equal advantage of ascending and
1227     * descending order in its input array, and can take advantage of
1228     * ascending and descending order in different parts of the the same
1229     * input array.  It is well-suited to merging two or more sorted arrays:
1230     * simply concatenate the arrays and sort the resulting array.
1231     *
1232     * <p>The implementation was adapted from Tim Peters's list sort for Python
1233     * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
1234     * TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic
1235     * Sorting and Information Theoretic Complexity", in Proceedings of the
1236     * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
1237     * January 1993.
1238     *
1239     * @param a the array to be sorted
1240     * @throws ClassCastException if the array contains elements that are not
1241     *         <i>mutually comparable</i> (for example, strings and integers)
1242     * @throws IllegalArgumentException (optional) if the natural
1243     *         ordering of the array elements is found to violate the
1244     *         {@link Comparable} contract
1245     */
1246    public static void sort(Object[] a) {
1247        // Android-changed: LegacyMergeSort is no longer supported
1248        // if (LegacyMergeSort.userRequested)
1249        //     legacyMergeSort(a);
1250        // else
1251            ComparableTimSort.sort(a, 0, a.length, null, 0, 0);
1252    }
1253
1254    /**
1255     * Sorts the specified range of the specified array of objects into
1256     * ascending order, according to the
1257     * {@linkplain Comparable natural ordering} of its
1258     * elements.  The range to be sorted extends from index
1259     * {@code fromIndex}, inclusive, to index {@code toIndex}, exclusive.
1260     * (If {@code fromIndex==toIndex}, the range to be sorted is empty.)  All
1261     * elements in this range must implement the {@link Comparable}
1262     * interface.  Furthermore, all elements in this range must be <i>mutually
1263     * comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a
1264     * {@code ClassCastException} for any elements {@code e1} and
1265     * {@code e2} in the array).
1266     *
1267     * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
1268     * not be reordered as a result of the sort.
1269     *
1270     * <p>Implementation note: This implementation is a stable, adaptive,
1271     * iterative mergesort that requires far fewer than n lg(n) comparisons
1272     * when the input array is partially sorted, while offering the
1273     * performance of a traditional mergesort when the input array is
1274     * randomly ordered.  If the input array is nearly sorted, the
1275     * implementation requires approximately n comparisons.  Temporary
1276     * storage requirements vary from a small constant for nearly sorted
1277     * input arrays to n/2 object references for randomly ordered input
1278     * arrays.
1279     *
1280     * <p>The implementation takes equal advantage of ascending and
1281     * descending order in its input array, and can take advantage of
1282     * ascending and descending order in different parts of the the same
1283     * input array.  It is well-suited to merging two or more sorted arrays:
1284     * simply concatenate the arrays and sort the resulting array.
1285     *
1286     * <p>The implementation was adapted from Tim Peters's list sort for Python
1287     * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
1288     * TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic
1289     * Sorting and Information Theoretic Complexity", in Proceedings of the
1290     * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
1291     * January 1993.
1292     *
1293     * @param a the array to be sorted
1294     * @param fromIndex the index of the first element (inclusive) to be
1295     *        sorted
1296     * @param toIndex the index of the last element (exclusive) to be sorted
1297     * @throws IllegalArgumentException if {@code fromIndex > toIndex} or
1298     *         (optional) if the natural ordering of the array elements is
1299     *         found to violate the {@link Comparable} contract
1300     * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
1301     *         {@code toIndex > a.length}
1302     * @throws ClassCastException if the array contains elements that are
1303     *         not <i>mutually comparable</i> (for example, strings and
1304     *         integers).
1305     */
1306    public static void sort(Object[] a, int fromIndex, int toIndex) {
1307        rangeCheck(a.length, fromIndex, toIndex);
1308        // Android-changed: LegacyMergeSort is no longer supported
1309        // if (LegacyMergeSort.userRequested)
1310        //     legacyMergeSort(a, fromIndex, toIndex);
1311        // else
1312            ComparableTimSort.sort(a, fromIndex, toIndex, null, 0, 0);
1313    }
1314
1315    /**
1316     * Tuning parameter: list size at or below which insertion sort will be
1317     * used in preference to mergesort.
1318     * To be removed in a future release.
1319     */
1320    private static final int INSERTIONSORT_THRESHOLD = 7;
1321
1322    /**
1323     * Src is the source array that starts at index 0
1324     * Dest is the (possibly larger) array destination with a possible offset
1325     * low is the index in dest to start sorting
1326     * high is the end index in dest to end sorting
1327     * off is the offset to generate corresponding low, high in src
1328     * To be removed in a future release.
1329     */
1330    @SuppressWarnings({"unchecked", "rawtypes"})
1331    private static void mergeSort(Object[] src,
1332                                  Object[] dest,
1333                                  int low,
1334                                  int high,
1335                                  int off) {
1336        int length = high - low;
1337
1338        // Insertion sort on smallest arrays
1339        if (length < INSERTIONSORT_THRESHOLD) {
1340            for (int i=low; i<high; i++)
1341                for (int j=i; j>low &&
1342                         ((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)
1343                    swap(dest, j, j-1);
1344            return;
1345        }
1346
1347        // Recursively sort halves of dest into src
1348        int destLow  = low;
1349        int destHigh = high;
1350        low  += off;
1351        high += off;
1352        int mid = (low + high) >>> 1;
1353        mergeSort(dest, src, low, mid, -off);
1354        mergeSort(dest, src, mid, high, -off);
1355
1356        // If list is already sorted, just copy from src to dest.  This is an
1357        // optimization that results in faster sorts for nearly ordered lists.
1358        if (((Comparable)src[mid-1]).compareTo(src[mid]) <= 0) {
1359            System.arraycopy(src, low, dest, destLow, length);
1360            return;
1361        }
1362
1363        // Merge sorted halves (now in src) into dest
1364        for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
1365            if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0)
1366                dest[i] = src[p++];
1367            else
1368                dest[i] = src[q++];
1369        }
1370    }
1371
1372    /**
1373     * Swaps x[a] with x[b].
1374     */
1375    private static void swap(Object[] x, int a, int b) {
1376        Object t = x[a];
1377        x[a] = x[b];
1378        x[b] = t;
1379    }
1380
1381    /**
1382     * Sorts the specified array of objects according to the order induced by
1383     * the specified comparator.  All elements in the array must be
1384     * <i>mutually comparable</i> by the specified comparator (that is,
1385     * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
1386     * for any elements {@code e1} and {@code e2} in the array).
1387     *
1388     * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
1389     * not be reordered as a result of the sort.
1390     *
1391     * <p>Implementation note: This implementation is a stable, adaptive,
1392     * iterative mergesort that requires far fewer than n lg(n) comparisons
1393     * when the input array is partially sorted, while offering the
1394     * performance of a traditional mergesort when the input array is
1395     * randomly ordered.  If the input array is nearly sorted, the
1396     * implementation requires approximately n comparisons.  Temporary
1397     * storage requirements vary from a small constant for nearly sorted
1398     * input arrays to n/2 object references for randomly ordered input
1399     * arrays.
1400     *
1401     * <p>The implementation takes equal advantage of ascending and
1402     * descending order in its input array, and can take advantage of
1403     * ascending and descending order in different parts of the the same
1404     * input array.  It is well-suited to merging two or more sorted arrays:
1405     * simply concatenate the arrays and sort the resulting array.
1406     *
1407     * <p>The implementation was adapted from Tim Peters's list sort for Python
1408     * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
1409     * TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic
1410     * Sorting and Information Theoretic Complexity", in Proceedings of the
1411     * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
1412     * January 1993.
1413     *
1414     * @param <T> the class of the objects to be sorted
1415     * @param a the array to be sorted
1416     * @param c the comparator to determine the order of the array.  A
1417     *        {@code null} value indicates that the elements'
1418     *        {@linkplain Comparable natural ordering} should be used.
1419     * @throws ClassCastException if the array contains elements that are
1420     *         not <i>mutually comparable</i> using the specified comparator
1421     * @throws IllegalArgumentException (optional) if the comparator is
1422     *         found to violate the {@link Comparator} contract
1423     */
1424    public static <T> void sort(T[] a, Comparator<? super T> c) {
1425        if (c == null) {
1426            sort(a);
1427        } else {
1428            // Android-changed: LegacyMergeSort is no longer supported
1429            // if (LegacyMergeSort.userRequested)
1430            //     legacyMergeSort(a, c);
1431            // else
1432                TimSort.sort(a, 0, a.length, c, null, 0, 0);
1433        }
1434    }
1435
1436    /**
1437     * Sorts the specified range of the specified array of objects according
1438     * to the order induced by the specified comparator.  The range to be
1439     * sorted extends from index {@code fromIndex}, inclusive, to index
1440     * {@code toIndex}, exclusive.  (If {@code fromIndex==toIndex}, the
1441     * range to be sorted is empty.)  All elements in the range must be
1442     * <i>mutually comparable</i> by the specified comparator (that is,
1443     * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
1444     * for any elements {@code e1} and {@code e2} in the range).
1445     *
1446     * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
1447     * not be reordered as a result of the sort.
1448     *
1449     * <p>Implementation note: This implementation is a stable, adaptive,
1450     * iterative mergesort that requires far fewer than n lg(n) comparisons
1451     * when the input array is partially sorted, while offering the
1452     * performance of a traditional mergesort when the input array is
1453     * randomly ordered.  If the input array is nearly sorted, the
1454     * implementation requires approximately n comparisons.  Temporary
1455     * storage requirements vary from a small constant for nearly sorted
1456     * input arrays to n/2 object references for randomly ordered input
1457     * arrays.
1458     *
1459     * <p>The implementation takes equal advantage of ascending and
1460     * descending order in its input array, and can take advantage of
1461     * ascending and descending order in different parts of the the same
1462     * input array.  It is well-suited to merging two or more sorted arrays:
1463     * simply concatenate the arrays and sort the resulting array.
1464     *
1465     * <p>The implementation was adapted from Tim Peters's list sort for Python
1466     * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
1467     * TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic
1468     * Sorting and Information Theoretic Complexity", in Proceedings of the
1469     * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
1470     * January 1993.
1471     *
1472     * @param <T> the class of the objects to be sorted
1473     * @param a the array to be sorted
1474     * @param fromIndex the index of the first element (inclusive) to be
1475     *        sorted
1476     * @param toIndex the index of the last element (exclusive) to be sorted
1477     * @param c the comparator to determine the order of the array.  A
1478     *        {@code null} value indicates that the elements'
1479     *        {@linkplain Comparable natural ordering} should be used.
1480     * @throws ClassCastException if the array contains elements that are not
1481     *         <i>mutually comparable</i> using the specified comparator.
1482     * @throws IllegalArgumentException if {@code fromIndex > toIndex} or
1483     *         (optional) if the comparator is found to violate the
1484     *         {@link Comparator} contract
1485     * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
1486     *         {@code toIndex > a.length}
1487     */
1488    public static <T> void sort(T[] a, int fromIndex, int toIndex,
1489                                Comparator<? super T> c) {
1490        if (c == null) {
1491            sort(a, fromIndex, toIndex);
1492        } else {
1493            rangeCheck(a.length, fromIndex, toIndex);
1494            // Android-changed: LegacyMergeSort is no longer supported
1495            // if (LegacyMergeSort.userRequested)
1496            //     legacyMergeSort(a, fromIndex, toIndex, c);
1497            // else
1498                TimSort.sort(a, fromIndex, toIndex, c, null, 0, 0);
1499        }
1500    }
1501
1502    // Parallel prefix
1503
1504    /**
1505     * Cumulates, in parallel, each element of the given array in place,
1506     * using the supplied function. For example if the array initially
1507     * holds {@code [2, 1, 0, 3]} and the operation performs addition,
1508     * then upon return the array holds {@code [2, 3, 3, 6]}.
1509     * Parallel prefix computation is usually more efficient than
1510     * sequential loops for large arrays.
1511     *
1512     * @param <T> the class of the objects in the array
1513     * @param array the array, which is modified in-place by this method
1514     * @param op a side-effect-free, associative function to perform the
1515     * cumulation
1516     * @throws NullPointerException if the specified array or function is null
1517     * @since 1.8
1518     */
1519    public static <T> void parallelPrefix(T[] array, BinaryOperator<T> op) {
1520        Objects.requireNonNull(op);
1521        if (array.length > 0)
1522            new ArrayPrefixHelpers.CumulateTask<>
1523                    (null, op, array, 0, array.length).invoke();
1524    }
1525
1526    /**
1527     * Performs {@link #parallelPrefix(Object[], BinaryOperator)}
1528     * for the given subrange of the array.
1529     *
1530     * @param <T> the class of the objects in the array
1531     * @param array the array
1532     * @param fromIndex the index of the first element, inclusive
1533     * @param toIndex the index of the last element, exclusive
1534     * @param op a side-effect-free, associative function to perform the
1535     * cumulation
1536     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
1537     * @throws ArrayIndexOutOfBoundsException
1538     *     if {@code fromIndex < 0} or {@code toIndex > array.length}
1539     * @throws NullPointerException if the specified array or function is null
1540     * @since 1.8
1541     */
1542    public static <T> void parallelPrefix(T[] array, int fromIndex,
1543                                          int toIndex, BinaryOperator<T> op) {
1544        Objects.requireNonNull(op);
1545        rangeCheck(array.length, fromIndex, toIndex);
1546        if (fromIndex < toIndex)
1547            new ArrayPrefixHelpers.CumulateTask<>
1548                    (null, op, array, fromIndex, toIndex).invoke();
1549    }
1550
1551    /**
1552     * Cumulates, in parallel, each element of the given array in place,
1553     * using the supplied function. For example if the array initially
1554     * holds {@code [2, 1, 0, 3]} and the operation performs addition,
1555     * then upon return the array holds {@code [2, 3, 3, 6]}.
1556     * Parallel prefix computation is usually more efficient than
1557     * sequential loops for large arrays.
1558     *
1559     * @param array the array, which is modified in-place by this method
1560     * @param op a side-effect-free, associative function to perform the
1561     * cumulation
1562     * @throws NullPointerException if the specified array or function is null
1563     * @since 1.8
1564     */
1565    public static void parallelPrefix(long[] array, LongBinaryOperator op) {
1566        Objects.requireNonNull(op);
1567        if (array.length > 0)
1568            new ArrayPrefixHelpers.LongCumulateTask
1569                    (null, op, array, 0, array.length).invoke();
1570    }
1571
1572    /**
1573     * Performs {@link #parallelPrefix(long[], LongBinaryOperator)}
1574     * for the given subrange of the array.
1575     *
1576     * @param array the array
1577     * @param fromIndex the index of the first element, inclusive
1578     * @param toIndex the index of the last element, exclusive
1579     * @param op a side-effect-free, associative function to perform the
1580     * cumulation
1581     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
1582     * @throws ArrayIndexOutOfBoundsException
1583     *     if {@code fromIndex < 0} or {@code toIndex > array.length}
1584     * @throws NullPointerException if the specified array or function is null
1585     * @since 1.8
1586     */
1587    public static void parallelPrefix(long[] array, int fromIndex,
1588                                      int toIndex, LongBinaryOperator op) {
1589        Objects.requireNonNull(op);
1590        rangeCheck(array.length, fromIndex, toIndex);
1591        if (fromIndex < toIndex)
1592            new ArrayPrefixHelpers.LongCumulateTask
1593                    (null, op, array, fromIndex, toIndex).invoke();
1594    }
1595
1596    /**
1597     * Cumulates, in parallel, each element of the given array in place,
1598     * using the supplied function. For example if the array initially
1599     * holds {@code [2.0, 1.0, 0.0, 3.0]} and the operation performs addition,
1600     * then upon return the array holds {@code [2.0, 3.0, 3.0, 6.0]}.
1601     * Parallel prefix computation is usually more efficient than
1602     * sequential loops for large arrays.
1603     *
1604     * <p> Because floating-point operations may not be strictly associative,
1605     * the returned result may not be identical to the value that would be
1606     * obtained if the operation was performed sequentially.
1607     *
1608     * @param array the array, which is modified in-place by this method
1609     * @param op a side-effect-free function to perform the cumulation
1610     * @throws NullPointerException if the specified array or function is null
1611     * @since 1.8
1612     */
1613    public static void parallelPrefix(double[] array, DoubleBinaryOperator op) {
1614        Objects.requireNonNull(op);
1615        if (array.length > 0)
1616            new ArrayPrefixHelpers.DoubleCumulateTask
1617                    (null, op, array, 0, array.length).invoke();
1618    }
1619
1620    /**
1621     * Performs {@link #parallelPrefix(double[], DoubleBinaryOperator)}
1622     * for the given subrange of the array.
1623     *
1624     * @param array the array
1625     * @param fromIndex the index of the first element, inclusive
1626     * @param toIndex the index of the last element, exclusive
1627     * @param op a side-effect-free, associative function to perform the
1628     * cumulation
1629     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
1630     * @throws ArrayIndexOutOfBoundsException
1631     *     if {@code fromIndex < 0} or {@code toIndex > array.length}
1632     * @throws NullPointerException if the specified array or function is null
1633     * @since 1.8
1634     */
1635    public static void parallelPrefix(double[] array, int fromIndex,
1636                                      int toIndex, DoubleBinaryOperator op) {
1637        Objects.requireNonNull(op);
1638        rangeCheck(array.length, fromIndex, toIndex);
1639        if (fromIndex < toIndex)
1640            new ArrayPrefixHelpers.DoubleCumulateTask
1641                    (null, op, array, fromIndex, toIndex).invoke();
1642    }
1643
1644    /**
1645     * Cumulates, in parallel, each element of the given array in place,
1646     * using the supplied function. For example if the array initially
1647     * holds {@code [2, 1, 0, 3]} and the operation performs addition,
1648     * then upon return the array holds {@code [2, 3, 3, 6]}.
1649     * Parallel prefix computation is usually more efficient than
1650     * sequential loops for large arrays.
1651     *
1652     * @param array the array, which is modified in-place by this method
1653     * @param op a side-effect-free, associative function to perform the
1654     * cumulation
1655     * @throws NullPointerException if the specified array or function is null
1656     * @since 1.8
1657     */
1658    public static void parallelPrefix(int[] array, IntBinaryOperator op) {
1659        Objects.requireNonNull(op);
1660        if (array.length > 0)
1661            new ArrayPrefixHelpers.IntCumulateTask
1662                    (null, op, array, 0, array.length).invoke();
1663    }
1664
1665    /**
1666     * Performs {@link #parallelPrefix(int[], IntBinaryOperator)}
1667     * for the given subrange of the array.
1668     *
1669     * @param array the array
1670     * @param fromIndex the index of the first element, inclusive
1671     * @param toIndex the index of the last element, exclusive
1672     * @param op a side-effect-free, associative function to perform the
1673     * cumulation
1674     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
1675     * @throws ArrayIndexOutOfBoundsException
1676     *     if {@code fromIndex < 0} or {@code toIndex > array.length}
1677     * @throws NullPointerException if the specified array or function is null
1678     * @since 1.8
1679     */
1680    public static void parallelPrefix(int[] array, int fromIndex,
1681                                      int toIndex, IntBinaryOperator op) {
1682        Objects.requireNonNull(op);
1683        rangeCheck(array.length, fromIndex, toIndex);
1684        if (fromIndex < toIndex)
1685            new ArrayPrefixHelpers.IntCumulateTask
1686                    (null, op, array, fromIndex, toIndex).invoke();
1687    }
1688
1689    // Searching
1690
1691    /**
1692     * Searches the specified array of longs for the specified value using the
1693     * binary search algorithm.  The array must be sorted (as
1694     * by the {@link #sort(long[])} method) prior to making this call.  If it
1695     * is not sorted, the results are undefined.  If the array contains
1696     * multiple elements with the specified value, there is no guarantee which
1697     * one will be found.
1698     *
1699     * @param a the array to be searched
1700     * @param key the value to be searched for
1701     * @return index of the search key, if it is contained in the array;
1702     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
1703     *         <i>insertion point</i> is defined as the point at which the
1704     *         key would be inserted into the array: the index of the first
1705     *         element greater than the key, or <tt>a.length</tt> if all
1706     *         elements in the array are less than the specified key.  Note
1707     *         that this guarantees that the return value will be &gt;= 0 if
1708     *         and only if the key is found.
1709     */
1710    public static int binarySearch(long[] a, long key) {
1711        return binarySearch0(a, 0, a.length, key);
1712    }
1713
1714    /**
1715     * Searches a range of
1716     * the specified array of longs for the specified value using the
1717     * binary search algorithm.
1718     * The range must be sorted (as
1719     * by the {@link #sort(long[], int, int)} method)
1720     * prior to making this call.  If it
1721     * is not sorted, the results are undefined.  If the range contains
1722     * multiple elements with the specified value, there is no guarantee which
1723     * one will be found.
1724     *
1725     * @param a the array to be searched
1726     * @param fromIndex the index of the first element (inclusive) to be
1727     *          searched
1728     * @param toIndex the index of the last element (exclusive) to be searched
1729     * @param key the value to be searched for
1730     * @return index of the search key, if it is contained in the array
1731     *         within the specified range;
1732     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
1733     *         <i>insertion point</i> is defined as the point at which the
1734     *         key would be inserted into the array: the index of the first
1735     *         element in the range greater than the key,
1736     *         or <tt>toIndex</tt> if all
1737     *         elements in the range are less than the specified key.  Note
1738     *         that this guarantees that the return value will be &gt;= 0 if
1739     *         and only if the key is found.
1740     * @throws IllegalArgumentException
1741     *         if {@code fromIndex > toIndex}
1742     * @throws ArrayIndexOutOfBoundsException
1743     *         if {@code fromIndex < 0 or toIndex > a.length}
1744     * @since 1.6
1745     */
1746    public static int binarySearch(long[] a, int fromIndex, int toIndex,
1747                                   long key) {
1748        rangeCheck(a.length, fromIndex, toIndex);
1749        return binarySearch0(a, fromIndex, toIndex, key);
1750    }
1751
1752    // Like public version, but without range checks.
1753    private static int binarySearch0(long[] a, int fromIndex, int toIndex,
1754                                     long key) {
1755        int low = fromIndex;
1756        int high = toIndex - 1;
1757
1758        while (low <= high) {
1759            int mid = (low + high) >>> 1;
1760            long midVal = a[mid];
1761
1762            if (midVal < key)
1763                low = mid + 1;
1764            else if (midVal > key)
1765                high = mid - 1;
1766            else
1767                return mid; // key found
1768        }
1769        return -(low + 1);  // key not found.
1770    }
1771
1772    /**
1773     * Searches the specified array of ints for the specified value using the
1774     * binary search algorithm.  The array must be sorted (as
1775     * by the {@link #sort(int[])} method) prior to making this call.  If it
1776     * is not sorted, the results are undefined.  If the array contains
1777     * multiple elements with the specified value, there is no guarantee which
1778     * one will be found.
1779     *
1780     * @param a the array to be searched
1781     * @param key the value to be searched for
1782     * @return index of the search key, if it is contained in the array;
1783     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
1784     *         <i>insertion point</i> is defined as the point at which the
1785     *         key would be inserted into the array: the index of the first
1786     *         element greater than the key, or <tt>a.length</tt> if all
1787     *         elements in the array are less than the specified key.  Note
1788     *         that this guarantees that the return value will be &gt;= 0 if
1789     *         and only if the key is found.
1790     */
1791    public static int binarySearch(int[] a, int key) {
1792        return binarySearch0(a, 0, a.length, key);
1793    }
1794
1795    /**
1796     * Searches a range of
1797     * the specified array of ints for the specified value using the
1798     * binary search algorithm.
1799     * The range must be sorted (as
1800     * by the {@link #sort(int[], int, int)} method)
1801     * prior to making this call.  If it
1802     * is not sorted, the results are undefined.  If the range contains
1803     * multiple elements with the specified value, there is no guarantee which
1804     * one will be found.
1805     *
1806     * @param a the array to be searched
1807     * @param fromIndex the index of the first element (inclusive) to be
1808     *          searched
1809     * @param toIndex the index of the last element (exclusive) to be searched
1810     * @param key the value to be searched for
1811     * @return index of the search key, if it is contained in the array
1812     *         within the specified range;
1813     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
1814     *         <i>insertion point</i> is defined as the point at which the
1815     *         key would be inserted into the array: the index of the first
1816     *         element in the range greater than the key,
1817     *         or <tt>toIndex</tt> if all
1818     *         elements in the range are less than the specified key.  Note
1819     *         that this guarantees that the return value will be &gt;= 0 if
1820     *         and only if the key is found.
1821     * @throws IllegalArgumentException
1822     *         if {@code fromIndex > toIndex}
1823     * @throws ArrayIndexOutOfBoundsException
1824     *         if {@code fromIndex < 0 or toIndex > a.length}
1825     * @since 1.6
1826     */
1827    public static int binarySearch(int[] a, int fromIndex, int toIndex,
1828                                   int key) {
1829        rangeCheck(a.length, fromIndex, toIndex);
1830        return binarySearch0(a, fromIndex, toIndex, key);
1831    }
1832
1833    // Like public version, but without range checks.
1834    private static int binarySearch0(int[] a, int fromIndex, int toIndex,
1835                                     int key) {
1836        int low = fromIndex;
1837        int high = toIndex - 1;
1838
1839        while (low <= high) {
1840            int mid = (low + high) >>> 1;
1841            int midVal = a[mid];
1842
1843            if (midVal < key)
1844                low = mid + 1;
1845            else if (midVal > key)
1846                high = mid - 1;
1847            else
1848                return mid; // key found
1849        }
1850        return -(low + 1);  // key not found.
1851    }
1852
1853    /**
1854     * Searches the specified array of shorts for the specified value using
1855     * the binary search algorithm.  The array must be sorted
1856     * (as by the {@link #sort(short[])} method) prior to making this call.  If
1857     * it is not sorted, the results are undefined.  If the array contains
1858     * multiple elements with the specified value, there is no guarantee which
1859     * one will be found.
1860     *
1861     * @param a the array to be searched
1862     * @param key the value to be searched for
1863     * @return index of the search key, if it is contained in the array;
1864     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
1865     *         <i>insertion point</i> is defined as the point at which the
1866     *         key would be inserted into the array: the index of the first
1867     *         element greater than the key, or <tt>a.length</tt> if all
1868     *         elements in the array are less than the specified key.  Note
1869     *         that this guarantees that the return value will be &gt;= 0 if
1870     *         and only if the key is found.
1871     */
1872    public static int binarySearch(short[] a, short key) {
1873        return binarySearch0(a, 0, a.length, key);
1874    }
1875
1876    /**
1877     * Searches a range of
1878     * the specified array of shorts for the specified value using
1879     * the binary search algorithm.
1880     * The range must be sorted
1881     * (as by the {@link #sort(short[], int, int)} method)
1882     * prior to making this call.  If
1883     * it is not sorted, the results are undefined.  If the range contains
1884     * multiple elements with the specified value, there is no guarantee which
1885     * one will be found.
1886     *
1887     * @param a the array to be searched
1888     * @param fromIndex the index of the first element (inclusive) to be
1889     *          searched
1890     * @param toIndex the index of the last element (exclusive) to be searched
1891     * @param key the value to be searched for
1892     * @return index of the search key, if it is contained in the array
1893     *         within the specified range;
1894     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
1895     *         <i>insertion point</i> is defined as the point at which the
1896     *         key would be inserted into the array: the index of the first
1897     *         element in the range greater than the key,
1898     *         or <tt>toIndex</tt> if all
1899     *         elements in the range are less than the specified key.  Note
1900     *         that this guarantees that the return value will be &gt;= 0 if
1901     *         and only if the key is found.
1902     * @throws IllegalArgumentException
1903     *         if {@code fromIndex > toIndex}
1904     * @throws ArrayIndexOutOfBoundsException
1905     *         if {@code fromIndex < 0 or toIndex > a.length}
1906     * @since 1.6
1907     */
1908    public static int binarySearch(short[] a, int fromIndex, int toIndex,
1909                                   short key) {
1910        rangeCheck(a.length, fromIndex, toIndex);
1911        return binarySearch0(a, fromIndex, toIndex, key);
1912    }
1913
1914    // Like public version, but without range checks.
1915    private static int binarySearch0(short[] a, int fromIndex, int toIndex,
1916                                     short key) {
1917        int low = fromIndex;
1918        int high = toIndex - 1;
1919
1920        while (low <= high) {
1921            int mid = (low + high) >>> 1;
1922            short midVal = a[mid];
1923
1924            if (midVal < key)
1925                low = mid + 1;
1926            else if (midVal > key)
1927                high = mid - 1;
1928            else
1929                return mid; // key found
1930        }
1931        return -(low + 1);  // key not found.
1932    }
1933
1934    /**
1935     * Searches the specified array of chars for the specified value using the
1936     * binary search algorithm.  The array must be sorted (as
1937     * by the {@link #sort(char[])} method) prior to making this call.  If it
1938     * is not sorted, the results are undefined.  If the array contains
1939     * multiple elements with the specified value, there is no guarantee which
1940     * one will be found.
1941     *
1942     * @param a the array to be searched
1943     * @param key the value to be searched for
1944     * @return index of the search key, if it is contained in the array;
1945     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
1946     *         <i>insertion point</i> is defined as the point at which the
1947     *         key would be inserted into the array: the index of the first
1948     *         element greater than the key, or <tt>a.length</tt> if all
1949     *         elements in the array are less than the specified key.  Note
1950     *         that this guarantees that the return value will be &gt;= 0 if
1951     *         and only if the key is found.
1952     */
1953    public static int binarySearch(char[] a, char key) {
1954        return binarySearch0(a, 0, a.length, key);
1955    }
1956
1957    /**
1958     * Searches a range of
1959     * the specified array of chars for the specified value using the
1960     * binary search algorithm.
1961     * The range must be sorted (as
1962     * by the {@link #sort(char[], int, int)} method)
1963     * prior to making this call.  If it
1964     * is not sorted, the results are undefined.  If the range contains
1965     * multiple elements with the specified value, there is no guarantee which
1966     * one will be found.
1967     *
1968     * @param a the array to be searched
1969     * @param fromIndex the index of the first element (inclusive) to be
1970     *          searched
1971     * @param toIndex the index of the last element (exclusive) to be searched
1972     * @param key the value to be searched for
1973     * @return index of the search key, if it is contained in the array
1974     *         within the specified range;
1975     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
1976     *         <i>insertion point</i> is defined as the point at which the
1977     *         key would be inserted into the array: the index of the first
1978     *         element in the range greater than the key,
1979     *         or <tt>toIndex</tt> if all
1980     *         elements in the range are less than the specified key.  Note
1981     *         that this guarantees that the return value will be &gt;= 0 if
1982     *         and only if the key is found.
1983     * @throws IllegalArgumentException
1984     *         if {@code fromIndex > toIndex}
1985     * @throws ArrayIndexOutOfBoundsException
1986     *         if {@code fromIndex < 0 or toIndex > a.length}
1987     * @since 1.6
1988     */
1989    public static int binarySearch(char[] a, int fromIndex, int toIndex,
1990                                   char key) {
1991        rangeCheck(a.length, fromIndex, toIndex);
1992        return binarySearch0(a, fromIndex, toIndex, key);
1993    }
1994
1995    // Like public version, but without range checks.
1996    private static int binarySearch0(char[] a, int fromIndex, int toIndex,
1997                                     char key) {
1998        int low = fromIndex;
1999        int high = toIndex - 1;
2000
2001        while (low <= high) {
2002            int mid = (low + high) >>> 1;
2003            char midVal = a[mid];
2004
2005            if (midVal < key)
2006                low = mid + 1;
2007            else if (midVal > key)
2008                high = mid - 1;
2009            else
2010                return mid; // key found
2011        }
2012        return -(low + 1);  // key not found.
2013    }
2014
2015    /**
2016     * Searches the specified array of bytes for the specified value using the
2017     * binary search algorithm.  The array must be sorted (as
2018     * by the {@link #sort(byte[])} method) prior to making this call.  If it
2019     * is not sorted, the results are undefined.  If the array contains
2020     * multiple elements with the specified value, there is no guarantee which
2021     * one will be found.
2022     *
2023     * @param a the array to be searched
2024     * @param key the value to be searched for
2025     * @return index of the search key, if it is contained in the array;
2026     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
2027     *         <i>insertion point</i> is defined as the point at which the
2028     *         key would be inserted into the array: the index of the first
2029     *         element greater than the key, or <tt>a.length</tt> if all
2030     *         elements in the array are less than the specified key.  Note
2031     *         that this guarantees that the return value will be &gt;= 0 if
2032     *         and only if the key is found.
2033     */
2034    public static int binarySearch(byte[] a, byte key) {
2035        return binarySearch0(a, 0, a.length, key);
2036    }
2037
2038    /**
2039     * Searches a range of
2040     * the specified array of bytes for the specified value using the
2041     * binary search algorithm.
2042     * The range must be sorted (as
2043     * by the {@link #sort(byte[], int, int)} method)
2044     * prior to making this call.  If it
2045     * is not sorted, the results are undefined.  If the range contains
2046     * multiple elements with the specified value, there is no guarantee which
2047     * one will be found.
2048     *
2049     * @param a the array to be searched
2050     * @param fromIndex the index of the first element (inclusive) to be
2051     *          searched
2052     * @param toIndex the index of the last element (exclusive) to be searched
2053     * @param key the value to be searched for
2054     * @return index of the search key, if it is contained in the array
2055     *         within the specified range;
2056     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
2057     *         <i>insertion point</i> is defined as the point at which the
2058     *         key would be inserted into the array: the index of the first
2059     *         element in the range greater than the key,
2060     *         or <tt>toIndex</tt> if all
2061     *         elements in the range are less than the specified key.  Note
2062     *         that this guarantees that the return value will be &gt;= 0 if
2063     *         and only if the key is found.
2064     * @throws IllegalArgumentException
2065     *         if {@code fromIndex > toIndex}
2066     * @throws ArrayIndexOutOfBoundsException
2067     *         if {@code fromIndex < 0 or toIndex > a.length}
2068     * @since 1.6
2069     */
2070    public static int binarySearch(byte[] a, int fromIndex, int toIndex,
2071                                   byte key) {
2072        rangeCheck(a.length, fromIndex, toIndex);
2073        return binarySearch0(a, fromIndex, toIndex, key);
2074    }
2075
2076    // Like public version, but without range checks.
2077    private static int binarySearch0(byte[] a, int fromIndex, int toIndex,
2078                                     byte key) {
2079        int low = fromIndex;
2080        int high = toIndex - 1;
2081
2082        while (low <= high) {
2083            int mid = (low + high) >>> 1;
2084            byte midVal = a[mid];
2085
2086            if (midVal < key)
2087                low = mid + 1;
2088            else if (midVal > key)
2089                high = mid - 1;
2090            else
2091                return mid; // key found
2092        }
2093        return -(low + 1);  // key not found.
2094    }
2095
2096    /**
2097     * Searches the specified array of doubles for the specified value using
2098     * the binary search algorithm.  The array must be sorted
2099     * (as by the {@link #sort(double[])} method) prior to making this call.
2100     * If it is not sorted, the results are undefined.  If the array contains
2101     * multiple elements with the specified value, there is no guarantee which
2102     * one will be found.  This method considers all NaN values to be
2103     * equivalent and equal.
2104     *
2105     * @param a the array to be searched
2106     * @param key the value to be searched for
2107     * @return index of the search key, if it is contained in the array;
2108     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
2109     *         <i>insertion point</i> is defined as the point at which the
2110     *         key would be inserted into the array: the index of the first
2111     *         element greater than the key, or <tt>a.length</tt> if all
2112     *         elements in the array are less than the specified key.  Note
2113     *         that this guarantees that the return value will be &gt;= 0 if
2114     *         and only if the key is found.
2115     */
2116    public static int binarySearch(double[] a, double key) {
2117        return binarySearch0(a, 0, a.length, key);
2118    }
2119
2120    /**
2121     * Searches a range of
2122     * the specified array of doubles for the specified value using
2123     * the binary search algorithm.
2124     * The range must be sorted
2125     * (as by the {@link #sort(double[], int, int)} method)
2126     * prior to making this call.
2127     * If it is not sorted, the results are undefined.  If the range contains
2128     * multiple elements with the specified value, there is no guarantee which
2129     * one will be found.  This method considers all NaN values to be
2130     * equivalent and equal.
2131     *
2132     * @param a the array to be searched
2133     * @param fromIndex the index of the first element (inclusive) to be
2134     *          searched
2135     * @param toIndex the index of the last element (exclusive) to be searched
2136     * @param key the value to be searched for
2137     * @return index of the search key, if it is contained in the array
2138     *         within the specified range;
2139     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
2140     *         <i>insertion point</i> is defined as the point at which the
2141     *         key would be inserted into the array: the index of the first
2142     *         element in the range greater than the key,
2143     *         or <tt>toIndex</tt> if all
2144     *         elements in the range are less than the specified key.  Note
2145     *         that this guarantees that the return value will be &gt;= 0 if
2146     *         and only if the key is found.
2147     * @throws IllegalArgumentException
2148     *         if {@code fromIndex > toIndex}
2149     * @throws ArrayIndexOutOfBoundsException
2150     *         if {@code fromIndex < 0 or toIndex > a.length}
2151     * @since 1.6
2152     */
2153    public static int binarySearch(double[] a, int fromIndex, int toIndex,
2154                                   double key) {
2155        rangeCheck(a.length, fromIndex, toIndex);
2156        return binarySearch0(a, fromIndex, toIndex, key);
2157    }
2158
2159    // Like public version, but without range checks.
2160    private static int binarySearch0(double[] a, int fromIndex, int toIndex,
2161                                     double key) {
2162        int low = fromIndex;
2163        int high = toIndex - 1;
2164
2165        while (low <= high) {
2166            int mid = (low + high) >>> 1;
2167            double midVal = a[mid];
2168
2169            if (midVal < key)
2170                low = mid + 1;  // Neither val is NaN, thisVal is smaller
2171            else if (midVal > key)
2172                high = mid - 1; // Neither val is NaN, thisVal is larger
2173            else {
2174                long midBits = Double.doubleToLongBits(midVal);
2175                long keyBits = Double.doubleToLongBits(key);
2176                if (midBits == keyBits)     // Values are equal
2177                    return mid;             // Key found
2178                else if (midBits < keyBits) // (-0.0, 0.0) or (!NaN, NaN)
2179                    low = mid + 1;
2180                else                        // (0.0, -0.0) or (NaN, !NaN)
2181                    high = mid - 1;
2182            }
2183        }
2184        return -(low + 1);  // key not found.
2185    }
2186
2187    /**
2188     * Searches the specified array of floats for the specified value using
2189     * the binary search algorithm. The array must be sorted
2190     * (as by the {@link #sort(float[])} method) prior to making this call. If
2191     * it is not sorted, the results are undefined. If the array contains
2192     * multiple elements with the specified value, there is no guarantee which
2193     * one will be found. This method considers all NaN values to be
2194     * equivalent and equal.
2195     *
2196     * @param a the array to be searched
2197     * @param key the value to be searched for
2198     * @return index of the search key, if it is contained in the array;
2199     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
2200     *         <i>insertion point</i> is defined as the point at which the
2201     *         key would be inserted into the array: the index of the first
2202     *         element greater than the key, or <tt>a.length</tt> if all
2203     *         elements in the array are less than the specified key. Note
2204     *         that this guarantees that the return value will be &gt;= 0 if
2205     *         and only if the key is found.
2206     */
2207    public static int binarySearch(float[] a, float key) {
2208        return binarySearch0(a, 0, a.length, key);
2209    }
2210
2211    /**
2212     * Searches a range of
2213     * the specified array of floats for the specified value using
2214     * the binary search algorithm.
2215     * The range must be sorted
2216     * (as by the {@link #sort(float[], int, int)} method)
2217     * prior to making this call. If
2218     * it is not sorted, the results are undefined. If the range contains
2219     * multiple elements with the specified value, there is no guarantee which
2220     * one will be found. This method considers all NaN values to be
2221     * equivalent and equal.
2222     *
2223     * @param a the array to be searched
2224     * @param fromIndex the index of the first element (inclusive) to be
2225     *          searched
2226     * @param toIndex the index of the last element (exclusive) to be searched
2227     * @param key the value to be searched for
2228     * @return index of the search key, if it is contained in the array
2229     *         within the specified range;
2230     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
2231     *         <i>insertion point</i> is defined as the point at which the
2232     *         key would be inserted into the array: the index of the first
2233     *         element in the range greater than the key,
2234     *         or <tt>toIndex</tt> if all
2235     *         elements in the range are less than the specified key. Note
2236     *         that this guarantees that the return value will be &gt;= 0 if
2237     *         and only if the key is found.
2238     * @throws IllegalArgumentException
2239     *         if {@code fromIndex > toIndex}
2240     * @throws ArrayIndexOutOfBoundsException
2241     *         if {@code fromIndex < 0 or toIndex > a.length}
2242     * @since 1.6
2243     */
2244    public static int binarySearch(float[] a, int fromIndex, int toIndex,
2245                                   float key) {
2246        rangeCheck(a.length, fromIndex, toIndex);
2247        return binarySearch0(a, fromIndex, toIndex, key);
2248    }
2249
2250    // Like public version, but without range checks.
2251    private static int binarySearch0(float[] a, int fromIndex, int toIndex,
2252                                     float key) {
2253        int low = fromIndex;
2254        int high = toIndex - 1;
2255
2256        while (low <= high) {
2257            int mid = (low + high) >>> 1;
2258            float midVal = a[mid];
2259
2260            if (midVal < key)
2261                low = mid + 1;  // Neither val is NaN, thisVal is smaller
2262            else if (midVal > key)
2263                high = mid - 1; // Neither val is NaN, thisVal is larger
2264            else {
2265                int midBits = Float.floatToIntBits(midVal);
2266                int keyBits = Float.floatToIntBits(key);
2267                if (midBits == keyBits)     // Values are equal
2268                    return mid;             // Key found
2269                else if (midBits < keyBits) // (-0.0, 0.0) or (!NaN, NaN)
2270                    low = mid + 1;
2271                else                        // (0.0, -0.0) or (NaN, !NaN)
2272                    high = mid - 1;
2273            }
2274        }
2275        return -(low + 1);  // key not found.
2276    }
2277
2278    /**
2279     * Searches the specified array for the specified object using the binary
2280     * search algorithm. The array must be sorted into ascending order
2281     * according to the
2282     * {@linkplain Comparable natural ordering}
2283     * of its elements (as by the
2284     * {@link #sort(Object[])} method) prior to making this call.
2285     * If it is not sorted, the results are undefined.
2286     * (If the array contains elements that are not mutually comparable (for
2287     * example, strings and integers), it <i>cannot</i> be sorted according
2288     * to the natural ordering of its elements, hence results are undefined.)
2289     * If the array contains multiple
2290     * elements equal to the specified object, there is no guarantee which
2291     * one will be found.
2292     *
2293     * @param a the array to be searched
2294     * @param key the value to be searched for
2295     * @return index of the search key, if it is contained in the array;
2296     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
2297     *         <i>insertion point</i> is defined as the point at which the
2298     *         key would be inserted into the array: the index of the first
2299     *         element greater than the key, or <tt>a.length</tt> if all
2300     *         elements in the array are less than the specified key.  Note
2301     *         that this guarantees that the return value will be &gt;= 0 if
2302     *         and only if the key is found.
2303     * @throws ClassCastException if the search key is not comparable to the
2304     *         elements of the array.
2305     */
2306    public static int binarySearch(Object[] a, Object key) {
2307        return binarySearch0(a, 0, a.length, key);
2308    }
2309
2310    /**
2311     * Searches a range of
2312     * the specified array for the specified object using the binary
2313     * search algorithm.
2314     * The range must be sorted into ascending order
2315     * according to the
2316     * {@linkplain Comparable natural ordering}
2317     * of its elements (as by the
2318     * {@link #sort(Object[], int, int)} method) prior to making this
2319     * call.  If it is not sorted, the results are undefined.
2320     * (If the range contains elements that are not mutually comparable (for
2321     * example, strings and integers), it <i>cannot</i> be sorted according
2322     * to the natural ordering of its elements, hence results are undefined.)
2323     * If the range contains multiple
2324     * elements equal to the specified object, there is no guarantee which
2325     * one will be found.
2326     *
2327     * @param a the array to be searched
2328     * @param fromIndex the index of the first element (inclusive) to be
2329     *          searched
2330     * @param toIndex the index of the last element (exclusive) to be searched
2331     * @param key the value to be searched for
2332     * @return index of the search key, if it is contained in the array
2333     *         within the specified range;
2334     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
2335     *         <i>insertion point</i> is defined as the point at which the
2336     *         key would be inserted into the array: the index of the first
2337     *         element in the range greater than the key,
2338     *         or <tt>toIndex</tt> if all
2339     *         elements in the range are less than the specified key.  Note
2340     *         that this guarantees that the return value will be &gt;= 0 if
2341     *         and only if the key is found.
2342     * @throws ClassCastException if the search key is not comparable to the
2343     *         elements of the array within the specified range.
2344     * @throws IllegalArgumentException
2345     *         if {@code fromIndex > toIndex}
2346     * @throws ArrayIndexOutOfBoundsException
2347     *         if {@code fromIndex < 0 or toIndex > a.length}
2348     * @since 1.6
2349     */
2350    public static int binarySearch(Object[] a, int fromIndex, int toIndex,
2351                                   Object key) {
2352        rangeCheck(a.length, fromIndex, toIndex);
2353        return binarySearch0(a, fromIndex, toIndex, key);
2354    }
2355
2356    // Like public version, but without range checks.
2357    private static int binarySearch0(Object[] a, int fromIndex, int toIndex,
2358                                     Object key) {
2359        int low = fromIndex;
2360        int high = toIndex - 1;
2361
2362        while (low <= high) {
2363            int mid = (low + high) >>> 1;
2364            @SuppressWarnings("rawtypes")
2365            Comparable midVal = (Comparable)a[mid];
2366            @SuppressWarnings("unchecked")
2367            int cmp = midVal.compareTo(key);
2368
2369            if (cmp < 0)
2370                low = mid + 1;
2371            else if (cmp > 0)
2372                high = mid - 1;
2373            else
2374                return mid; // key found
2375        }
2376        return -(low + 1);  // key not found.
2377    }
2378
2379    /**
2380     * Searches the specified array for the specified object using the binary
2381     * search algorithm.  The array must be sorted into ascending order
2382     * according to the specified comparator (as by the
2383     * {@link #sort(Object[], Comparator) sort(T[], Comparator)}
2384     * method) prior to making this call.  If it is
2385     * not sorted, the results are undefined.
2386     * If the array contains multiple
2387     * elements equal to the specified object, there is no guarantee which one
2388     * will be found.
2389     *
2390     * @param <T> the class of the objects in the array
2391     * @param a the array to be searched
2392     * @param key the value to be searched for
2393     * @param c the comparator by which the array is ordered.  A
2394     *        <tt>null</tt> value indicates that the elements'
2395     *        {@linkplain Comparable natural ordering} should be used.
2396     * @return index of the search key, if it is contained in the array;
2397     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
2398     *         <i>insertion point</i> is defined as the point at which the
2399     *         key would be inserted into the array: the index of the first
2400     *         element greater than the key, or <tt>a.length</tt> if all
2401     *         elements in the array are less than the specified key.  Note
2402     *         that this guarantees that the return value will be &gt;= 0 if
2403     *         and only if the key is found.
2404     * @throws ClassCastException if the array contains elements that are not
2405     *         <i>mutually comparable</i> using the specified comparator,
2406     *         or the search key is not comparable to the
2407     *         elements of the array using this comparator.
2408     */
2409    public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c) {
2410        return binarySearch0(a, 0, a.length, key, c);
2411    }
2412
2413    /**
2414     * Searches a range of
2415     * the specified array for the specified object using the binary
2416     * search algorithm.
2417     * The range must be sorted into ascending order
2418     * according to the specified comparator (as by the
2419     * {@link #sort(Object[], int, int, Comparator)
2420     * sort(T[], int, int, Comparator)}
2421     * method) prior to making this call.
2422     * If it is not sorted, the results are undefined.
2423     * If the range contains multiple elements equal to the specified object,
2424     * there is no guarantee which one will be found.
2425     *
2426     * @param <T> the class of the objects in the array
2427     * @param a the array to be searched
2428     * @param fromIndex the index of the first element (inclusive) to be
2429     *          searched
2430     * @param toIndex the index of the last element (exclusive) to be searched
2431     * @param key the value to be searched for
2432     * @param c the comparator by which the array is ordered.  A
2433     *        <tt>null</tt> value indicates that the elements'
2434     *        {@linkplain Comparable natural ordering} should be used.
2435     * @return index of the search key, if it is contained in the array
2436     *         within the specified range;
2437     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
2438     *         <i>insertion point</i> is defined as the point at which the
2439     *         key would be inserted into the array: the index of the first
2440     *         element in the range greater than the key,
2441     *         or <tt>toIndex</tt> if all
2442     *         elements in the range are less than the specified key.  Note
2443     *         that this guarantees that the return value will be &gt;= 0 if
2444     *         and only if the key is found.
2445     * @throws ClassCastException if the range contains elements that are not
2446     *         <i>mutually comparable</i> using the specified comparator,
2447     *         or the search key is not comparable to the
2448     *         elements in the range using this comparator.
2449     * @throws IllegalArgumentException
2450     *         if {@code fromIndex > toIndex}
2451     * @throws ArrayIndexOutOfBoundsException
2452     *         if {@code fromIndex < 0 or toIndex > a.length}
2453     * @since 1.6
2454     */
2455    public static <T> int binarySearch(T[] a, int fromIndex, int toIndex,
2456                                       T key, Comparator<? super T> c) {
2457        rangeCheck(a.length, fromIndex, toIndex);
2458        return binarySearch0(a, fromIndex, toIndex, key, c);
2459    }
2460
2461    // Like public version, but without range checks.
2462    private static <T> int binarySearch0(T[] a, int fromIndex, int toIndex,
2463                                         T key, Comparator<? super T> c) {
2464        if (c == null) {
2465            return binarySearch0(a, fromIndex, toIndex, key);
2466        }
2467        int low = fromIndex;
2468        int high = toIndex - 1;
2469
2470        while (low <= high) {
2471            int mid = (low + high) >>> 1;
2472            T midVal = a[mid];
2473            int cmp = c.compare(midVal, key);
2474            if (cmp < 0)
2475                low = mid + 1;
2476            else if (cmp > 0)
2477                high = mid - 1;
2478            else
2479                return mid; // key found
2480        }
2481        return -(low + 1);  // key not found.
2482    }
2483
2484    // Equality Testing
2485
2486    /**
2487     * Returns <tt>true</tt> if the two specified arrays of longs are
2488     * <i>equal</i> to one another.  Two arrays are considered equal if both
2489     * arrays contain the same number of elements, and all corresponding pairs
2490     * of elements in the two arrays are equal.  In other words, two arrays
2491     * are equal if they contain the same elements in the same order.  Also,
2492     * two array references are considered equal if both are <tt>null</tt>.<p>
2493     *
2494     * @param a one array to be tested for equality
2495     * @param a2 the other array to be tested for equality
2496     * @return <tt>true</tt> if the two arrays are equal
2497     */
2498    public static boolean equals(long[] a, long[] a2) {
2499        if (a==a2)
2500            return true;
2501        if (a==null || a2==null)
2502            return false;
2503
2504        int length = a.length;
2505        if (a2.length != length)
2506            return false;
2507
2508        for (int i=0; i<length; i++)
2509            if (a[i] != a2[i])
2510                return false;
2511
2512        return true;
2513    }
2514
2515    /**
2516     * Returns <tt>true</tt> if the two specified arrays of ints are
2517     * <i>equal</i> to one another.  Two arrays are considered equal if both
2518     * arrays contain the same number of elements, and all corresponding pairs
2519     * of elements in the two arrays are equal.  In other words, two arrays
2520     * are equal if they contain the same elements in the same order.  Also,
2521     * two array references are considered equal if both are <tt>null</tt>.<p>
2522     *
2523     * @param a one array to be tested for equality
2524     * @param a2 the other array to be tested for equality
2525     * @return <tt>true</tt> if the two arrays are equal
2526     */
2527    public static boolean equals(int[] a, int[] a2) {
2528        if (a==a2)
2529            return true;
2530        if (a==null || a2==null)
2531            return false;
2532
2533        int length = a.length;
2534        if (a2.length != length)
2535            return false;
2536
2537        for (int i=0; i<length; i++)
2538            if (a[i] != a2[i])
2539                return false;
2540
2541        return true;
2542    }
2543
2544    /**
2545     * Returns <tt>true</tt> if the two specified arrays of shorts are
2546     * <i>equal</i> to one another.  Two arrays are considered equal if both
2547     * arrays contain the same number of elements, and all corresponding pairs
2548     * of elements in the two arrays are equal.  In other words, two arrays
2549     * are equal if they contain the same elements in the same order.  Also,
2550     * two array references are considered equal if both are <tt>null</tt>.<p>
2551     *
2552     * @param a one array to be tested for equality
2553     * @param a2 the other array to be tested for equality
2554     * @return <tt>true</tt> if the two arrays are equal
2555     */
2556    public static boolean equals(short[] a, short a2[]) {
2557        if (a==a2)
2558            return true;
2559        if (a==null || a2==null)
2560            return false;
2561
2562        int length = a.length;
2563        if (a2.length != length)
2564            return false;
2565
2566        for (int i=0; i<length; i++)
2567            if (a[i] != a2[i])
2568                return false;
2569
2570        return true;
2571    }
2572
2573    /**
2574     * Returns <tt>true</tt> if the two specified arrays of chars are
2575     * <i>equal</i> to one another.  Two arrays are considered equal if both
2576     * arrays contain the same number of elements, and all corresponding pairs
2577     * of elements in the two arrays are equal.  In other words, two arrays
2578     * are equal if they contain the same elements in the same order.  Also,
2579     * two array references are considered equal if both are <tt>null</tt>.<p>
2580     *
2581     * @param a one array to be tested for equality
2582     * @param a2 the other array to be tested for equality
2583     * @return <tt>true</tt> if the two arrays are equal
2584     */
2585    public static boolean equals(char[] a, char[] a2) {
2586        if (a==a2)
2587            return true;
2588        if (a==null || a2==null)
2589            return false;
2590
2591        int length = a.length;
2592        if (a2.length != length)
2593            return false;
2594
2595        for (int i=0; i<length; i++)
2596            if (a[i] != a2[i])
2597                return false;
2598
2599        return true;
2600    }
2601
2602    /**
2603     * Returns <tt>true</tt> if the two specified arrays of bytes are
2604     * <i>equal</i> to one another.  Two arrays are considered equal if both
2605     * arrays contain the same number of elements, and all corresponding pairs
2606     * of elements in the two arrays are equal.  In other words, two arrays
2607     * are equal if they contain the same elements in the same order.  Also,
2608     * two array references are considered equal if both are <tt>null</tt>.<p>
2609     *
2610     * @param a one array to be tested for equality
2611     * @param a2 the other array to be tested for equality
2612     * @return <tt>true</tt> if the two arrays are equal
2613     */
2614    public static boolean equals(byte[] a, byte[] a2) {
2615        if (a==a2)
2616            return true;
2617        if (a==null || a2==null)
2618            return false;
2619
2620        int length = a.length;
2621        if (a2.length != length)
2622            return false;
2623
2624        for (int i=0; i<length; i++)
2625            if (a[i] != a2[i])
2626                return false;
2627
2628        return true;
2629    }
2630
2631    /**
2632     * Returns <tt>true</tt> if the two specified arrays of booleans are
2633     * <i>equal</i> to one another.  Two arrays are considered equal if both
2634     * arrays contain the same number of elements, and all corresponding pairs
2635     * of elements in the two arrays are equal.  In other words, two arrays
2636     * are equal if they contain the same elements in the same order.  Also,
2637     * two array references are considered equal if both are <tt>null</tt>.<p>
2638     *
2639     * @param a one array to be tested for equality
2640     * @param a2 the other array to be tested for equality
2641     * @return <tt>true</tt> if the two arrays are equal
2642     */
2643    public static boolean equals(boolean[] a, boolean[] a2) {
2644        if (a==a2)
2645            return true;
2646        if (a==null || a2==null)
2647            return false;
2648
2649        int length = a.length;
2650        if (a2.length != length)
2651            return false;
2652
2653        for (int i=0; i<length; i++)
2654            if (a[i] != a2[i])
2655                return false;
2656
2657        return true;
2658    }
2659
2660    /**
2661     * Returns <tt>true</tt> if the two specified arrays of doubles are
2662     * <i>equal</i> to one another.  Two arrays are considered equal if both
2663     * arrays contain the same number of elements, and all corresponding pairs
2664     * of elements in the two arrays are equal.  In other words, two arrays
2665     * are equal if they contain the same elements in the same order.  Also,
2666     * two array references are considered equal if both are <tt>null</tt>.<p>
2667     *
2668     * Two doubles <tt>d1</tt> and <tt>d2</tt> are considered equal if:
2669     * <pre>    <tt>new Double(d1).equals(new Double(d2))</tt></pre>
2670     * (Unlike the <tt>==</tt> operator, this method considers
2671     * <tt>NaN</tt> equals to itself, and 0.0d unequal to -0.0d.)
2672     *
2673     * @param a one array to be tested for equality
2674     * @param a2 the other array to be tested for equality
2675     * @return <tt>true</tt> if the two arrays are equal
2676     * @see Double#equals(Object)
2677     */
2678    public static boolean equals(double[] a, double[] a2) {
2679        if (a==a2)
2680            return true;
2681        if (a==null || a2==null)
2682            return false;
2683
2684        int length = a.length;
2685        if (a2.length != length)
2686            return false;
2687
2688        for (int i=0; i<length; i++)
2689            if (Double.doubleToLongBits(a[i])!=Double.doubleToLongBits(a2[i]))
2690                return false;
2691
2692        return true;
2693    }
2694
2695    /**
2696     * Returns <tt>true</tt> if the two specified arrays of floats are
2697     * <i>equal</i> to one another.  Two arrays are considered equal if both
2698     * arrays contain the same number of elements, and all corresponding pairs
2699     * of elements in the two arrays are equal.  In other words, two arrays
2700     * are equal if they contain the same elements in the same order.  Also,
2701     * two array references are considered equal if both are <tt>null</tt>.<p>
2702     *
2703     * Two floats <tt>f1</tt> and <tt>f2</tt> are considered equal if:
2704     * <pre>    <tt>new Float(f1).equals(new Float(f2))</tt></pre>
2705     * (Unlike the <tt>==</tt> operator, this method considers
2706     * <tt>NaN</tt> equals to itself, and 0.0f unequal to -0.0f.)
2707     *
2708     * @param a one array to be tested for equality
2709     * @param a2 the other array to be tested for equality
2710     * @return <tt>true</tt> if the two arrays are equal
2711     * @see Float#equals(Object)
2712     */
2713    public static boolean equals(float[] a, float[] a2) {
2714        if (a==a2)
2715            return true;
2716        if (a==null || a2==null)
2717            return false;
2718
2719        int length = a.length;
2720        if (a2.length != length)
2721            return false;
2722
2723        for (int i=0; i<length; i++)
2724            if (Float.floatToIntBits(a[i])!=Float.floatToIntBits(a2[i]))
2725                return false;
2726
2727        return true;
2728    }
2729
2730    /**
2731     * Returns <tt>true</tt> if the two specified arrays of Objects are
2732     * <i>equal</i> to one another.  The two arrays are considered equal if
2733     * both arrays contain the same number of elements, and all corresponding
2734     * pairs of elements in the two arrays are equal.  Two objects <tt>e1</tt>
2735     * and <tt>e2</tt> are considered <i>equal</i> if <tt>(e1==null ? e2==null
2736     * : e1.equals(e2))</tt>.  In other words, the two arrays are equal if
2737     * they contain the same elements in the same order.  Also, two array
2738     * references are considered equal if both are <tt>null</tt>.<p>
2739     *
2740     * @param a one array to be tested for equality
2741     * @param a2 the other array to be tested for equality
2742     * @return <tt>true</tt> if the two arrays are equal
2743     */
2744    public static boolean equals(Object[] a, Object[] a2) {
2745        if (a==a2)
2746            return true;
2747        if (a==null || a2==null)
2748            return false;
2749
2750        int length = a.length;
2751        if (a2.length != length)
2752            return false;
2753
2754        for (int i=0; i<length; i++) {
2755            Object o1 = a[i];
2756            Object o2 = a2[i];
2757            if (!(o1==null ? o2==null : o1.equals(o2)))
2758                return false;
2759        }
2760
2761        return true;
2762    }
2763
2764    // Filling
2765
2766    /**
2767     * Assigns the specified long value to each element of the specified array
2768     * of longs.
2769     *
2770     * @param a the array to be filled
2771     * @param val the value to be stored in all elements of the array
2772     */
2773    public static void fill(long[] a, long val) {
2774        for (int i = 0, len = a.length; i < len; i++)
2775            a[i] = val;
2776    }
2777
2778    /**
2779     * Assigns the specified long value to each element of the specified
2780     * range of the specified array of longs.  The range to be filled
2781     * extends from index <tt>fromIndex</tt>, inclusive, to index
2782     * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
2783     * range to be filled is empty.)
2784     *
2785     * @param a the array to be filled
2786     * @param fromIndex the index of the first element (inclusive) to be
2787     *        filled with the specified value
2788     * @param toIndex the index of the last element (exclusive) to be
2789     *        filled with the specified value
2790     * @param val the value to be stored in all elements of the array
2791     * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
2792     * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
2793     *         <tt>toIndex &gt; a.length</tt>
2794     */
2795    public static void fill(long[] a, int fromIndex, int toIndex, long val) {
2796        rangeCheck(a.length, fromIndex, toIndex);
2797        for (int i = fromIndex; i < toIndex; i++)
2798            a[i] = val;
2799    }
2800
2801    /**
2802     * Assigns the specified int value to each element of the specified array
2803     * of ints.
2804     *
2805     * @param a the array to be filled
2806     * @param val the value to be stored in all elements of the array
2807     */
2808    public static void fill(int[] a, int val) {
2809        for (int i = 0, len = a.length; i < len; i++)
2810            a[i] = val;
2811    }
2812
2813    /**
2814     * Assigns the specified int value to each element of the specified
2815     * range of the specified array of ints.  The range to be filled
2816     * extends from index <tt>fromIndex</tt>, inclusive, to index
2817     * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
2818     * range to be filled is empty.)
2819     *
2820     * @param a the array to be filled
2821     * @param fromIndex the index of the first element (inclusive) to be
2822     *        filled with the specified value
2823     * @param toIndex the index of the last element (exclusive) to be
2824     *        filled with the specified value
2825     * @param val the value to be stored in all elements of the array
2826     * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
2827     * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
2828     *         <tt>toIndex &gt; a.length</tt>
2829     */
2830    public static void fill(int[] a, int fromIndex, int toIndex, int val) {
2831        rangeCheck(a.length, fromIndex, toIndex);
2832        for (int i = fromIndex; i < toIndex; i++)
2833            a[i] = val;
2834    }
2835
2836    /**
2837     * Assigns the specified short value to each element of the specified array
2838     * of shorts.
2839     *
2840     * @param a the array to be filled
2841     * @param val the value to be stored in all elements of the array
2842     */
2843    public static void fill(short[] a, short val) {
2844        for (int i = 0, len = a.length; i < len; i++)
2845            a[i] = val;
2846    }
2847
2848    /**
2849     * Assigns the specified short value to each element of the specified
2850     * range of the specified array of shorts.  The range to be filled
2851     * extends from index <tt>fromIndex</tt>, inclusive, to index
2852     * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
2853     * range to be filled is empty.)
2854     *
2855     * @param a the array to be filled
2856     * @param fromIndex the index of the first element (inclusive) to be
2857     *        filled with the specified value
2858     * @param toIndex the index of the last element (exclusive) to be
2859     *        filled with the specified value
2860     * @param val the value to be stored in all elements of the array
2861     * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
2862     * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
2863     *         <tt>toIndex &gt; a.length</tt>
2864     */
2865    public static void fill(short[] a, int fromIndex, int toIndex, short val) {
2866        rangeCheck(a.length, fromIndex, toIndex);
2867        for (int i = fromIndex; i < toIndex; i++)
2868            a[i] = val;
2869    }
2870
2871    /**
2872     * Assigns the specified char value to each element of the specified array
2873     * of chars.
2874     *
2875     * @param a the array to be filled
2876     * @param val the value to be stored in all elements of the array
2877     */
2878    public static void fill(char[] a, char val) {
2879        for (int i = 0, len = a.length; i < len; i++)
2880            a[i] = val;
2881    }
2882
2883    /**
2884     * Assigns the specified char value to each element of the specified
2885     * range of the specified array of chars.  The range to be filled
2886     * extends from index <tt>fromIndex</tt>, inclusive, to index
2887     * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
2888     * range to be filled is empty.)
2889     *
2890     * @param a the array to be filled
2891     * @param fromIndex the index of the first element (inclusive) to be
2892     *        filled with the specified value
2893     * @param toIndex the index of the last element (exclusive) to be
2894     *        filled with the specified value
2895     * @param val the value to be stored in all elements of the array
2896     * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
2897     * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
2898     *         <tt>toIndex &gt; a.length</tt>
2899     */
2900    public static void fill(char[] a, int fromIndex, int toIndex, char val) {
2901        rangeCheck(a.length, fromIndex, toIndex);
2902        for (int i = fromIndex; i < toIndex; i++)
2903            a[i] = val;
2904    }
2905
2906    /**
2907     * Assigns the specified byte value to each element of the specified array
2908     * of bytes.
2909     *
2910     * @param a the array to be filled
2911     * @param val the value to be stored in all elements of the array
2912     */
2913    public static void fill(byte[] a, byte val) {
2914        for (int i = 0, len = a.length; i < len; i++)
2915            a[i] = val;
2916    }
2917
2918    /**
2919     * Assigns the specified byte value to each element of the specified
2920     * range of the specified array of bytes.  The range to be filled
2921     * extends from index <tt>fromIndex</tt>, inclusive, to index
2922     * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
2923     * range to be filled is empty.)
2924     *
2925     * @param a the array to be filled
2926     * @param fromIndex the index of the first element (inclusive) to be
2927     *        filled with the specified value
2928     * @param toIndex the index of the last element (exclusive) to be
2929     *        filled with the specified value
2930     * @param val the value to be stored in all elements of the array
2931     * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
2932     * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
2933     *         <tt>toIndex &gt; a.length</tt>
2934     */
2935    public static void fill(byte[] a, int fromIndex, int toIndex, byte val) {
2936        rangeCheck(a.length, fromIndex, toIndex);
2937        for (int i = fromIndex; i < toIndex; i++)
2938            a[i] = val;
2939    }
2940
2941    /**
2942     * Assigns the specified boolean value to each element of the specified
2943     * array of booleans.
2944     *
2945     * @param a the array to be filled
2946     * @param val the value to be stored in all elements of the array
2947     */
2948    public static void fill(boolean[] a, boolean val) {
2949        for (int i = 0, len = a.length; i < len; i++)
2950            a[i] = val;
2951    }
2952
2953    /**
2954     * Assigns the specified boolean value to each element of the specified
2955     * range of the specified array of booleans.  The range to be filled
2956     * extends from index <tt>fromIndex</tt>, inclusive, to index
2957     * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
2958     * range to be filled is empty.)
2959     *
2960     * @param a the array to be filled
2961     * @param fromIndex the index of the first element (inclusive) to be
2962     *        filled with the specified value
2963     * @param toIndex the index of the last element (exclusive) to be
2964     *        filled with the specified value
2965     * @param val the value to be stored in all elements of the array
2966     * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
2967     * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
2968     *         <tt>toIndex &gt; a.length</tt>
2969     */
2970    public static void fill(boolean[] a, int fromIndex, int toIndex,
2971                            boolean val) {
2972        rangeCheck(a.length, fromIndex, toIndex);
2973        for (int i = fromIndex; i < toIndex; i++)
2974            a[i] = val;
2975    }
2976
2977    /**
2978     * Assigns the specified double value to each element of the specified
2979     * array of doubles.
2980     *
2981     * @param a the array to be filled
2982     * @param val the value to be stored in all elements of the array
2983     */
2984    public static void fill(double[] a, double val) {
2985        for (int i = 0, len = a.length; i < len; i++)
2986            a[i] = val;
2987    }
2988
2989    /**
2990     * Assigns the specified double value to each element of the specified
2991     * range of the specified array of doubles.  The range to be filled
2992     * extends from index <tt>fromIndex</tt>, inclusive, to index
2993     * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
2994     * range to be filled is empty.)
2995     *
2996     * @param a the array to be filled
2997     * @param fromIndex the index of the first element (inclusive) to be
2998     *        filled with the specified value
2999     * @param toIndex the index of the last element (exclusive) to be
3000     *        filled with the specified value
3001     * @param val the value to be stored in all elements of the array
3002     * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
3003     * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
3004     *         <tt>toIndex &gt; a.length</tt>
3005     */
3006    public static void fill(double[] a, int fromIndex, int toIndex,double val){
3007        rangeCheck(a.length, fromIndex, toIndex);
3008        for (int i = fromIndex; i < toIndex; i++)
3009            a[i] = val;
3010    }
3011
3012    /**
3013     * Assigns the specified float value to each element of the specified array
3014     * of floats.
3015     *
3016     * @param a the array to be filled
3017     * @param val the value to be stored in all elements of the array
3018     */
3019    public static void fill(float[] a, float val) {
3020        for (int i = 0, len = a.length; i < len; i++)
3021            a[i] = val;
3022    }
3023
3024    /**
3025     * Assigns the specified float value to each element of the specified
3026     * range of the specified array of floats.  The range to be filled
3027     * extends from index <tt>fromIndex</tt>, inclusive, to index
3028     * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
3029     * range to be filled is empty.)
3030     *
3031     * @param a the array to be filled
3032     * @param fromIndex the index of the first element (inclusive) to be
3033     *        filled with the specified value
3034     * @param toIndex the index of the last element (exclusive) to be
3035     *        filled with the specified value
3036     * @param val the value to be stored in all elements of the array
3037     * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
3038     * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
3039     *         <tt>toIndex &gt; a.length</tt>
3040     */
3041    public static void fill(float[] a, int fromIndex, int toIndex, float val) {
3042        rangeCheck(a.length, fromIndex, toIndex);
3043        for (int i = fromIndex; i < toIndex; i++)
3044            a[i] = val;
3045    }
3046
3047    /**
3048     * Assigns the specified Object reference to each element of the specified
3049     * array of Objects.
3050     *
3051     * @param a the array to be filled
3052     * @param val the value to be stored in all elements of the array
3053     * @throws ArrayStoreException if the specified value is not of a
3054     *         runtime type that can be stored in the specified array
3055     */
3056    public static void fill(Object[] a, Object val) {
3057        for (int i = 0, len = a.length; i < len; i++)
3058            a[i] = val;
3059    }
3060
3061    /**
3062     * Assigns the specified Object reference to each element of the specified
3063     * range of the specified array of Objects.  The range to be filled
3064     * extends from index <tt>fromIndex</tt>, inclusive, to index
3065     * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
3066     * range to be filled is empty.)
3067     *
3068     * @param a the array to be filled
3069     * @param fromIndex the index of the first element (inclusive) to be
3070     *        filled with the specified value
3071     * @param toIndex the index of the last element (exclusive) to be
3072     *        filled with the specified value
3073     * @param val the value to be stored in all elements of the array
3074     * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
3075     * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
3076     *         <tt>toIndex &gt; a.length</tt>
3077     * @throws ArrayStoreException if the specified value is not of a
3078     *         runtime type that can be stored in the specified array
3079     */
3080    public static void fill(Object[] a, int fromIndex, int toIndex, Object val) {
3081        rangeCheck(a.length, fromIndex, toIndex);
3082        for (int i = fromIndex; i < toIndex; i++)
3083            a[i] = val;
3084    }
3085
3086    // Cloning
3087
3088    /**
3089     * Copies the specified array, truncating or padding with nulls (if necessary)
3090     * so the copy has the specified length.  For all indices that are
3091     * valid in both the original array and the copy, the two arrays will
3092     * contain identical values.  For any indices that are valid in the
3093     * copy but not the original, the copy will contain <tt>null</tt>.
3094     * Such indices will exist if and only if the specified length
3095     * is greater than that of the original array.
3096     * The resulting array is of exactly the same class as the original array.
3097     *
3098     * @param <T> the class of the objects in the array
3099     * @param original the array to be copied
3100     * @param newLength the length of the copy to be returned
3101     * @return a copy of the original array, truncated or padded with nulls
3102     *     to obtain the specified length
3103     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
3104     * @throws NullPointerException if <tt>original</tt> is null
3105     * @since 1.6
3106     */
3107    @SuppressWarnings("unchecked")
3108    public static <T> T[] copyOf(T[] original, int newLength) {
3109        return (T[]) copyOf(original, newLength, original.getClass());
3110    }
3111
3112    /**
3113     * Copies the specified array, truncating or padding with nulls (if necessary)
3114     * so the copy has the specified length.  For all indices that are
3115     * valid in both the original array and the copy, the two arrays will
3116     * contain identical values.  For any indices that are valid in the
3117     * copy but not the original, the copy will contain <tt>null</tt>.
3118     * Such indices will exist if and only if the specified length
3119     * is greater than that of the original array.
3120     * The resulting array is of the class <tt>newType</tt>.
3121     *
3122     * @param <U> the class of the objects in the original array
3123     * @param <T> the class of the objects in the returned array
3124     * @param original the array to be copied
3125     * @param newLength the length of the copy to be returned
3126     * @param newType the class of the copy to be returned
3127     * @return a copy of the original array, truncated or padded with nulls
3128     *     to obtain the specified length
3129     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
3130     * @throws NullPointerException if <tt>original</tt> is null
3131     * @throws ArrayStoreException if an element copied from
3132     *     <tt>original</tt> is not of a runtime type that can be stored in
3133     *     an array of class <tt>newType</tt>
3134     * @since 1.6
3135     */
3136    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
3137        @SuppressWarnings("unchecked")
3138        T[] copy = ((Object)newType == (Object)Object[].class)
3139            ? (T[]) new Object[newLength]
3140            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
3141        System.arraycopy(original, 0, copy, 0,
3142                         Math.min(original.length, newLength));
3143        return copy;
3144    }
3145
3146    /**
3147     * Copies the specified array, truncating or padding with zeros (if necessary)
3148     * so the copy has the specified length.  For all indices that are
3149     * valid in both the original array and the copy, the two arrays will
3150     * contain identical values.  For any indices that are valid in the
3151     * copy but not the original, the copy will contain <tt>(byte)0</tt>.
3152     * Such indices will exist if and only if the specified length
3153     * is greater than that of the original array.
3154     *
3155     * @param original the array to be copied
3156     * @param newLength the length of the copy to be returned
3157     * @return a copy of the original array, truncated or padded with zeros
3158     *     to obtain the specified length
3159     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
3160     * @throws NullPointerException if <tt>original</tt> is null
3161     * @since 1.6
3162     */
3163    public static byte[] copyOf(byte[] original, int newLength) {
3164        byte[] copy = new byte[newLength];
3165        System.arraycopy(original, 0, copy, 0,
3166                         Math.min(original.length, newLength));
3167        return copy;
3168    }
3169
3170    /**
3171     * Copies the specified array, truncating or padding with zeros (if necessary)
3172     * so the copy has the specified length.  For all indices that are
3173     * valid in both the original array and the copy, the two arrays will
3174     * contain identical values.  For any indices that are valid in the
3175     * copy but not the original, the copy will contain <tt>(short)0</tt>.
3176     * Such indices will exist if and only if the specified length
3177     * is greater than that of the original array.
3178     *
3179     * @param original the array to be copied
3180     * @param newLength the length of the copy to be returned
3181     * @return a copy of the original array, truncated or padded with zeros
3182     *     to obtain the specified length
3183     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
3184     * @throws NullPointerException if <tt>original</tt> is null
3185     * @since 1.6
3186     */
3187    public static short[] copyOf(short[] original, int newLength) {
3188        short[] copy = new short[newLength];
3189        System.arraycopy(original, 0, copy, 0,
3190                         Math.min(original.length, newLength));
3191        return copy;
3192    }
3193
3194    /**
3195     * Copies the specified array, truncating or padding with zeros (if necessary)
3196     * so the copy has the specified length.  For all indices that are
3197     * valid in both the original array and the copy, the two arrays will
3198     * contain identical values.  For any indices that are valid in the
3199     * copy but not the original, the copy will contain <tt>0</tt>.
3200     * Such indices will exist if and only if the specified length
3201     * is greater than that of the original array.
3202     *
3203     * @param original the array to be copied
3204     * @param newLength the length of the copy to be returned
3205     * @return a copy of the original array, truncated or padded with zeros
3206     *     to obtain the specified length
3207     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
3208     * @throws NullPointerException if <tt>original</tt> is null
3209     * @since 1.6
3210     */
3211    public static int[] copyOf(int[] original, int newLength) {
3212        int[] copy = new int[newLength];
3213        System.arraycopy(original, 0, copy, 0,
3214                         Math.min(original.length, newLength));
3215        return copy;
3216    }
3217
3218    /**
3219     * Copies the specified array, truncating or padding with zeros (if necessary)
3220     * so the copy has the specified length.  For all indices that are
3221     * valid in both the original array and the copy, the two arrays will
3222     * contain identical values.  For any indices that are valid in the
3223     * copy but not the original, the copy will contain <tt>0L</tt>.
3224     * Such indices will exist if and only if the specified length
3225     * is greater than that of the original array.
3226     *
3227     * @param original the array to be copied
3228     * @param newLength the length of the copy to be returned
3229     * @return a copy of the original array, truncated or padded with zeros
3230     *     to obtain the specified length
3231     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
3232     * @throws NullPointerException if <tt>original</tt> is null
3233     * @since 1.6
3234     */
3235    public static long[] copyOf(long[] original, int newLength) {
3236        long[] copy = new long[newLength];
3237        System.arraycopy(original, 0, copy, 0,
3238                         Math.min(original.length, newLength));
3239        return copy;
3240    }
3241
3242    /**
3243     * Copies the specified array, truncating or padding with null characters (if necessary)
3244     * so the copy has the specified length.  For all indices that are valid
3245     * in both the original array and the copy, the two arrays will contain
3246     * identical values.  For any indices that are valid in the copy but not
3247     * the original, the copy will contain <tt>'\\u000'</tt>.  Such indices
3248     * will exist if and only if the specified length is greater than that of
3249     * the original array.
3250     *
3251     * @param original the array to be copied
3252     * @param newLength the length of the copy to be returned
3253     * @return a copy of the original array, truncated or padded with null characters
3254     *     to obtain the specified length
3255     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
3256     * @throws NullPointerException if <tt>original</tt> is null
3257     * @since 1.6
3258     */
3259    public static char[] copyOf(char[] original, int newLength) {
3260        char[] copy = new char[newLength];
3261        System.arraycopy(original, 0, copy, 0,
3262                         Math.min(original.length, newLength));
3263        return copy;
3264    }
3265
3266    /**
3267     * Copies the specified array, truncating or padding with zeros (if necessary)
3268     * so the copy has the specified length.  For all indices that are
3269     * valid in both the original array and the copy, the two arrays will
3270     * contain identical values.  For any indices that are valid in the
3271     * copy but not the original, the copy will contain <tt>0f</tt>.
3272     * Such indices will exist if and only if the specified length
3273     * is greater than that of the original array.
3274     *
3275     * @param original the array to be copied
3276     * @param newLength the length of the copy to be returned
3277     * @return a copy of the original array, truncated or padded with zeros
3278     *     to obtain the specified length
3279     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
3280     * @throws NullPointerException if <tt>original</tt> is null
3281     * @since 1.6
3282     */
3283    public static float[] copyOf(float[] original, int newLength) {
3284        float[] copy = new float[newLength];
3285        System.arraycopy(original, 0, copy, 0,
3286                         Math.min(original.length, newLength));
3287        return copy;
3288    }
3289
3290    /**
3291     * Copies the specified array, truncating or padding with zeros (if necessary)
3292     * so the copy has the specified length.  For all indices that are
3293     * valid in both the original array and the copy, the two arrays will
3294     * contain identical values.  For any indices that are valid in the
3295     * copy but not the original, the copy will contain <tt>0d</tt>.
3296     * Such indices will exist if and only if the specified length
3297     * is greater than that of the original array.
3298     *
3299     * @param original the array to be copied
3300     * @param newLength the length of the copy to be returned
3301     * @return a copy of the original array, truncated or padded with zeros
3302     *     to obtain the specified length
3303     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
3304     * @throws NullPointerException if <tt>original</tt> is null
3305     * @since 1.6
3306     */
3307    public static double[] copyOf(double[] original, int newLength) {
3308        double[] copy = new double[newLength];
3309        System.arraycopy(original, 0, copy, 0,
3310                         Math.min(original.length, newLength));
3311        return copy;
3312    }
3313
3314    /**
3315     * Copies the specified array, truncating or padding with <tt>false</tt> (if necessary)
3316     * so the copy has the specified length.  For all indices that are
3317     * valid in both the original array and the copy, the two arrays will
3318     * contain identical values.  For any indices that are valid in the
3319     * copy but not the original, the copy will contain <tt>false</tt>.
3320     * Such indices will exist if and only if the specified length
3321     * is greater than that of the original array.
3322     *
3323     * @param original the array to be copied
3324     * @param newLength the length of the copy to be returned
3325     * @return a copy of the original array, truncated or padded with false elements
3326     *     to obtain the specified length
3327     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
3328     * @throws NullPointerException if <tt>original</tt> is null
3329     * @since 1.6
3330     */
3331    public static boolean[] copyOf(boolean[] original, int newLength) {
3332        boolean[] copy = new boolean[newLength];
3333        System.arraycopy(original, 0, copy, 0,
3334                         Math.min(original.length, newLength));
3335        return copy;
3336    }
3337
3338    /**
3339     * Copies the specified range of the specified array into a new array.
3340     * The initial index of the range (<tt>from</tt>) must lie between zero
3341     * and <tt>original.length</tt>, inclusive.  The value at
3342     * <tt>original[from]</tt> is placed into the initial element of the copy
3343     * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
3344     * Values from subsequent elements in the original array are placed into
3345     * subsequent elements in the copy.  The final index of the range
3346     * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
3347     * may be greater than <tt>original.length</tt>, in which case
3348     * <tt>null</tt> is placed in all elements of the copy whose index is
3349     * greater than or equal to <tt>original.length - from</tt>.  The length
3350     * of the returned array will be <tt>to - from</tt>.
3351     * <p>
3352     * The resulting array is of exactly the same class as the original array.
3353     *
3354     * @param <T> the class of the objects in the array
3355     * @param original the array from which a range is to be copied
3356     * @param from the initial index of the range to be copied, inclusive
3357     * @param to the final index of the range to be copied, exclusive.
3358     *     (This index may lie outside the array.)
3359     * @return a new array containing the specified range from the original array,
3360     *     truncated or padded with nulls to obtain the required length
3361     * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
3362     *     or {@code from > original.length}
3363     * @throws IllegalArgumentException if <tt>from &gt; to</tt>
3364     * @throws NullPointerException if <tt>original</tt> is null
3365     * @since 1.6
3366     */
3367    @SuppressWarnings("unchecked")
3368    public static <T> T[] copyOfRange(T[] original, int from, int to) {
3369        return copyOfRange(original, from, to, (Class<? extends T[]>) original.getClass());
3370    }
3371
3372    /**
3373     * Copies the specified range of the specified array into a new array.
3374     * The initial index of the range (<tt>from</tt>) must lie between zero
3375     * and <tt>original.length</tt>, inclusive.  The value at
3376     * <tt>original[from]</tt> is placed into the initial element of the copy
3377     * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
3378     * Values from subsequent elements in the original array are placed into
3379     * subsequent elements in the copy.  The final index of the range
3380     * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
3381     * may be greater than <tt>original.length</tt>, in which case
3382     * <tt>null</tt> is placed in all elements of the copy whose index is
3383     * greater than or equal to <tt>original.length - from</tt>.  The length
3384     * of the returned array will be <tt>to - from</tt>.
3385     * The resulting array is of the class <tt>newType</tt>.
3386     *
3387     * @param <U> the class of the objects in the original array
3388     * @param <T> the class of the objects in the returned array
3389     * @param original the array from which a range is to be copied
3390     * @param from the initial index of the range to be copied, inclusive
3391     * @param to the final index of the range to be copied, exclusive.
3392     *     (This index may lie outside the array.)
3393     * @param newType the class of the copy to be returned
3394     * @return a new array containing the specified range from the original array,
3395     *     truncated or padded with nulls to obtain the required length
3396     * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
3397     *     or {@code from > original.length}
3398     * @throws IllegalArgumentException if <tt>from &gt; to</tt>
3399     * @throws NullPointerException if <tt>original</tt> is null
3400     * @throws ArrayStoreException if an element copied from
3401     *     <tt>original</tt> is not of a runtime type that can be stored in
3402     *     an array of class <tt>newType</tt>.
3403     * @since 1.6
3404     */
3405    public static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {
3406        int newLength = to - from;
3407        if (newLength < 0)
3408            throw new IllegalArgumentException(from + " > " + to);
3409        @SuppressWarnings("unchecked")
3410        T[] copy = ((Object)newType == (Object)Object[].class)
3411            ? (T[]) new Object[newLength]
3412            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
3413        System.arraycopy(original, from, copy, 0,
3414                         Math.min(original.length - from, newLength));
3415        return copy;
3416    }
3417
3418    /**
3419     * Copies the specified range of the specified array into a new array.
3420     * The initial index of the range (<tt>from</tt>) must lie between zero
3421     * and <tt>original.length</tt>, inclusive.  The value at
3422     * <tt>original[from]</tt> is placed into the initial element of the copy
3423     * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
3424     * Values from subsequent elements in the original array are placed into
3425     * subsequent elements in the copy.  The final index of the range
3426     * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
3427     * may be greater than <tt>original.length</tt>, in which case
3428     * <tt>(byte)0</tt> is placed in all elements of the copy whose index is
3429     * greater than or equal to <tt>original.length - from</tt>.  The length
3430     * of the returned array will be <tt>to - from</tt>.
3431     *
3432     * @param original the array from which a range is to be copied
3433     * @param from the initial index of the range to be copied, inclusive
3434     * @param to the final index of the range to be copied, exclusive.
3435     *     (This index may lie outside the array.)
3436     * @return a new array containing the specified range from the original array,
3437     *     truncated or padded with zeros to obtain the required length
3438     * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
3439     *     or {@code from > original.length}
3440     * @throws IllegalArgumentException if <tt>from &gt; to</tt>
3441     * @throws NullPointerException if <tt>original</tt> is null
3442     * @since 1.6
3443     */
3444    public static byte[] copyOfRange(byte[] original, int from, int to) {
3445        int newLength = to - from;
3446        if (newLength < 0)
3447            throw new IllegalArgumentException(from + " > " + to);
3448        byte[] copy = new byte[newLength];
3449        System.arraycopy(original, from, copy, 0,
3450                         Math.min(original.length - from, newLength));
3451        return copy;
3452    }
3453
3454    /**
3455     * Copies the specified range of the specified array into a new array.
3456     * The initial index of the range (<tt>from</tt>) must lie between zero
3457     * and <tt>original.length</tt>, inclusive.  The value at
3458     * <tt>original[from]</tt> is placed into the initial element of the copy
3459     * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
3460     * Values from subsequent elements in the original array are placed into
3461     * subsequent elements in the copy.  The final index of the range
3462     * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
3463     * may be greater than <tt>original.length</tt>, in which case
3464     * <tt>(short)0</tt> is placed in all elements of the copy whose index is
3465     * greater than or equal to <tt>original.length - from</tt>.  The length
3466     * of the returned array will be <tt>to - from</tt>.
3467     *
3468     * @param original the array from which a range is to be copied
3469     * @param from the initial index of the range to be copied, inclusive
3470     * @param to the final index of the range to be copied, exclusive.
3471     *     (This index may lie outside the array.)
3472     * @return a new array containing the specified range from the original array,
3473     *     truncated or padded with zeros to obtain the required length
3474     * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
3475     *     or {@code from > original.length}
3476     * @throws IllegalArgumentException if <tt>from &gt; to</tt>
3477     * @throws NullPointerException if <tt>original</tt> is null
3478     * @since 1.6
3479     */
3480    public static short[] copyOfRange(short[] original, int from, int to) {
3481        int newLength = to - from;
3482        if (newLength < 0)
3483            throw new IllegalArgumentException(from + " > " + to);
3484        short[] copy = new short[newLength];
3485        System.arraycopy(original, from, copy, 0,
3486                         Math.min(original.length - from, newLength));
3487        return copy;
3488    }
3489
3490    /**
3491     * Copies the specified range of the specified array into a new array.
3492     * The initial index of the range (<tt>from</tt>) must lie between zero
3493     * and <tt>original.length</tt>, inclusive.  The value at
3494     * <tt>original[from]</tt> is placed into the initial element of the copy
3495     * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
3496     * Values from subsequent elements in the original array are placed into
3497     * subsequent elements in the copy.  The final index of the range
3498     * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
3499     * may be greater than <tt>original.length</tt>, in which case
3500     * <tt>0</tt> is placed in all elements of the copy whose index is
3501     * greater than or equal to <tt>original.length - from</tt>.  The length
3502     * of the returned array will be <tt>to - from</tt>.
3503     *
3504     * @param original the array from which a range is to be copied
3505     * @param from the initial index of the range to be copied, inclusive
3506     * @param to the final index of the range to be copied, exclusive.
3507     *     (This index may lie outside the array.)
3508     * @return a new array containing the specified range from the original array,
3509     *     truncated or padded with zeros to obtain the required length
3510     * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
3511     *     or {@code from > original.length}
3512     * @throws IllegalArgumentException if <tt>from &gt; to</tt>
3513     * @throws NullPointerException if <tt>original</tt> is null
3514     * @since 1.6
3515     */
3516    public static int[] copyOfRange(int[] original, int from, int to) {
3517        int newLength = to - from;
3518        if (newLength < 0)
3519            throw new IllegalArgumentException(from + " > " + to);
3520        int[] copy = new int[newLength];
3521        System.arraycopy(original, from, copy, 0,
3522                         Math.min(original.length - from, newLength));
3523        return copy;
3524    }
3525
3526    /**
3527     * Copies the specified range of the specified array into a new array.
3528     * The initial index of the range (<tt>from</tt>) must lie between zero
3529     * and <tt>original.length</tt>, inclusive.  The value at
3530     * <tt>original[from]</tt> is placed into the initial element of the copy
3531     * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
3532     * Values from subsequent elements in the original array are placed into
3533     * subsequent elements in the copy.  The final index of the range
3534     * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
3535     * may be greater than <tt>original.length</tt>, in which case
3536     * <tt>0L</tt> is placed in all elements of the copy whose index is
3537     * greater than or equal to <tt>original.length - from</tt>.  The length
3538     * of the returned array will be <tt>to - from</tt>.
3539     *
3540     * @param original the array from which a range is to be copied
3541     * @param from the initial index of the range to be copied, inclusive
3542     * @param to the final index of the range to be copied, exclusive.
3543     *     (This index may lie outside the array.)
3544     * @return a new array containing the specified range from the original array,
3545     *     truncated or padded with zeros to obtain the required length
3546     * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
3547     *     or {@code from > original.length}
3548     * @throws IllegalArgumentException if <tt>from &gt; to</tt>
3549     * @throws NullPointerException if <tt>original</tt> is null
3550     * @since 1.6
3551     */
3552    public static long[] copyOfRange(long[] original, int from, int to) {
3553        int newLength = to - from;
3554        if (newLength < 0)
3555            throw new IllegalArgumentException(from + " > " + to);
3556        long[] copy = new long[newLength];
3557        System.arraycopy(original, from, copy, 0,
3558                         Math.min(original.length - from, newLength));
3559        return copy;
3560    }
3561
3562    /**
3563     * Copies the specified range of the specified array into a new array.
3564     * The initial index of the range (<tt>from</tt>) must lie between zero
3565     * and <tt>original.length</tt>, inclusive.  The value at
3566     * <tt>original[from]</tt> is placed into the initial element of the copy
3567     * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
3568     * Values from subsequent elements in the original array are placed into
3569     * subsequent elements in the copy.  The final index of the range
3570     * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
3571     * may be greater than <tt>original.length</tt>, in which case
3572     * <tt>'\\u000'</tt> is placed in all elements of the copy whose index is
3573     * greater than or equal to <tt>original.length - from</tt>.  The length
3574     * of the returned array will be <tt>to - from</tt>.
3575     *
3576     * @param original the array from which a range is to be copied
3577     * @param from the initial index of the range to be copied, inclusive
3578     * @param to the final index of the range to be copied, exclusive.
3579     *     (This index may lie outside the array.)
3580     * @return a new array containing the specified range from the original array,
3581     *     truncated or padded with null characters to obtain the required length
3582     * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
3583     *     or {@code from > original.length}
3584     * @throws IllegalArgumentException if <tt>from &gt; to</tt>
3585     * @throws NullPointerException if <tt>original</tt> is null
3586     * @since 1.6
3587     */
3588    public static char[] copyOfRange(char[] original, int from, int to) {
3589        int newLength = to - from;
3590        if (newLength < 0)
3591            throw new IllegalArgumentException(from + " > " + to);
3592        char[] copy = new char[newLength];
3593        System.arraycopy(original, from, copy, 0,
3594                         Math.min(original.length - from, newLength));
3595        return copy;
3596    }
3597
3598    /**
3599     * Copies the specified range of the specified array into a new array.
3600     * The initial index of the range (<tt>from</tt>) must lie between zero
3601     * and <tt>original.length</tt>, inclusive.  The value at
3602     * <tt>original[from]</tt> is placed into the initial element of the copy
3603     * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
3604     * Values from subsequent elements in the original array are placed into
3605     * subsequent elements in the copy.  The final index of the range
3606     * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
3607     * may be greater than <tt>original.length</tt>, in which case
3608     * <tt>0f</tt> is placed in all elements of the copy whose index is
3609     * greater than or equal to <tt>original.length - from</tt>.  The length
3610     * of the returned array will be <tt>to - from</tt>.
3611     *
3612     * @param original the array from which a range is to be copied
3613     * @param from the initial index of the range to be copied, inclusive
3614     * @param to the final index of the range to be copied, exclusive.
3615     *     (This index may lie outside the array.)
3616     * @return a new array containing the specified range from the original array,
3617     *     truncated or padded with zeros to obtain the required length
3618     * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
3619     *     or {@code from > original.length}
3620     * @throws IllegalArgumentException if <tt>from &gt; to</tt>
3621     * @throws NullPointerException if <tt>original</tt> is null
3622     * @since 1.6
3623     */
3624    public static float[] copyOfRange(float[] original, int from, int to) {
3625        int newLength = to - from;
3626        if (newLength < 0)
3627            throw new IllegalArgumentException(from + " > " + to);
3628        float[] copy = new float[newLength];
3629        System.arraycopy(original, from, copy, 0,
3630                         Math.min(original.length - from, newLength));
3631        return copy;
3632    }
3633
3634    /**
3635     * Copies the specified range of the specified array into a new array.
3636     * The initial index of the range (<tt>from</tt>) must lie between zero
3637     * and <tt>original.length</tt>, inclusive.  The value at
3638     * <tt>original[from]</tt> is placed into the initial element of the copy
3639     * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
3640     * Values from subsequent elements in the original array are placed into
3641     * subsequent elements in the copy.  The final index of the range
3642     * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
3643     * may be greater than <tt>original.length</tt>, in which case
3644     * <tt>0d</tt> is placed in all elements of the copy whose index is
3645     * greater than or equal to <tt>original.length - from</tt>.  The length
3646     * of the returned array will be <tt>to - from</tt>.
3647     *
3648     * @param original the array from which a range is to be copied
3649     * @param from the initial index of the range to be copied, inclusive
3650     * @param to the final index of the range to be copied, exclusive.
3651     *     (This index may lie outside the array.)
3652     * @return a new array containing the specified range from the original array,
3653     *     truncated or padded with zeros to obtain the required length
3654     * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
3655     *     or {@code from > original.length}
3656     * @throws IllegalArgumentException if <tt>from &gt; to</tt>
3657     * @throws NullPointerException if <tt>original</tt> is null
3658     * @since 1.6
3659     */
3660    public static double[] copyOfRange(double[] original, int from, int to) {
3661        int newLength = to - from;
3662        if (newLength < 0)
3663            throw new IllegalArgumentException(from + " > " + to);
3664        double[] copy = new double[newLength];
3665        System.arraycopy(original, from, copy, 0,
3666                         Math.min(original.length - from, newLength));
3667        return copy;
3668    }
3669
3670    /**
3671     * Copies the specified range of the specified array into a new array.
3672     * The initial index of the range (<tt>from</tt>) must lie between zero
3673     * and <tt>original.length</tt>, inclusive.  The value at
3674     * <tt>original[from]</tt> is placed into the initial element of the copy
3675     * (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
3676     * Values from subsequent elements in the original array are placed into
3677     * subsequent elements in the copy.  The final index of the range
3678     * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
3679     * may be greater than <tt>original.length</tt>, in which case
3680     * <tt>false</tt> is placed in all elements of the copy whose index is
3681     * greater than or equal to <tt>original.length - from</tt>.  The length
3682     * of the returned array will be <tt>to - from</tt>.
3683     *
3684     * @param original the array from which a range is to be copied
3685     * @param from the initial index of the range to be copied, inclusive
3686     * @param to the final index of the range to be copied, exclusive.
3687     *     (This index may lie outside the array.)
3688     * @return a new array containing the specified range from the original array,
3689     *     truncated or padded with false elements to obtain the required length
3690     * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
3691     *     or {@code from > original.length}
3692     * @throws IllegalArgumentException if <tt>from &gt; to</tt>
3693     * @throws NullPointerException if <tt>original</tt> is null
3694     * @since 1.6
3695     */
3696    public static boolean[] copyOfRange(boolean[] original, int from, int to) {
3697        int newLength = to - from;
3698        if (newLength < 0)
3699            throw new IllegalArgumentException(from + " > " + to);
3700        boolean[] copy = new boolean[newLength];
3701        System.arraycopy(original, from, copy, 0,
3702                         Math.min(original.length - from, newLength));
3703        return copy;
3704    }
3705
3706    // Misc
3707
3708    /**
3709     * Returns a fixed-size list backed by the specified array.  (Changes to
3710     * the returned list "write through" to the array.)  This method acts
3711     * as bridge between array-based and collection-based APIs, in
3712     * combination with {@link Collection#toArray}.  The returned list is
3713     * serializable and implements {@link RandomAccess}.
3714     *
3715     * <p>This method also provides a convenient way to create a fixed-size
3716     * list initialized to contain several elements:
3717     * <pre>
3718     *     List&lt;String&gt; stooges = Arrays.asList("Larry", "Moe", "Curly");
3719     * </pre>
3720     *
3721     * @param <T> the class of the objects in the array
3722     * @param a the array by which the list will be backed
3723     * @return a list view of the specified array
3724     */
3725    @SafeVarargs
3726    @SuppressWarnings("varargs")
3727    public static <T> List<T> asList(T... a) {
3728        return new ArrayList<>(a);
3729    }
3730
3731    /**
3732     * @serial include
3733     */
3734    private static class ArrayList<E> extends AbstractList<E>
3735        implements RandomAccess, java.io.Serializable
3736    {
3737        private static final long serialVersionUID = -2764017481108945198L;
3738        private final E[] a;
3739
3740        ArrayList(E[] array) {
3741            a = Objects.requireNonNull(array);
3742        }
3743
3744        @Override
3745        public int size() {
3746            return a.length;
3747        }
3748
3749        @Override
3750        public Object[] toArray() {
3751            return a.clone();
3752        }
3753
3754        @Override
3755        @SuppressWarnings("unchecked")
3756        public <T> T[] toArray(T[] a) {
3757            int size = size();
3758            if (a.length < size)
3759                return Arrays.copyOf(this.a, size,
3760                                     (Class<? extends T[]>) a.getClass());
3761            System.arraycopy(this.a, 0, a, 0, size);
3762            if (a.length > size)
3763                a[size] = null;
3764            return a;
3765        }
3766
3767        @Override
3768        public E get(int index) {
3769            return a[index];
3770        }
3771
3772        @Override
3773        public E set(int index, E element) {
3774            E oldValue = a[index];
3775            a[index] = element;
3776            return oldValue;
3777        }
3778
3779        @Override
3780        public int indexOf(Object o) {
3781            E[] a = this.a;
3782            if (o == null) {
3783                for (int i = 0; i < a.length; i++)
3784                    if (a[i] == null)
3785                        return i;
3786            } else {
3787                for (int i = 0; i < a.length; i++)
3788                    if (o.equals(a[i]))
3789                        return i;
3790            }
3791            return -1;
3792        }
3793
3794        @Override
3795        public boolean contains(Object o) {
3796            return indexOf(o) != -1;
3797        }
3798
3799        @Override
3800        public Spliterator<E> spliterator() {
3801            return Spliterators.spliterator(a, Spliterator.ORDERED);
3802        }
3803
3804        @Override
3805        public void forEach(Consumer<? super E> action) {
3806            Objects.requireNonNull(action);
3807            for (E e : a) {
3808                action.accept(e);
3809            }
3810        }
3811
3812        @Override
3813        public void replaceAll(UnaryOperator<E> operator) {
3814            Objects.requireNonNull(operator);
3815            E[] a = this.a;
3816            for (int i = 0; i < a.length; i++) {
3817                a[i] = operator.apply(a[i]);
3818            }
3819        }
3820
3821        @Override
3822        public void sort(Comparator<? super E> c) {
3823            Arrays.sort(a, c);
3824        }
3825    }
3826
3827    /**
3828     * Returns a hash code based on the contents of the specified array.
3829     * For any two <tt>long</tt> arrays <tt>a</tt> and <tt>b</tt>
3830     * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
3831     * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
3832     *
3833     * <p>The value returned by this method is the same value that would be
3834     * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
3835     * method on a {@link List} containing a sequence of {@link Long}
3836     * instances representing the elements of <tt>a</tt> in the same order.
3837     * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
3838     *
3839     * @param a the array whose hash value to compute
3840     * @return a content-based hash code for <tt>a</tt>
3841     * @since 1.5
3842     */
3843    public static int hashCode(long a[]) {
3844        if (a == null)
3845            return 0;
3846
3847        int result = 1;
3848        for (long element : a) {
3849            int elementHash = (int)(element ^ (element >>> 32));
3850            result = 31 * result + elementHash;
3851        }
3852
3853        return result;
3854    }
3855
3856    /**
3857     * Returns a hash code based on the contents of the specified array.
3858     * For any two non-null <tt>int</tt> arrays <tt>a</tt> and <tt>b</tt>
3859     * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
3860     * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
3861     *
3862     * <p>The value returned by this method is the same value that would be
3863     * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
3864     * method on a {@link List} containing a sequence of {@link Integer}
3865     * instances representing the elements of <tt>a</tt> in the same order.
3866     * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
3867     *
3868     * @param a the array whose hash value to compute
3869     * @return a content-based hash code for <tt>a</tt>
3870     * @since 1.5
3871     */
3872    public static int hashCode(int a[]) {
3873        if (a == null)
3874            return 0;
3875
3876        int result = 1;
3877        for (int element : a)
3878            result = 31 * result + element;
3879
3880        return result;
3881    }
3882
3883    /**
3884     * Returns a hash code based on the contents of the specified array.
3885     * For any two <tt>short</tt> arrays <tt>a</tt> and <tt>b</tt>
3886     * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
3887     * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
3888     *
3889     * <p>The value returned by this method is the same value that would be
3890     * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
3891     * method on a {@link List} containing a sequence of {@link Short}
3892     * instances representing the elements of <tt>a</tt> in the same order.
3893     * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
3894     *
3895     * @param a the array whose hash value to compute
3896     * @return a content-based hash code for <tt>a</tt>
3897     * @since 1.5
3898     */
3899    public static int hashCode(short a[]) {
3900        if (a == null)
3901            return 0;
3902
3903        int result = 1;
3904        for (short element : a)
3905            result = 31 * result + element;
3906
3907        return result;
3908    }
3909
3910    /**
3911     * Returns a hash code based on the contents of the specified array.
3912     * For any two <tt>char</tt> arrays <tt>a</tt> and <tt>b</tt>
3913     * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
3914     * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
3915     *
3916     * <p>The value returned by this method is the same value that would be
3917     * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
3918     * method on a {@link List} containing a sequence of {@link Character}
3919     * instances representing the elements of <tt>a</tt> in the same order.
3920     * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
3921     *
3922     * @param a the array whose hash value to compute
3923     * @return a content-based hash code for <tt>a</tt>
3924     * @since 1.5
3925     */
3926    public static int hashCode(char a[]) {
3927        if (a == null)
3928            return 0;
3929
3930        int result = 1;
3931        for (char element : a)
3932            result = 31 * result + element;
3933
3934        return result;
3935    }
3936
3937    /**
3938     * Returns a hash code based on the contents of the specified array.
3939     * For any two <tt>byte</tt> arrays <tt>a</tt> and <tt>b</tt>
3940     * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
3941     * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
3942     *
3943     * <p>The value returned by this method is the same value that would be
3944     * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
3945     * method on a {@link List} containing a sequence of {@link Byte}
3946     * instances representing the elements of <tt>a</tt> in the same order.
3947     * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
3948     *
3949     * @param a the array whose hash value to compute
3950     * @return a content-based hash code for <tt>a</tt>
3951     * @since 1.5
3952     */
3953    public static int hashCode(byte a[]) {
3954        if (a == null)
3955            return 0;
3956
3957        int result = 1;
3958        for (byte element : a)
3959            result = 31 * result + element;
3960
3961        return result;
3962    }
3963
3964    /**
3965     * Returns a hash code based on the contents of the specified array.
3966     * For any two <tt>boolean</tt> arrays <tt>a</tt> and <tt>b</tt>
3967     * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
3968     * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
3969     *
3970     * <p>The value returned by this method is the same value that would be
3971     * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
3972     * method on a {@link List} containing a sequence of {@link Boolean}
3973     * instances representing the elements of <tt>a</tt> in the same order.
3974     * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
3975     *
3976     * @param a the array whose hash value to compute
3977     * @return a content-based hash code for <tt>a</tt>
3978     * @since 1.5
3979     */
3980    public static int hashCode(boolean a[]) {
3981        if (a == null)
3982            return 0;
3983
3984        int result = 1;
3985        for (boolean element : a)
3986            result = 31 * result + (element ? 1231 : 1237);
3987
3988        return result;
3989    }
3990
3991    /**
3992     * Returns a hash code based on the contents of the specified array.
3993     * For any two <tt>float</tt> arrays <tt>a</tt> and <tt>b</tt>
3994     * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
3995     * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
3996     *
3997     * <p>The value returned by this method is the same value that would be
3998     * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
3999     * method on a {@link List} containing a sequence of {@link Float}
4000     * instances representing the elements of <tt>a</tt> in the same order.
4001     * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
4002     *
4003     * @param a the array whose hash value to compute
4004     * @return a content-based hash code for <tt>a</tt>
4005     * @since 1.5
4006     */
4007    public static int hashCode(float a[]) {
4008        if (a == null)
4009            return 0;
4010
4011        int result = 1;
4012        for (float element : a)
4013            result = 31 * result + Float.floatToIntBits(element);
4014
4015        return result;
4016    }
4017
4018    /**
4019     * Returns a hash code based on the contents of the specified array.
4020     * For any two <tt>double</tt> arrays <tt>a</tt> and <tt>b</tt>
4021     * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that
4022     * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
4023     *
4024     * <p>The value returned by this method is the same value that would be
4025     * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}
4026     * method on a {@link List} containing a sequence of {@link Double}
4027     * instances representing the elements of <tt>a</tt> in the same order.
4028     * If <tt>a</tt> is <tt>null</tt>, this method returns 0.
4029     *
4030     * @param a the array whose hash value to compute
4031     * @return a content-based hash code for <tt>a</tt>
4032     * @since 1.5
4033     */
4034    public static int hashCode(double a[]) {
4035        if (a == null)
4036            return 0;
4037
4038        int result = 1;
4039        for (double element : a) {
4040            long bits = Double.doubleToLongBits(element);
4041            result = 31 * result + (int)(bits ^ (bits >>> 32));
4042        }
4043        return result;
4044    }
4045
4046    /**
4047     * Returns a hash code based on the contents of the specified array.  If
4048     * the array contains other arrays as elements, the hash code is based on
4049     * their identities rather than their contents.  It is therefore
4050     * acceptable to invoke this method on an array that contains itself as an
4051     * element,  either directly or indirectly through one or more levels of
4052     * arrays.
4053     *
4054     * <p>For any two arrays <tt>a</tt> and <tt>b</tt> such that
4055     * <tt>Arrays.equals(a, b)</tt>, it is also the case that
4056     * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.
4057     *
4058     * <p>The value returned by this method is equal to the value that would
4059     * be returned by <tt>Arrays.asList(a).hashCode()</tt>, unless <tt>a</tt>
4060     * is <tt>null</tt>, in which case <tt>0</tt> is returned.
4061     *
4062     * @param a the array whose content-based hash code to compute
4063     * @return a content-based hash code for <tt>a</tt>
4064     * @see #deepHashCode(Object[])
4065     * @since 1.5
4066     */
4067    public static int hashCode(Object a[]) {
4068        if (a == null)
4069            return 0;
4070
4071        int result = 1;
4072
4073        for (Object element : a)
4074            result = 31 * result + (element == null ? 0 : element.hashCode());
4075
4076        return result;
4077    }
4078
4079    /**
4080     * Returns a hash code based on the "deep contents" of the specified
4081     * array.  If the array contains other arrays as elements, the
4082     * hash code is based on their contents and so on, ad infinitum.
4083     * It is therefore unacceptable to invoke this method on an array that
4084     * contains itself as an element, either directly or indirectly through
4085     * one or more levels of arrays.  The behavior of such an invocation is
4086     * undefined.
4087     *
4088     * <p>For any two arrays <tt>a</tt> and <tt>b</tt> such that
4089     * <tt>Arrays.deepEquals(a, b)</tt>, it is also the case that
4090     * <tt>Arrays.deepHashCode(a) == Arrays.deepHashCode(b)</tt>.
4091     *
4092     * <p>The computation of the value returned by this method is similar to
4093     * that of the value returned by {@link List#hashCode()} on a list
4094     * containing the same elements as <tt>a</tt> in the same order, with one
4095     * difference: If an element <tt>e</tt> of <tt>a</tt> is itself an array,
4096     * its hash code is computed not by calling <tt>e.hashCode()</tt>, but as
4097     * by calling the appropriate overloading of <tt>Arrays.hashCode(e)</tt>
4098     * if <tt>e</tt> is an array of a primitive type, or as by calling
4099     * <tt>Arrays.deepHashCode(e)</tt> recursively if <tt>e</tt> is an array
4100     * of a reference type.  If <tt>a</tt> is <tt>null</tt>, this method
4101     * returns 0.
4102     *
4103     * @param a the array whose deep-content-based hash code to compute
4104     * @return a deep-content-based hash code for <tt>a</tt>
4105     * @see #hashCode(Object[])
4106     * @since 1.5
4107     */
4108    public static int deepHashCode(Object a[]) {
4109        if (a == null)
4110            return 0;
4111
4112        int result = 1;
4113
4114        for (Object element : a) {
4115            int elementHash = 0;
4116            // BEGIN Android-changed: getComponentType() is faster than instanceof()
4117            if (element != null) {
4118                Class<?> cl = element.getClass().getComponentType();
4119                if (cl == null)
4120                    elementHash = element.hashCode();
4121                else if (element instanceof Object[])
4122                    elementHash = deepHashCode((Object[]) element);
4123                else if (cl == byte.class)
4124                    elementHash = hashCode((byte[]) element);
4125                else if (cl == short.class)
4126                    elementHash = hashCode((short[]) element);
4127                else if (cl == int.class)
4128                    elementHash = hashCode((int[]) element);
4129                else if (cl == long.class)
4130                    elementHash = hashCode((long[]) element);
4131                else if (cl == char.class)
4132                    elementHash = hashCode((char[]) element);
4133                else if (cl == float.class)
4134                    elementHash = hashCode((float[]) element);
4135                else if (cl == double.class)
4136                    elementHash = hashCode((double[]) element);
4137                else if (cl == boolean.class)
4138                    elementHash = hashCode((boolean[]) element);
4139                else
4140                    elementHash = element.hashCode();
4141            }
4142            // END Android-changed: getComponentType() is faster than instanceof()
4143            result = 31 * result + elementHash;
4144        }
4145
4146        return result;
4147    }
4148
4149    /**
4150     * Returns <tt>true</tt> if the two specified arrays are <i>deeply
4151     * equal</i> to one another.  Unlike the {@link #equals(Object[],Object[])}
4152     * method, this method is appropriate for use with nested arrays of
4153     * arbitrary depth.
4154     *
4155     * <p>Two array references are considered deeply equal if both
4156     * are <tt>null</tt>, or if they refer to arrays that contain the same
4157     * number of elements and all corresponding pairs of elements in the two
4158     * arrays are deeply equal.
4159     *
4160     * <p>Two possibly <tt>null</tt> elements <tt>e1</tt> and <tt>e2</tt> are
4161     * deeply equal if any of the following conditions hold:
4162     * <ul>
4163     *    <li> <tt>e1</tt> and <tt>e2</tt> are both arrays of object reference
4164     *         types, and <tt>Arrays.deepEquals(e1, e2) would return true</tt>
4165     *    <li> <tt>e1</tt> and <tt>e2</tt> are arrays of the same primitive
4166     *         type, and the appropriate overloading of
4167     *         <tt>Arrays.equals(e1, e2)</tt> would return true.
4168     *    <li> <tt>e1 == e2</tt>
4169     *    <li> <tt>e1.equals(e2)</tt> would return true.
4170     * </ul>
4171     * Note that this definition permits <tt>null</tt> elements at any depth.
4172     *
4173     * <p>If either of the specified arrays contain themselves as elements
4174     * either directly or indirectly through one or more levels of arrays,
4175     * the behavior of this method is undefined.
4176     *
4177     * @param a1 one array to be tested for equality
4178     * @param a2 the other array to be tested for equality
4179     * @return <tt>true</tt> if the two arrays are equal
4180     * @see #equals(Object[],Object[])
4181     * @see Objects#deepEquals(Object, Object)
4182     * @since 1.5
4183     */
4184    public static boolean deepEquals(Object[] a1, Object[] a2) {
4185        if (a1 == a2)
4186            return true;
4187        if (a1 == null || a2==null)
4188            return false;
4189        int length = a1.length;
4190        if (a2.length != length)
4191            return false;
4192
4193        for (int i = 0; i < length; i++) {
4194            Object e1 = a1[i];
4195            Object e2 = a2[i];
4196
4197            if (e1 == e2)
4198                continue;
4199            // Android-changed: Return early if e2 == null
4200            if (e1 == null || e2 == null)
4201                return false;
4202
4203            // Figure out whether the two elements are equal
4204            boolean eq = deepEquals0(e1, e2);
4205
4206            if (!eq)
4207                return false;
4208        }
4209        return true;
4210    }
4211
4212    static boolean deepEquals0(Object e1, Object e2) {
4213        // BEGIN Android-changed: getComponentType() is faster than instanceof()
4214        Class<?> cl1 = e1.getClass().getComponentType();
4215        Class<?> cl2 = e2.getClass().getComponentType();
4216
4217        if (cl1 != cl2) {
4218            return false;
4219        }
4220        if (e1 instanceof Object[])
4221            return deepEquals ((Object[]) e1, (Object[]) e2);
4222        else if (cl1 == byte.class)
4223            return equals((byte[]) e1, (byte[]) e2);
4224        else if (cl1 == short.class)
4225            return equals((short[]) e1, (short[]) e2);
4226        else if (cl1 == int.class)
4227            return equals((int[]) e1, (int[]) e2);
4228        else if (cl1 == long.class)
4229            return equals((long[]) e1, (long[]) e2);
4230        else if (cl1 == char.class)
4231            return equals((char[]) e1, (char[]) e2);
4232        else if (cl1 == float.class)
4233            return equals((float[]) e1, (float[]) e2);
4234        else if (cl1 == double.class)
4235            return equals((double[]) e1, (double[]) e2);
4236        else if (cl1 == boolean.class)
4237            return equals((boolean[]) e1, (boolean[]) e2);
4238        else
4239            return e1.equals(e2);
4240        // END Android-changed: getComponentType() is faster than instanceof()
4241    }
4242
4243    /**
4244     * Returns a string representation of the contents of the specified array.
4245     * The string representation consists of a list of the array's elements,
4246     * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are
4247     * separated by the characters <tt>", "</tt> (a comma followed by a
4248     * space).  Elements are converted to strings as by
4249     * <tt>String.valueOf(long)</tt>.  Returns <tt>"null"</tt> if <tt>a</tt>
4250     * is <tt>null</tt>.
4251     *
4252     * @param a the array whose string representation to return
4253     * @return a string representation of <tt>a</tt>
4254     * @since 1.5
4255     */
4256    public static String toString(long[] a) {
4257        if (a == null)
4258            return "null";
4259        int iMax = a.length - 1;
4260        if (iMax == -1)
4261            return "[]";
4262
4263        StringBuilder b = new StringBuilder();
4264        b.append('[');
4265        for (int i = 0; ; i++) {
4266            b.append(a[i]);
4267            if (i == iMax)
4268                return b.append(']').toString();
4269            b.append(", ");
4270        }
4271    }
4272
4273    /**
4274     * Returns a string representation of the contents of the specified array.
4275     * The string representation consists of a list of the array's elements,
4276     * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are
4277     * separated by the characters <tt>", "</tt> (a comma followed by a
4278     * space).  Elements are converted to strings as by
4279     * <tt>String.valueOf(int)</tt>.  Returns <tt>"null"</tt> if <tt>a</tt> is
4280     * <tt>null</tt>.
4281     *
4282     * @param a the array whose string representation to return
4283     * @return a string representation of <tt>a</tt>
4284     * @since 1.5
4285     */
4286    public static String toString(int[] a) {
4287        if (a == null)
4288            return "null";
4289        int iMax = a.length - 1;
4290        if (iMax == -1)
4291            return "[]";
4292
4293        StringBuilder b = new StringBuilder();
4294        b.append('[');
4295        for (int i = 0; ; i++) {
4296            b.append(a[i]);
4297            if (i == iMax)
4298                return b.append(']').toString();
4299            b.append(", ");
4300        }
4301    }
4302
4303    /**
4304     * Returns a string representation of the contents of the specified array.
4305     * The string representation consists of a list of the array's elements,
4306     * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are
4307     * separated by the characters <tt>", "</tt> (a comma followed by a
4308     * space).  Elements are converted to strings as by
4309     * <tt>String.valueOf(short)</tt>.  Returns <tt>"null"</tt> if <tt>a</tt>
4310     * is <tt>null</tt>.
4311     *
4312     * @param a the array whose string representation to return
4313     * @return a string representation of <tt>a</tt>
4314     * @since 1.5
4315     */
4316    public static String toString(short[] a) {
4317        if (a == null)
4318            return "null";
4319        int iMax = a.length - 1;
4320        if (iMax == -1)
4321            return "[]";
4322
4323        StringBuilder b = new StringBuilder();
4324        b.append('[');
4325        for (int i = 0; ; i++) {
4326            b.append(a[i]);
4327            if (i == iMax)
4328                return b.append(']').toString();
4329            b.append(", ");
4330        }
4331    }
4332
4333    /**
4334     * Returns a string representation of the contents of the specified array.
4335     * The string representation consists of a list of the array's elements,
4336     * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are
4337     * separated by the characters <tt>", "</tt> (a comma followed by a
4338     * space).  Elements are converted to strings as by
4339     * <tt>String.valueOf(char)</tt>.  Returns <tt>"null"</tt> if <tt>a</tt>
4340     * is <tt>null</tt>.
4341     *
4342     * @param a the array whose string representation to return
4343     * @return a string representation of <tt>a</tt>
4344     * @since 1.5
4345     */
4346    public static String toString(char[] a) {
4347        if (a == null)
4348            return "null";
4349        int iMax = a.length - 1;
4350        if (iMax == -1)
4351            return "[]";
4352
4353        StringBuilder b = new StringBuilder();
4354        b.append('[');
4355        for (int i = 0; ; i++) {
4356            b.append(a[i]);
4357            if (i == iMax)
4358                return b.append(']').toString();
4359            b.append(", ");
4360        }
4361    }
4362
4363    /**
4364     * Returns a string representation of the contents of the specified array.
4365     * The string representation consists of a list of the array's elements,
4366     * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements
4367     * are separated by the characters <tt>", "</tt> (a comma followed
4368     * by a space).  Elements are converted to strings as by
4369     * <tt>String.valueOf(byte)</tt>.  Returns <tt>"null"</tt> if
4370     * <tt>a</tt> is <tt>null</tt>.
4371     *
4372     * @param a the array whose string representation to return
4373     * @return a string representation of <tt>a</tt>
4374     * @since 1.5
4375     */
4376    public static String toString(byte[] a) {
4377        if (a == null)
4378            return "null";
4379        int iMax = a.length - 1;
4380        if (iMax == -1)
4381            return "[]";
4382
4383        StringBuilder b = new StringBuilder();
4384        b.append('[');
4385        for (int i = 0; ; i++) {
4386            b.append(a[i]);
4387            if (i == iMax)
4388                return b.append(']').toString();
4389            b.append(", ");
4390        }
4391    }
4392
4393    /**
4394     * Returns a string representation of the contents of the specified array.
4395     * The string representation consists of a list of the array's elements,
4396     * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are
4397     * separated by the characters <tt>", "</tt> (a comma followed by a
4398     * space).  Elements are converted to strings as by
4399     * <tt>String.valueOf(boolean)</tt>.  Returns <tt>"null"</tt> if
4400     * <tt>a</tt> is <tt>null</tt>.
4401     *
4402     * @param a the array whose string representation to return
4403     * @return a string representation of <tt>a</tt>
4404     * @since 1.5
4405     */
4406    public static String toString(boolean[] a) {
4407        if (a == null)
4408            return "null";
4409        int iMax = a.length - 1;
4410        if (iMax == -1)
4411            return "[]";
4412
4413        StringBuilder b = new StringBuilder();
4414        b.append('[');
4415        for (int i = 0; ; i++) {
4416            b.append(a[i]);
4417            if (i == iMax)
4418                return b.append(']').toString();
4419            b.append(", ");
4420        }
4421    }
4422
4423    /**
4424     * Returns a string representation of the contents of the specified array.
4425     * The string representation consists of a list of the array's elements,
4426     * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are
4427     * separated by the characters <tt>", "</tt> (a comma followed by a
4428     * space).  Elements are converted to strings as by
4429     * <tt>String.valueOf(float)</tt>.  Returns <tt>"null"</tt> if <tt>a</tt>
4430     * is <tt>null</tt>.
4431     *
4432     * @param a the array whose string representation to return
4433     * @return a string representation of <tt>a</tt>
4434     * @since 1.5
4435     */
4436    public static String toString(float[] a) {
4437        if (a == null)
4438            return "null";
4439
4440        int iMax = a.length - 1;
4441        if (iMax == -1)
4442            return "[]";
4443
4444        StringBuilder b = new StringBuilder();
4445        b.append('[');
4446        for (int i = 0; ; i++) {
4447            b.append(a[i]);
4448            if (i == iMax)
4449                return b.append(']').toString();
4450            b.append(", ");
4451        }
4452    }
4453
4454    /**
4455     * Returns a string representation of the contents of the specified array.
4456     * The string representation consists of a list of the array's elements,
4457     * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are
4458     * separated by the characters <tt>", "</tt> (a comma followed by a
4459     * space).  Elements are converted to strings as by
4460     * <tt>String.valueOf(double)</tt>.  Returns <tt>"null"</tt> if <tt>a</tt>
4461     * is <tt>null</tt>.
4462     *
4463     * @param a the array whose string representation to return
4464     * @return a string representation of <tt>a</tt>
4465     * @since 1.5
4466     */
4467    public static String toString(double[] a) {
4468        if (a == null)
4469            return "null";
4470        int iMax = a.length - 1;
4471        if (iMax == -1)
4472            return "[]";
4473
4474        StringBuilder b = new StringBuilder();
4475        b.append('[');
4476        for (int i = 0; ; i++) {
4477            b.append(a[i]);
4478            if (i == iMax)
4479                return b.append(']').toString();
4480            b.append(", ");
4481        }
4482    }
4483
4484    /**
4485     * Returns a string representation of the contents of the specified array.
4486     * If the array contains other arrays as elements, they are converted to
4487     * strings by the {@link Object#toString} method inherited from
4488     * <tt>Object</tt>, which describes their <i>identities</i> rather than
4489     * their contents.
4490     *
4491     * <p>The value returned by this method is equal to the value that would
4492     * be returned by <tt>Arrays.asList(a).toString()</tt>, unless <tt>a</tt>
4493     * is <tt>null</tt>, in which case <tt>"null"</tt> is returned.
4494     *
4495     * @param a the array whose string representation to return
4496     * @return a string representation of <tt>a</tt>
4497     * @see #deepToString(Object[])
4498     * @since 1.5
4499     */
4500    public static String toString(Object[] a) {
4501        if (a == null)
4502            return "null";
4503
4504        int iMax = a.length - 1;
4505        if (iMax == -1)
4506            return "[]";
4507
4508        StringBuilder b = new StringBuilder();
4509        b.append('[');
4510        for (int i = 0; ; i++) {
4511            b.append(String.valueOf(a[i]));
4512            if (i == iMax)
4513                return b.append(']').toString();
4514            b.append(", ");
4515        }
4516    }
4517
4518    /**
4519     * Returns a string representation of the "deep contents" of the specified
4520     * array.  If the array contains other arrays as elements, the string
4521     * representation contains their contents and so on.  This method is
4522     * designed for converting multidimensional arrays to strings.
4523     *
4524     * <p>The string representation consists of a list of the array's
4525     * elements, enclosed in square brackets (<tt>"[]"</tt>).  Adjacent
4526     * elements are separated by the characters <tt>", "</tt> (a comma
4527     * followed by a space).  Elements are converted to strings as by
4528     * <tt>String.valueOf(Object)</tt>, unless they are themselves
4529     * arrays.
4530     *
4531     * <p>If an element <tt>e</tt> is an array of a primitive type, it is
4532     * converted to a string as by invoking the appropriate overloading of
4533     * <tt>Arrays.toString(e)</tt>.  If an element <tt>e</tt> is an array of a
4534     * reference type, it is converted to a string as by invoking
4535     * this method recursively.
4536     *
4537     * <p>To avoid infinite recursion, if the specified array contains itself
4538     * as an element, or contains an indirect reference to itself through one
4539     * or more levels of arrays, the self-reference is converted to the string
4540     * <tt>"[...]"</tt>.  For example, an array containing only a reference
4541     * to itself would be rendered as <tt>"[[...]]"</tt>.
4542     *
4543     * <p>This method returns <tt>"null"</tt> if the specified array
4544     * is <tt>null</tt>.
4545     *
4546     * @param a the array whose string representation to return
4547     * @return a string representation of <tt>a</tt>
4548     * @see #toString(Object[])
4549     * @since 1.5
4550     */
4551    public static String deepToString(Object[] a) {
4552        if (a == null)
4553            return "null";
4554
4555        int bufLen = 20 * a.length;
4556        if (a.length != 0 && bufLen <= 0)
4557            bufLen = Integer.MAX_VALUE;
4558        StringBuilder buf = new StringBuilder(bufLen);
4559        deepToString(a, buf, new HashSet<Object[]>());
4560        return buf.toString();
4561    }
4562
4563    private static void deepToString(Object[] a, StringBuilder buf,
4564                                     Set<Object[]> dejaVu) {
4565        if (a == null) {
4566            buf.append("null");
4567            return;
4568        }
4569        int iMax = a.length - 1;
4570        if (iMax == -1) {
4571            buf.append("[]");
4572            return;
4573        }
4574
4575        dejaVu.add(a);
4576        buf.append('[');
4577        for (int i = 0; ; i++) {
4578
4579            Object element = a[i];
4580            if (element == null) {
4581                buf.append("null");
4582            } else {
4583                Class<?> eClass = element.getClass();
4584
4585                if (eClass.isArray()) {
4586                    if (eClass == byte[].class)
4587                        buf.append(toString((byte[]) element));
4588                    else if (eClass == short[].class)
4589                        buf.append(toString((short[]) element));
4590                    else if (eClass == int[].class)
4591                        buf.append(toString((int[]) element));
4592                    else if (eClass == long[].class)
4593                        buf.append(toString((long[]) element));
4594                    else if (eClass == char[].class)
4595                        buf.append(toString((char[]) element));
4596                    else if (eClass == float[].class)
4597                        buf.append(toString((float[]) element));
4598                    else if (eClass == double[].class)
4599                        buf.append(toString((double[]) element));
4600                    else if (eClass == boolean[].class)
4601                        buf.append(toString((boolean[]) element));
4602                    else { // element is an array of object references
4603                        if (dejaVu.contains(element))
4604                            buf.append("[...]");
4605                        else
4606                            deepToString((Object[])element, buf, dejaVu);
4607                    }
4608                } else {  // element is non-null and not an array
4609                    buf.append(element.toString());
4610                }
4611            }
4612            if (i == iMax)
4613                break;
4614            buf.append(", ");
4615        }
4616        buf.append(']');
4617        dejaVu.remove(a);
4618    }
4619
4620
4621    /**
4622     * Set all elements of the specified array, using the provided
4623     * generator function to compute each element.
4624     *
4625     * <p>If the generator function throws an exception, it is relayed to
4626     * the caller and the array is left in an indeterminate state.
4627     *
4628     * @param <T> type of elements of the array
4629     * @param array array to be initialized
4630     * @param generator a function accepting an index and producing the desired
4631     *        value for that position
4632     * @throws NullPointerException if the generator is null
4633     * @since 1.8
4634     */
4635    public static <T> void setAll(T[] array, IntFunction<? extends T> generator) {
4636        Objects.requireNonNull(generator);
4637        for (int i = 0; i < array.length; i++)
4638            array[i] = generator.apply(i);
4639    }
4640
4641    /**
4642     * Set all elements of the specified array, in parallel, using the
4643     * provided generator function to compute each element.
4644     *
4645     * <p>If the generator function throws an exception, an unchecked exception
4646     * is thrown from {@code parallelSetAll} and the array is left in an
4647     * indeterminate state.
4648     *
4649     * @param <T> type of elements of the array
4650     * @param array array to be initialized
4651     * @param generator a function accepting an index and producing the desired
4652     *        value for that position
4653     * @throws NullPointerException if the generator is null
4654     * @since 1.8
4655     */
4656    public static <T> void parallelSetAll(T[] array, IntFunction<? extends T> generator) {
4657        Objects.requireNonNull(generator);
4658        IntStream.range(0, array.length).parallel().forEach(i -> { array[i] = generator.apply(i); });
4659    }
4660
4661    /**
4662     * Set all elements of the specified array, using the provided
4663     * generator function to compute each element.
4664     *
4665     * <p>If the generator function throws an exception, it is relayed to
4666     * the caller and the array is left in an indeterminate state.
4667     *
4668     * @param array array to be initialized
4669     * @param generator a function accepting an index and producing the desired
4670     *        value for that position
4671     * @throws NullPointerException if the generator is null
4672     * @since 1.8
4673     */
4674    public static void setAll(int[] array, IntUnaryOperator generator) {
4675        Objects.requireNonNull(generator);
4676        for (int i = 0; i < array.length; i++)
4677            array[i] = generator.applyAsInt(i);
4678    }
4679
4680    /**
4681     * Set all elements of the specified array, in parallel, using the
4682     * provided generator function to compute each element.
4683     *
4684     * <p>If the generator function throws an exception, an unchecked exception
4685     * is thrown from {@code parallelSetAll} and the array is left in an
4686     * indeterminate state.
4687     *
4688     * @param array array to be initialized
4689     * @param generator a function accepting an index and producing the desired
4690     * value for that position
4691     * @throws NullPointerException if the generator is null
4692     * @since 1.8
4693     */
4694    public static void parallelSetAll(int[] array, IntUnaryOperator generator) {
4695        Objects.requireNonNull(generator);
4696        IntStream.range(0, array.length).parallel().forEach(i -> { array[i] = generator.applyAsInt(i); });
4697    }
4698
4699    /**
4700     * Set all elements of the specified array, using the provided
4701     * generator function to compute each element.
4702     *
4703     * <p>If the generator function throws an exception, it is relayed to
4704     * the caller and the array is left in an indeterminate state.
4705     *
4706     * @param array array to be initialized
4707     * @param generator a function accepting an index and producing the desired
4708     *        value for that position
4709     * @throws NullPointerException if the generator is null
4710     * @since 1.8
4711     */
4712    public static void setAll(long[] array, IntToLongFunction generator) {
4713        Objects.requireNonNull(generator);
4714        for (int i = 0; i < array.length; i++)
4715            array[i] = generator.applyAsLong(i);
4716    }
4717
4718    /**
4719     * Set all elements of the specified array, in parallel, using the
4720     * provided generator function to compute each element.
4721     *
4722     * <p>If the generator function throws an exception, an unchecked exception
4723     * is thrown from {@code parallelSetAll} and the array is left in an
4724     * indeterminate state.
4725     *
4726     * @param array array to be initialized
4727     * @param generator a function accepting an index and producing the desired
4728     *        value for that position
4729     * @throws NullPointerException if the generator is null
4730     * @since 1.8
4731     */
4732    public static void parallelSetAll(long[] array, IntToLongFunction generator) {
4733        Objects.requireNonNull(generator);
4734        IntStream.range(0, array.length).parallel().forEach(i -> { array[i] = generator.applyAsLong(i); });
4735    }
4736
4737    /**
4738     * Set all elements of the specified array, using the provided
4739     * generator function to compute each element.
4740     *
4741     * <p>If the generator function throws an exception, it is relayed to
4742     * the caller and the array is left in an indeterminate state.
4743     *
4744     * @param array array to be initialized
4745     * @param generator a function accepting an index and producing the desired
4746     *        value for that position
4747     * @throws NullPointerException if the generator is null
4748     * @since 1.8
4749     */
4750    public static void setAll(double[] array, IntToDoubleFunction generator) {
4751        Objects.requireNonNull(generator);
4752        for (int i = 0; i < array.length; i++)
4753            array[i] = generator.applyAsDouble(i);
4754    }
4755
4756    /**
4757     * Set all elements of the specified array, in parallel, using the
4758     * provided generator function to compute each element.
4759     *
4760     * <p>If the generator function throws an exception, an unchecked exception
4761     * is thrown from {@code parallelSetAll} and the array is left in an
4762     * indeterminate state.
4763     *
4764     * @param array array to be initialized
4765     * @param generator a function accepting an index and producing the desired
4766     *        value for that position
4767     * @throws NullPointerException if the generator is null
4768     * @since 1.8
4769     */
4770    public static void parallelSetAll(double[] array, IntToDoubleFunction generator) {
4771        Objects.requireNonNull(generator);
4772        IntStream.range(0, array.length).parallel().forEach(i -> { array[i] = generator.applyAsDouble(i); });
4773    }
4774
4775    /**
4776     * Returns a {@link Spliterator} covering all of the specified array.
4777     *
4778     * <p>The spliterator reports {@link Spliterator#SIZED},
4779     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
4780     * {@link Spliterator#IMMUTABLE}.
4781     *
4782     * @param <T> type of elements
4783     * @param array the array, assumed to be unmodified during use
4784     * @return a spliterator for the array elements
4785     * @since 1.8
4786     */
4787    public static <T> Spliterator<T> spliterator(T[] array) {
4788        return Spliterators.spliterator(array,
4789                                        Spliterator.ORDERED | Spliterator.IMMUTABLE);
4790    }
4791
4792    /**
4793     * Returns a {@link Spliterator} covering the specified range of the
4794     * specified array.
4795     *
4796     * <p>The spliterator reports {@link Spliterator#SIZED},
4797     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
4798     * {@link Spliterator#IMMUTABLE}.
4799     *
4800     * @param <T> type of elements
4801     * @param array the array, assumed to be unmodified during use
4802     * @param startInclusive the first index to cover, inclusive
4803     * @param endExclusive index immediately past the last index to cover
4804     * @return a spliterator for the array elements
4805     * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
4806     *         negative, {@code endExclusive} is less than
4807     *         {@code startInclusive}, or {@code endExclusive} is greater than
4808     *         the array size
4809     * @since 1.8
4810     */
4811    public static <T> Spliterator<T> spliterator(T[] array, int startInclusive, int endExclusive) {
4812        return Spliterators.spliterator(array, startInclusive, endExclusive,
4813                                        Spliterator.ORDERED | Spliterator.IMMUTABLE);
4814    }
4815
4816    /**
4817     * Returns a {@link Spliterator.OfInt} covering all of the specified array.
4818     *
4819     * <p>The spliterator reports {@link Spliterator#SIZED},
4820     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
4821     * {@link Spliterator#IMMUTABLE}.
4822     *
4823     * @param array the array, assumed to be unmodified during use
4824     * @return a spliterator for the array elements
4825     * @since 1.8
4826     */
4827    public static Spliterator.OfInt spliterator(int[] array) {
4828        return Spliterators.spliterator(array,
4829                                        Spliterator.ORDERED | Spliterator.IMMUTABLE);
4830    }
4831
4832    /**
4833     * Returns a {@link Spliterator.OfInt} covering the specified range of the
4834     * specified array.
4835     *
4836     * <p>The spliterator reports {@link Spliterator#SIZED},
4837     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
4838     * {@link Spliterator#IMMUTABLE}.
4839     *
4840     * @param array the array, assumed to be unmodified during use
4841     * @param startInclusive the first index to cover, inclusive
4842     * @param endExclusive index immediately past the last index to cover
4843     * @return a spliterator for the array elements
4844     * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
4845     *         negative, {@code endExclusive} is less than
4846     *         {@code startInclusive}, or {@code endExclusive} is greater than
4847     *         the array size
4848     * @since 1.8
4849     */
4850    public static Spliterator.OfInt spliterator(int[] array, int startInclusive, int endExclusive) {
4851        return Spliterators.spliterator(array, startInclusive, endExclusive,
4852                                        Spliterator.ORDERED | Spliterator.IMMUTABLE);
4853    }
4854
4855    /**
4856     * Returns a {@link Spliterator.OfLong} covering all of the specified array.
4857     *
4858     * <p>The spliterator reports {@link Spliterator#SIZED},
4859     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
4860     * {@link Spliterator#IMMUTABLE}.
4861     *
4862     * @param array the array, assumed to be unmodified during use
4863     * @return the spliterator for the array elements
4864     * @since 1.8
4865     */
4866    public static Spliterator.OfLong spliterator(long[] array) {
4867        return Spliterators.spliterator(array,
4868                                        Spliterator.ORDERED | Spliterator.IMMUTABLE);
4869    }
4870
4871    /**
4872     * Returns a {@link Spliterator.OfLong} covering the specified range of the
4873     * specified array.
4874     *
4875     * <p>The spliterator reports {@link Spliterator#SIZED},
4876     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
4877     * {@link Spliterator#IMMUTABLE}.
4878     *
4879     * @param array the array, assumed to be unmodified during use
4880     * @param startInclusive the first index to cover, inclusive
4881     * @param endExclusive index immediately past the last index to cover
4882     * @return a spliterator for the array elements
4883     * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
4884     *         negative, {@code endExclusive} is less than
4885     *         {@code startInclusive}, or {@code endExclusive} is greater than
4886     *         the array size
4887     * @since 1.8
4888     */
4889    public static Spliterator.OfLong spliterator(long[] array, int startInclusive, int endExclusive) {
4890        return Spliterators.spliterator(array, startInclusive, endExclusive,
4891                                        Spliterator.ORDERED | Spliterator.IMMUTABLE);
4892    }
4893
4894    /**
4895     * Returns a {@link Spliterator.OfDouble} covering all of the specified
4896     * array.
4897     *
4898     * <p>The spliterator reports {@link Spliterator#SIZED},
4899     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
4900     * {@link Spliterator#IMMUTABLE}.
4901     *
4902     * @param array the array, assumed to be unmodified during use
4903     * @return a spliterator for the array elements
4904     * @since 1.8
4905     */
4906    public static Spliterator.OfDouble spliterator(double[] array) {
4907        return Spliterators.spliterator(array,
4908                                        Spliterator.ORDERED | Spliterator.IMMUTABLE);
4909    }
4910
4911    /**
4912     * Returns a {@link Spliterator.OfDouble} covering the specified range of
4913     * the specified array.
4914     *
4915     * <p>The spliterator reports {@link Spliterator#SIZED},
4916     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
4917     * {@link Spliterator#IMMUTABLE}.
4918     *
4919     * @param array the array, assumed to be unmodified during use
4920     * @param startInclusive the first index to cover, inclusive
4921     * @param endExclusive index immediately past the last index to cover
4922     * @return a spliterator for the array elements
4923     * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
4924     *         negative, {@code endExclusive} is less than
4925     *         {@code startInclusive}, or {@code endExclusive} is greater than
4926     *         the array size
4927     * @since 1.8
4928     */
4929    public static Spliterator.OfDouble spliterator(double[] array, int startInclusive, int endExclusive) {
4930        return Spliterators.spliterator(array, startInclusive, endExclusive,
4931                                        Spliterator.ORDERED | Spliterator.IMMUTABLE);
4932    }
4933
4934    /**
4935     * Returns a sequential {@link Stream} with the specified array as its
4936     * source.
4937     *
4938     * @param <T> The type of the array elements
4939     * @param array The array, assumed to be unmodified during use
4940     * @return a {@code Stream} for the array
4941     * @since 1.8
4942     */
4943    public static <T> Stream<T> stream(T[] array) {
4944        return stream(array, 0, array.length);
4945    }
4946
4947    /**
4948     * Returns a sequential {@link Stream} with the specified range of the
4949     * specified array as its source.
4950     *
4951     * @param <T> the type of the array elements
4952     * @param array the array, assumed to be unmodified during use
4953     * @param startInclusive the first index to cover, inclusive
4954     * @param endExclusive index immediately past the last index to cover
4955     * @return a {@code Stream} for the array range
4956     * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
4957     *         negative, {@code endExclusive} is less than
4958     *         {@code startInclusive}, or {@code endExclusive} is greater than
4959     *         the array size
4960     * @since 1.8
4961     */
4962    public static <T> Stream<T> stream(T[] array, int startInclusive, int endExclusive) {
4963        return StreamSupport.stream(spliterator(array, startInclusive, endExclusive), false);
4964    }
4965
4966    /**
4967     * Returns a sequential {@link IntStream} with the specified array as its
4968     * source.
4969     *
4970     * @param array the array, assumed to be unmodified during use
4971     * @return an {@code IntStream} for the array
4972     * @since 1.8
4973     */
4974    public static IntStream stream(int[] array) {
4975        return stream(array, 0, array.length);
4976    }
4977
4978    /**
4979     * Returns a sequential {@link IntStream} with the specified range of the
4980     * specified array as its source.
4981     *
4982     * @param array the array, assumed to be unmodified during use
4983     * @param startInclusive the first index to cover, inclusive
4984     * @param endExclusive index immediately past the last index to cover
4985     * @return an {@code IntStream} for the array range
4986     * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
4987     *         negative, {@code endExclusive} is less than
4988     *         {@code startInclusive}, or {@code endExclusive} is greater than
4989     *         the array size
4990     * @since 1.8
4991     */
4992    public static IntStream stream(int[] array, int startInclusive, int endExclusive) {
4993        return StreamSupport.intStream(spliterator(array, startInclusive, endExclusive), false);
4994    }
4995
4996    /**
4997     * Returns a sequential {@link LongStream} with the specified array as its
4998     * source.
4999     *
5000     * @param array the array, assumed to be unmodified during use
5001     * @return a {@code LongStream} for the array
5002     * @since 1.8
5003     */
5004    public static LongStream stream(long[] array) {
5005        return stream(array, 0, array.length);
5006    }
5007
5008    /**
5009     * Returns a sequential {@link LongStream} with the specified range of the
5010     * specified array as its source.
5011     *
5012     * @param array the array, assumed to be unmodified during use
5013     * @param startInclusive the first index to cover, inclusive
5014     * @param endExclusive index immediately past the last index to cover
5015     * @return a {@code LongStream} for the array range
5016     * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
5017     *         negative, {@code endExclusive} is less than
5018     *         {@code startInclusive}, or {@code endExclusive} is greater than
5019     *         the array size
5020     * @since 1.8
5021     */
5022    public static LongStream stream(long[] array, int startInclusive, int endExclusive) {
5023        return StreamSupport.longStream(spliterator(array, startInclusive, endExclusive), false);
5024    }
5025
5026    /**
5027     * Returns a sequential {@link DoubleStream} with the specified array as its
5028     * source.
5029     *
5030     * @param array the array, assumed to be unmodified during use
5031     * @return a {@code DoubleStream} for the array
5032     * @since 1.8
5033     */
5034    public static DoubleStream stream(double[] array) {
5035        return stream(array, 0, array.length);
5036    }
5037
5038    /**
5039     * Returns a sequential {@link DoubleStream} with the specified range of the
5040     * specified array as its source.
5041     *
5042     * @param array the array, assumed to be unmodified during use
5043     * @param startInclusive the first index to cover, inclusive
5044     * @param endExclusive index immediately past the last index to cover
5045     * @return a {@code DoubleStream} for the array range
5046     * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
5047     *         negative, {@code endExclusive} is less than
5048     *         {@code startInclusive}, or {@code endExclusive} is greater than
5049     *         the array size
5050     * @since 1.8
5051     */
5052    public static DoubleStream stream(double[] array, int startInclusive, int endExclusive) {
5053        return StreamSupport.doubleStream(spliterator(array, startInclusive, endExclusive), false);
5054    }
5055}
5056