• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1997, 2023, 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 
27 package java.util;
28 
29 import android.compat.Compatibility;
30 import android.compat.annotation.ChangeId;
31 import android.compat.annotation.EnabledSince;
32 
33 import dalvik.annotation.compat.VersionCodes;
34 import dalvik.system.VMRuntime;
35 
36 import jdk.internal.util.ArraysSupport;
37 import jdk.internal.vm.annotation.ForceInline;
38 import jdk.internal.vm.annotation.IntrinsicCandidate;
39 
40 import java.io.Serializable;
41 import java.lang.reflect.Array;
42 import java.util.concurrent.ForkJoinPool;
43 import java.util.function.BinaryOperator;
44 import java.util.function.Consumer;
45 import java.util.function.DoubleBinaryOperator;
46 import java.util.function.IntBinaryOperator;
47 import java.util.function.IntFunction;
48 import java.util.function.IntToDoubleFunction;
49 import java.util.function.IntToLongFunction;
50 import java.util.function.IntUnaryOperator;
51 import java.util.function.LongBinaryOperator;
52 import java.util.function.UnaryOperator;
53 import java.util.stream.DoubleStream;
54 import java.util.stream.IntStream;
55 import java.util.stream.LongStream;
56 import java.util.stream.Stream;
57 import java.util.stream.StreamSupport;
58 
59 /**
60  * This class contains various methods for manipulating arrays (such as
61  * sorting and searching). This class also contains a static factory
62  * that allows arrays to be viewed as lists.
63  *
64  * <p>The methods in this class all throw a {@code NullPointerException},
65  * if the specified array reference is null, except where noted.
66  *
67  * <p>The documentation for the methods contained in this class includes
68  * brief descriptions of the <i>implementations</i>. Such descriptions should
69  * be regarded as <i>implementation notes</i>, rather than parts of the
70  * <i>specification</i>. Implementors should feel free to substitute other
71  * algorithms, so long as the specification itself is adhered to. (For
72  * example, the algorithm used by {@code sort(Object[])} does not have to be
73  * a MergeSort, but it does have to be <i>stable</i>.)
74  *
75  * <p>This class is a member of the
76  * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
77  * Java Collections Framework</a>.
78  *
79  * @author Josh Bloch
80  * @author Neal Gafter
81  * @author John Rose
82  * @since  1.2
83  */
84 public final class Arrays {
85 
86     // Suppresses default constructor, ensuring non-instantiability.
Arrays()87     private Arrays() {}
88 
89     /*
90      * Sorting methods. Note that all public "sort" methods take the
91      * same form: performing argument checks if necessary, and then
92      * expanding arguments into those required for the internal
93      * implementation methods residing in other package-private
94      * classes (except for legacyMergeSort, included in this class).
95      */
96 
97     /**
98      * Sorts the specified array into ascending numerical order.
99      *
100      * @implNote The sorting algorithm is a Dual-Pivot Quicksort
101      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
102      * offers O(n log(n)) performance on all data sets, and is typically
103      * faster than traditional (one-pivot) Quicksort implementations.
104      *
105      * @param a the array to be sorted
106      */
sort(int[] a)107     public static void sort(int[] a) {
108         DualPivotQuicksort.sort(a, 0, 0, a.length);
109     }
110 
111     /**
112      * Sorts the specified range of the array into ascending order. The range
113      * to be sorted extends from the index {@code fromIndex}, inclusive, to
114      * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
115      * the range to be sorted is empty.
116      *
117      * @implNote The sorting algorithm is a Dual-Pivot Quicksort
118      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
119      * offers O(n log(n)) performance on all data sets, and is typically
120      * faster than traditional (one-pivot) Quicksort implementations.
121      *
122      * @param a the array to be sorted
123      * @param fromIndex the index of the first element, inclusive, to be sorted
124      * @param toIndex the index of the last element, exclusive, to be sorted
125      *
126      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
127      * @throws ArrayIndexOutOfBoundsException
128      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
129      */
sort(int[] a, int fromIndex, int toIndex)130     public static void sort(int[] a, int fromIndex, int toIndex) {
131         rangeCheck(a.length, fromIndex, toIndex);
132         DualPivotQuicksort.sort(a, 0, fromIndex, toIndex);
133     }
134 
135     /**
136      * Sorts the specified array into ascending numerical order.
137      *
138      * @implNote The sorting algorithm is a Dual-Pivot Quicksort
139      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
140      * offers O(n log(n)) performance on all data sets, and is typically
141      * faster than traditional (one-pivot) Quicksort implementations.
142      *
143      * @param a the array to be sorted
144      */
sort(long[] a)145     public static void sort(long[] a) {
146         DualPivotQuicksort.sort(a, 0, 0, a.length);
147     }
148 
149     /**
150      * Sorts the specified range of the array into ascending order. The range
151      * to be sorted extends from the index {@code fromIndex}, inclusive, to
152      * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
153      * the range to be sorted is empty.
154      *
155      * @implNote The sorting algorithm is a Dual-Pivot Quicksort
156      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
157      * offers O(n log(n)) performance on all data sets, and is typically
158      * faster than traditional (one-pivot) Quicksort implementations.
159      *
160      * @param a the array to be sorted
161      * @param fromIndex the index of the first element, inclusive, to be sorted
162      * @param toIndex the index of the last element, exclusive, to be sorted
163      *
164      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
165      * @throws ArrayIndexOutOfBoundsException
166      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
167      */
sort(long[] a, int fromIndex, int toIndex)168     public static void sort(long[] a, int fromIndex, int toIndex) {
169         rangeCheck(a.length, fromIndex, toIndex);
170         DualPivotQuicksort.sort(a, 0, fromIndex, toIndex);
171     }
172 
173     /**
174      * Sorts the specified array into ascending numerical order.
175      *
176      * @implNote The sorting algorithm is a Dual-Pivot Quicksort
177      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
178      * offers O(n log(n)) performance on all data sets, and is typically
179      * faster than traditional (one-pivot) Quicksort implementations.
180      *
181      * @param a the array to be sorted
182      */
sort(short[] a)183     public static void sort(short[] a) {
184         DualPivotQuicksort.sort(a, 0, a.length);
185     }
186 
187     /**
188      * Sorts the specified range of the array into ascending order. The range
189      * to be sorted extends from the index {@code fromIndex}, inclusive, to
190      * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
191      * the range to be sorted is empty.
192      *
193      * @implNote The sorting algorithm is a Dual-Pivot Quicksort
194      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
195      * offers O(n log(n)) performance on all data sets, and is typically
196      * faster than traditional (one-pivot) Quicksort implementations.
197      *
198      * @param a the array to be sorted
199      * @param fromIndex the index of the first element, inclusive, to be sorted
200      * @param toIndex the index of the last element, exclusive, to be sorted
201      *
202      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
203      * @throws ArrayIndexOutOfBoundsException
204      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
205      */
sort(short[] a, int fromIndex, int toIndex)206     public static void sort(short[] a, int fromIndex, int toIndex) {
207         rangeCheck(a.length, fromIndex, toIndex);
208         DualPivotQuicksort.sort(a, fromIndex, toIndex);
209     }
210 
211     /**
212      * Sorts the specified array into ascending numerical order.
213      *
214      * @implNote The sorting algorithm is a Dual-Pivot Quicksort
215      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
216      * offers O(n log(n)) performance on all data sets, and is typically
217      * faster than traditional (one-pivot) Quicksort implementations.
218      *
219      * @param a the array to be sorted
220      */
sort(char[] a)221     public static void sort(char[] a) {
222         DualPivotQuicksort.sort(a, 0, a.length);
223     }
224 
225     /**
226      * Sorts the specified range of the array into ascending order. The range
227      * to be sorted extends from the index {@code fromIndex}, inclusive, to
228      * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
229      * the range to be sorted is empty.
230      *
231      * @implNote The sorting algorithm is a Dual-Pivot Quicksort
232      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
233      * offers O(n log(n)) performance on all data sets, and is typically
234      * faster than traditional (one-pivot) Quicksort implementations.
235      *
236      * @param a the array to be sorted
237      * @param fromIndex the index of the first element, inclusive, to be sorted
238      * @param toIndex the index of the last element, exclusive, to be sorted
239      *
240      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
241      * @throws ArrayIndexOutOfBoundsException
242      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
243      */
sort(char[] a, int fromIndex, int toIndex)244     public static void sort(char[] a, int fromIndex, int toIndex) {
245         rangeCheck(a.length, fromIndex, toIndex);
246         DualPivotQuicksort.sort(a, fromIndex, toIndex);
247     }
248 
249     /**
250      * Sorts the specified array into ascending numerical order.
251      *
252      * @implNote The sorting algorithm is a Dual-Pivot Quicksort
253      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
254      * offers O(n log(n)) performance on all data sets, and is typically
255      * faster than traditional (one-pivot) Quicksort implementations.
256      *
257      * @param a the array to be sorted
258      */
sort(byte[] a)259     public static void sort(byte[] a) {
260         DualPivotQuicksort.sort(a, 0, a.length);
261     }
262 
263     /**
264      * Sorts the specified range of the array into ascending order. The range
265      * to be sorted extends from the index {@code fromIndex}, inclusive, to
266      * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
267      * the range to be sorted is empty.
268      *
269      * @implNote The sorting algorithm is a Dual-Pivot Quicksort
270      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
271      * offers O(n log(n)) performance on all data sets, and is typically
272      * faster than traditional (one-pivot) Quicksort implementations.
273      *
274      * @param a the array to be sorted
275      * @param fromIndex the index of the first element, inclusive, to be sorted
276      * @param toIndex the index of the last element, exclusive, to be sorted
277      *
278      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
279      * @throws ArrayIndexOutOfBoundsException
280      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
281      */
sort(byte[] a, int fromIndex, int toIndex)282     public static void sort(byte[] a, int fromIndex, int toIndex) {
283         rangeCheck(a.length, fromIndex, toIndex);
284         DualPivotQuicksort.sort(a, fromIndex, toIndex);
285     }
286 
287     /**
288      * Sorts the specified array into ascending numerical order.
289      *
290      * <p>The {@code <} relation does not provide a total order on all float
291      * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
292      * value compares neither less than, greater than, nor equal to any value,
293      * even itself. This method uses the total order imposed by the method
294      * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
295      * {@code 0.0f} and {@code Float.NaN} is considered greater than any
296      * other value and all {@code Float.NaN} values are considered equal.
297      *
298      * @implNote The sorting algorithm is a Dual-Pivot Quicksort
299      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
300      * offers O(n log(n)) performance on all data sets, and is typically
301      * faster than traditional (one-pivot) Quicksort implementations.
302      *
303      * @param a the array to be sorted
304      */
sort(float[] a)305     public static void sort(float[] a) {
306         DualPivotQuicksort.sort(a, 0, 0, a.length);
307     }
308 
309     /**
310      * Sorts the specified range of the array into ascending order. The range
311      * to be sorted extends from the index {@code fromIndex}, inclusive, to
312      * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
313      * the range to be sorted is empty.
314      *
315      * <p>The {@code <} relation does not provide a total order on all float
316      * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
317      * value compares neither less than, greater than, nor equal to any value,
318      * even itself. This method uses the total order imposed by the method
319      * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
320      * {@code 0.0f} and {@code Float.NaN} is considered greater than any
321      * other value and all {@code Float.NaN} values are considered equal.
322      *
323      * @implNote The sorting algorithm is a Dual-Pivot Quicksort
324      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
325      * offers O(n log(n)) performance on all data sets, and is typically
326      * faster than traditional (one-pivot) Quicksort implementations.
327      *
328      * @param a the array to be sorted
329      * @param fromIndex the index of the first element, inclusive, to be sorted
330      * @param toIndex the index of the last element, exclusive, to be sorted
331      *
332      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
333      * @throws ArrayIndexOutOfBoundsException
334      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
335      */
sort(float[] a, int fromIndex, int toIndex)336     public static void sort(float[] a, int fromIndex, int toIndex) {
337         rangeCheck(a.length, fromIndex, toIndex);
338         DualPivotQuicksort.sort(a, 0, fromIndex, toIndex);
339     }
340 
341     /**
342      * Sorts the specified array into ascending numerical order.
343      *
344      * <p>The {@code <} relation does not provide a total order on all double
345      * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
346      * value compares neither less than, greater than, nor equal to any value,
347      * even itself. This method uses the total order imposed by the method
348      * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
349      * {@code 0.0d} and {@code Double.NaN} is considered greater than any
350      * other value and all {@code Double.NaN} values are considered equal.
351      *
352      * @implNote The sorting algorithm is a Dual-Pivot Quicksort
353      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
354      * offers O(n log(n)) performance on all data sets, and is typically
355      * faster than traditional (one-pivot) Quicksort implementations.
356      *
357      * @param a the array to be sorted
358      */
sort(double[] a)359     public static void sort(double[] a) {
360         DualPivotQuicksort.sort(a, 0, 0, a.length);
361     }
362 
363     /**
364      * Sorts the specified range of the array into ascending order. The range
365      * to be sorted extends from the index {@code fromIndex}, inclusive, to
366      * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
367      * the range to be sorted is empty.
368      *
369      * <p>The {@code <} relation does not provide a total order on all double
370      * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
371      * value compares neither less than, greater than, nor equal to any value,
372      * even itself. This method uses the total order imposed by the method
373      * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
374      * {@code 0.0d} and {@code Double.NaN} is considered greater than any
375      * other value and all {@code Double.NaN} values are considered equal.
376      *
377      * @implNote The sorting algorithm is a Dual-Pivot Quicksort
378      * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
379      * offers O(n log(n)) performance on all data sets, and is typically
380      * faster than traditional (one-pivot) Quicksort implementations.
381      *
382      * @param a the array to be sorted
383      * @param fromIndex the index of the first element, inclusive, to be sorted
384      * @param toIndex the index of the last element, exclusive, to be sorted
385      *
386      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
387      * @throws ArrayIndexOutOfBoundsException
388      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
389      */
sort(double[] a, int fromIndex, int toIndex)390     public static void sort(double[] a, int fromIndex, int toIndex) {
391         rangeCheck(a.length, fromIndex, toIndex);
392         DualPivotQuicksort.sort(a, 0, fromIndex, toIndex);
393     }
394 
395     /**
396      * Sorts the specified array into ascending numerical order.
397      *
398      * @implNote The sorting algorithm is a Dual-Pivot Quicksort by
399      * Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch. This algorithm
400      * offers O(n log(n)) performance on all data sets, and is typically
401      * faster than traditional (one-pivot) Quicksort implementations.
402      *
403      * @param a the array to be sorted
404      *
405      * @since 1.8
406      */
parallelSort(byte[] a)407     public static void parallelSort(byte[] a) {
408         DualPivotQuicksort.sort(a, 0, a.length);
409     }
410 
411     /**
412      * Sorts the specified range of the array into ascending numerical order.
413      * The range to be sorted extends from the index {@code fromIndex},
414      * inclusive, to the index {@code toIndex}, exclusive. If
415      * {@code fromIndex == toIndex}, the range to be sorted is empty.
416      *
417      * @implNote The sorting algorithm is a Dual-Pivot Quicksort by
418      * Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch. This algorithm
419      * offers O(n log(n)) performance on all data sets, and is typically
420      * faster than traditional (one-pivot) Quicksort implementations.
421      *
422      * @param a the array to be sorted
423      * @param fromIndex the index of the first element, inclusive, to be sorted
424      * @param toIndex the index of the last element, exclusive, to be sorted
425      *
426      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
427      * @throws ArrayIndexOutOfBoundsException
428      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
429      *
430      * @since 1.8
431      */
parallelSort(byte[] a, int fromIndex, int toIndex)432     public static void parallelSort(byte[] a, int fromIndex, int toIndex) {
433         rangeCheck(a.length, fromIndex, toIndex);
434         DualPivotQuicksort.sort(a, fromIndex, toIndex);
435     }
436 
437     /**
438      * Sorts the specified array into ascending numerical order.
439      *
440      * @implNote The sorting algorithm is a Dual-Pivot Quicksort by
441      * Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch. This algorithm
442      * offers O(n log(n)) performance on all data sets, and is typically
443      * faster than traditional (one-pivot) Quicksort implementations.
444      *
445      * @param a the array to be sorted
446      *
447      * @since 1.8
448      */
parallelSort(char[] a)449     public static void parallelSort(char[] a) {
450         DualPivotQuicksort.sort(a, 0, a.length);
451     }
452 
453     /**
454      * Sorts the specified range of the array into ascending numerical order.
455      * The range to be sorted extends from the index {@code fromIndex},
456      * inclusive, to the index {@code toIndex}, exclusive. If
457      * {@code fromIndex == toIndex}, the range to be sorted is empty.
458      *
459      * @implNote The sorting algorithm is a Dual-Pivot Quicksort by
460      * Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch. This algorithm
461      * offers O(n log(n)) performance on all data sets, and is typically
462      * faster than traditional (one-pivot) Quicksort implementations.
463      *
464      * @param a the array to be sorted
465      * @param fromIndex the index of the first element, inclusive, to be sorted
466      * @param toIndex the index of the last element, exclusive, to be sorted
467      *
468      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
469      * @throws ArrayIndexOutOfBoundsException
470      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
471      *
472      * @since 1.8
473      */
parallelSort(char[] a, int fromIndex, int toIndex)474     public static void parallelSort(char[] a, int fromIndex, int toIndex) {
475         rangeCheck(a.length, fromIndex, toIndex);
476         DualPivotQuicksort.sort(a, fromIndex, toIndex);
477     }
478 
479     /**
480      * Sorts the specified array into ascending numerical order.
481      *
482      * @implNote The sorting algorithm is a Dual-Pivot Quicksort by
483      * Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch. This algorithm
484      * offers O(n log(n)) performance on all data sets, and is typically
485      * faster than traditional (one-pivot) Quicksort implementations.
486      *
487      * @param a the array to be sorted
488      *
489      * @since 1.8
490      */
parallelSort(short[] a)491     public static void parallelSort(short[] a) {
492         DualPivotQuicksort.sort(a, 0, a.length);
493     }
494 
495     /**
496      * Sorts the specified range of the array into ascending numerical order.
497      * The range to be sorted extends from the index {@code fromIndex},
498      * inclusive, to the index {@code toIndex}, exclusive. If
499      * {@code fromIndex == toIndex}, the range to be sorted is empty.
500      *
501      * @implNote The sorting algorithm is a Dual-Pivot Quicksort by
502      * Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch. This algorithm
503      * offers O(n log(n)) performance on all data sets, and is typically
504      * faster than traditional (one-pivot) Quicksort implementations.
505      *
506      * @param a the array to be sorted
507      * @param fromIndex the index of the first element, inclusive, to be sorted
508      * @param toIndex the index of the last element, exclusive, to be sorted
509      *
510      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
511      * @throws ArrayIndexOutOfBoundsException
512      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
513      *
514      * @since 1.8
515      */
parallelSort(short[] a, int fromIndex, int toIndex)516     public static void parallelSort(short[] a, int fromIndex, int toIndex) {
517         rangeCheck(a.length, fromIndex, toIndex);
518         DualPivotQuicksort.sort(a, fromIndex, toIndex);
519     }
520 
521     /**
522      * Sorts the specified array into ascending numerical order.
523      *
524      * @implNote The sorting algorithm is a Dual-Pivot Quicksort by
525      * Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch. This algorithm
526      * offers O(n log(n)) performance on all data sets, and is typically
527      * faster than traditional (one-pivot) Quicksort implementations.
528      *
529      * @param a the array to be sorted
530      *
531      * @since 1.8
532      */
parallelSort(int[] a)533     public static void parallelSort(int[] a) {
534         DualPivotQuicksort.sort(a, ForkJoinPool.getCommonPoolParallelism(), 0, a.length);
535     }
536 
537     /**
538      * Sorts the specified range of the array into ascending numerical order.
539      * The range to be sorted extends from the index {@code fromIndex},
540      * inclusive, to the index {@code toIndex}, exclusive. If
541      * {@code fromIndex == toIndex}, the range to be sorted is empty.
542      *
543      * @implNote The sorting algorithm is a Dual-Pivot Quicksort by
544      * Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch. This algorithm
545      * offers O(n log(n)) performance on all data sets, and is typically
546      * faster than traditional (one-pivot) Quicksort implementations.
547      *
548      * @param a the array to be sorted
549      * @param fromIndex the index of the first element, inclusive, to be sorted
550      * @param toIndex the index of the last element, exclusive, to be sorted
551      *
552      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
553      * @throws ArrayIndexOutOfBoundsException
554      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
555      *
556      * @since 1.8
557      */
parallelSort(int[] a, int fromIndex, int toIndex)558     public static void parallelSort(int[] a, int fromIndex, int toIndex) {
559         rangeCheck(a.length, fromIndex, toIndex);
560         DualPivotQuicksort.sort(a, ForkJoinPool.getCommonPoolParallelism(), fromIndex, toIndex);
561     }
562 
563     /**
564      * Sorts the specified array into ascending numerical order.
565      *
566      * @implNote The sorting algorithm is a Dual-Pivot Quicksort by
567      * Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch. This algorithm
568      * offers O(n log(n)) performance on all data sets, and is typically
569      * faster than traditional (one-pivot) Quicksort implementations.
570      *
571      * @param a the array to be sorted
572      *
573      * @since 1.8
574      */
parallelSort(long[] a)575     public static void parallelSort(long[] a) {
576         DualPivotQuicksort.sort(a, ForkJoinPool.getCommonPoolParallelism(), 0, a.length);
577     }
578 
579     /**
580      * Sorts the specified range of the array into ascending numerical order.
581      * The range to be sorted extends from the index {@code fromIndex},
582      * inclusive, to the index {@code toIndex}, exclusive. If
583      * {@code fromIndex == toIndex}, the range to be sorted is empty.
584      *
585      * @implNote The sorting algorithm is a Dual-Pivot Quicksort by
586      * Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch. This algorithm
587      * offers O(n log(n)) performance on all data sets, and is typically
588      * faster than traditional (one-pivot) Quicksort implementations.
589      *
590      * @param a the array to be sorted
591      * @param fromIndex the index of the first element, inclusive, to be sorted
592      * @param toIndex the index of the last element, exclusive, to be sorted
593      *
594      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
595      * @throws ArrayIndexOutOfBoundsException
596      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
597      *
598      * @since 1.8
599      */
parallelSort(long[] a, int fromIndex, int toIndex)600     public static void parallelSort(long[] a, int fromIndex, int toIndex) {
601         rangeCheck(a.length, fromIndex, toIndex);
602         DualPivotQuicksort.sort(a, ForkJoinPool.getCommonPoolParallelism(), fromIndex, toIndex);
603     }
604 
605     /**
606      * Sorts the specified array into ascending numerical order.
607      *
608      * <p>The {@code <} relation does not provide a total order on all float
609      * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
610      * value compares neither less than, greater than, nor equal to any value,
611      * even itself. This method uses the total order imposed by the method
612      * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
613      * {@code 0.0f} and {@code Float.NaN} is considered greater than any
614      * other value and all {@code Float.NaN} values are considered equal.
615      *
616      * @implNote The sorting algorithm is a Dual-Pivot Quicksort by
617      * Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch. This algorithm
618      * offers O(n log(n)) performance on all data sets, and is typically
619      * faster than traditional (one-pivot) Quicksort implementations.
620      *
621      * @param a the array to be sorted
622      *
623      * @since 1.8
624      */
parallelSort(float[] a)625     public static void parallelSort(float[] a) {
626         DualPivotQuicksort.sort(a, ForkJoinPool.getCommonPoolParallelism(), 0, a.length);
627     }
628 
629     /**
630      * Sorts the specified range of the array into ascending numerical order.
631      * The range to be sorted extends from the index {@code fromIndex},
632      * inclusive, to the index {@code toIndex}, exclusive. If
633      * {@code fromIndex == toIndex}, the range to be sorted is empty.
634      *
635      * <p>The {@code <} relation does not provide a total order on all float
636      * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
637      * value compares neither less than, greater than, nor equal to any value,
638      * even itself. This method uses the total order imposed by the method
639      * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
640      * {@code 0.0f} and {@code Float.NaN} is considered greater than any
641      * other value and all {@code Float.NaN} values are considered equal.
642      *
643      * @implNote The sorting algorithm is a Dual-Pivot Quicksort by
644      * Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch. This algorithm
645      * offers O(n log(n)) performance on all data sets, and is typically
646      * faster than traditional (one-pivot) Quicksort implementations.
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      */
parallelSort(float[] a, int fromIndex, int toIndex)658     public static void parallelSort(float[] a, int fromIndex, int toIndex) {
659         rangeCheck(a.length, fromIndex, toIndex);
660         DualPivotQuicksort.sort(a, ForkJoinPool.getCommonPoolParallelism(), fromIndex, toIndex);
661     }
662 
663     /**
664      * Sorts the specified array into ascending numerical order.
665      *
666      * <p>The {@code <} relation does not provide a total order on all double
667      * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
668      * value compares neither less than, greater than, nor equal to any value,
669      * even itself. This method uses the total order imposed by the method
670      * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
671      * {@code 0.0d} and {@code Double.NaN} is considered greater than any
672      * other value and all {@code Double.NaN} values are considered equal.
673      *
674      * @implNote The sorting algorithm is a Dual-Pivot Quicksort by
675      * Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch. This algorithm
676      * offers O(n log(n)) performance on all data sets, and is typically
677      * faster than traditional (one-pivot) Quicksort implementations.
678      *
679      * @param a the array to be sorted
680      *
681      * @since 1.8
682      */
parallelSort(double[] a)683     public static void parallelSort(double[] a) {
684         DualPivotQuicksort.sort(a, ForkJoinPool.getCommonPoolParallelism(), 0, a.length);
685     }
686 
687     /**
688      * Sorts the specified range of the array into ascending numerical order.
689      * The range to be sorted extends from the index {@code fromIndex},
690      * inclusive, to the index {@code toIndex}, exclusive. If
691      * {@code fromIndex == toIndex}, the range to be sorted is empty.
692      *
693      * <p>The {@code <} relation does not provide a total order on all double
694      * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
695      * value compares neither less than, greater than, nor equal to any value,
696      * even itself. This method uses the total order imposed by the method
697      * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
698      * {@code 0.0d} and {@code Double.NaN} is considered greater than any
699      * other value and all {@code Double.NaN} values are considered equal.
700      *
701      * @implNote The sorting algorithm is a Dual-Pivot Quicksort by
702      * Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch. This algorithm
703      * offers O(n log(n)) performance on all data sets, and is typically
704      * faster than traditional (one-pivot) Quicksort implementations.
705      *
706      * @param a the array to be sorted
707      * @param fromIndex the index of the first element, inclusive, to be sorted
708      * @param toIndex the index of the last element, exclusive, to be sorted
709      *
710      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
711      * @throws ArrayIndexOutOfBoundsException
712      *     if {@code fromIndex < 0} or {@code toIndex > a.length}
713      *
714      * @since 1.8
715      */
parallelSort(double[] a, int fromIndex, int toIndex)716     public static void parallelSort(double[] a, int fromIndex, int toIndex) {
717         rangeCheck(a.length, fromIndex, toIndex);
718         DualPivotQuicksort.sort(a, ForkJoinPool.getCommonPoolParallelism(), fromIndex, toIndex);
719     }
720 
721     /**
722      * Checks that {@code fromIndex} and {@code toIndex} are in
723      * the range and throws an exception if they aren't.
724      */
rangeCheck(int arrayLength, int fromIndex, int toIndex)725     static void rangeCheck(int arrayLength, int fromIndex, int toIndex) {
726         if (fromIndex > toIndex) {
727             throw new IllegalArgumentException(
728                 "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
729         }
730         if (fromIndex < 0) {
731             throw new ArrayIndexOutOfBoundsException(fromIndex);
732         }
733         if (toIndex > arrayLength) {
734             throw new ArrayIndexOutOfBoundsException(toIndex);
735         }
736     }
737 
738     /**
739      * A comparator that implements the natural ordering of a group of
740      * mutually comparable elements. May be used when a supplied
741      * comparator is null. To simplify code-sharing within underlying
742      * implementations, the compare method only declares type Object
743      * for its second argument.
744      *
745      * Arrays class implementor's note: It is an empirical matter
746      * whether ComparableTimSort offers any performance benefit over
747      * TimSort used with this comparator.  If not, you are better off
748      * deleting or bypassing ComparableTimSort.  There is currently no
749      * empirical case for separating them for parallel sorting, so all
750      * public Object parallelSort methods use the same comparator
751      * based implementation.
752      */
753     static final class NaturalOrder implements Comparator<Object> {
754         @SuppressWarnings("unchecked")
compare(Object first, Object second)755         public int compare(Object first, Object second) {
756             return ((Comparable<Object>)first).compareTo(second);
757         }
758         static final NaturalOrder INSTANCE = new NaturalOrder();
759     }
760 
761     /**
762      * The minimum array length below which a parallel sorting
763      * algorithm will not further partition the sorting task. Using
764      * smaller sizes typically results in memory contention across
765      * tasks that makes parallel speedups unlikely.
766      *
767      * @hide
768      */
769     // Android-changed: Make MIN_ARRAY_SORT_GRAN public and @hide (used by harmony
770     // ArraysTest).
771     public static final int MIN_ARRAY_SORT_GRAN = 1 << 13;
772 
773     /**
774      * Sorts the specified array of objects into ascending order, according
775      * to the {@linkplain Comparable natural ordering} of its elements.
776      * All elements in the array must implement the {@link Comparable}
777      * interface.  Furthermore, all elements in the array must be
778      * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)} must
779      * not throw a {@code ClassCastException} for any elements {@code e1}
780      * and {@code e2} in the array).
781      *
782      * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
783      * not be reordered as a result of the sort.
784      *
785      * @implNote The sorting algorithm is a parallel sort-merge that breaks the
786      * array into sub-arrays that are themselves sorted and then merged. When
787      * the sub-array length reaches a minimum granularity, the sub-array is
788      * sorted using the appropriate {@link Arrays#sort(Object[]) Arrays.sort}
789      * method. If the length of the specified array is less than the minimum
790      * granularity, then it is sorted using the appropriate {@link
791      * Arrays#sort(Object[]) Arrays.sort} method. The algorithm requires a
792      * working space no greater than the size of the original array. The
793      * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to
794      * execute any parallel tasks.
795      *
796      * @param <T> the class of the objects to be sorted
797      * @param a the array to be sorted
798      *
799      * @throws ClassCastException if the array contains elements that are not
800      *         <i>mutually comparable</i> (for example, strings and integers)
801      * @throws IllegalArgumentException (optional) if the natural
802      *         ordering of the array elements is found to violate the
803      *         {@link Comparable} contract
804      *
805      * @since 1.8
806      */
807     @SuppressWarnings("unchecked")
parallelSort(T[] a)808     public static <T extends Comparable<? super T>> void parallelSort(T[] a) {
809         int n = a.length, p, g;
810         if (n <= MIN_ARRAY_SORT_GRAN ||
811             (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
812             TimSort.sort(a, 0, n, NaturalOrder.INSTANCE, null, 0, 0);
813         else
814             new ArraysParallelSortHelpers.FJObject.Sorter<>
815                 (null, a,
816                  (T[])Array.newInstance(a.getClass().getComponentType(), n),
817                  0, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
818                  MIN_ARRAY_SORT_GRAN : g, NaturalOrder.INSTANCE).invoke();
819     }
820 
821     /**
822      * Sorts the specified range of the specified array of objects into
823      * ascending order, according to the
824      * {@linkplain Comparable natural ordering} of its
825      * elements.  The range to be sorted extends from index
826      * {@code fromIndex}, inclusive, to index {@code toIndex}, exclusive.
827      * (If {@code fromIndex==toIndex}, the range to be sorted is empty.)  All
828      * elements in this range must implement the {@link Comparable}
829      * interface.  Furthermore, all elements in this range must be <i>mutually
830      * comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a
831      * {@code ClassCastException} for any elements {@code e1} and
832      * {@code e2} in the array).
833      *
834      * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
835      * not be reordered as a result of the sort.
836      *
837      * @implNote The sorting algorithm is a parallel sort-merge that breaks the
838      * array into sub-arrays that are themselves sorted and then merged. When
839      * the sub-array length reaches a minimum granularity, the sub-array is
840      * sorted using the appropriate {@link Arrays#sort(Object[]) Arrays.sort}
841      * method. If the length of the specified array is less than the minimum
842      * granularity, then it is sorted using the appropriate {@link
843      * Arrays#sort(Object[]) Arrays.sort} method. The algorithm requires a working
844      * space no greater than the size of the specified range of the original
845      * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is
846      * used to execute any parallel tasks.
847      *
848      * @param <T> the class of the objects to be sorted
849      * @param a the array to be sorted
850      * @param fromIndex the index of the first element (inclusive) to be
851      *        sorted
852      * @param toIndex the index of the last element (exclusive) to be sorted
853      * @throws IllegalArgumentException if {@code fromIndex > toIndex} or
854      *         (optional) if the natural ordering of the array elements is
855      *         found to violate the {@link Comparable} contract
856      * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
857      *         {@code toIndex > a.length}
858      * @throws ClassCastException if the array contains elements that are
859      *         not <i>mutually comparable</i> (for example, strings and
860      *         integers).
861      *
862      * @since 1.8
863      */
864     @SuppressWarnings("unchecked")
865     public static <T extends Comparable<? super T>>
parallelSort(T[] a, int fromIndex, int toIndex)866     void parallelSort(T[] a, int fromIndex, int toIndex) {
867         rangeCheck(a.length, fromIndex, toIndex);
868         int n = toIndex - fromIndex, p, g;
869         if (n <= MIN_ARRAY_SORT_GRAN ||
870             (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
871             TimSort.sort(a, fromIndex, toIndex, NaturalOrder.INSTANCE, null, 0, 0);
872         else
873             new ArraysParallelSortHelpers.FJObject.Sorter<>
874                 (null, a,
875                  (T[])Array.newInstance(a.getClass().getComponentType(), n),
876                  fromIndex, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
877                  MIN_ARRAY_SORT_GRAN : g, NaturalOrder.INSTANCE).invoke();
878     }
879 
880     /**
881      * Sorts the specified array of objects according to the order induced by
882      * the specified comparator.  All elements in the array must be
883      * <i>mutually comparable</i> by the specified comparator (that is,
884      * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
885      * for any elements {@code e1} and {@code e2} in the array).
886      *
887      * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
888      * not be reordered as a result of the sort.
889      *
890      * @implNote The sorting algorithm is a parallel sort-merge that breaks the
891      * array into sub-arrays that are themselves sorted and then merged. When
892      * the sub-array length reaches a minimum granularity, the sub-array is
893      * sorted using the appropriate {@link Arrays#sort(Object[]) Arrays.sort}
894      * method. If the length of the specified array is less than the minimum
895      * granularity, then it is sorted using the appropriate {@link
896      * Arrays#sort(Object[]) Arrays.sort} method. The algorithm requires a
897      * working space no greater than the size of the original array. The
898      * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to
899      * execute any parallel tasks.
900      *
901      * @param <T> the class of the objects to be sorted
902      * @param a the array to be sorted
903      * @param cmp the comparator to determine the order of the array.  A
904      *        {@code null} value indicates that the elements'
905      *        {@linkplain Comparable natural ordering} should be used.
906      * @throws ClassCastException if the array contains elements that are
907      *         not <i>mutually comparable</i> using the specified comparator
908      * @throws IllegalArgumentException (optional) if the comparator is
909      *         found to violate the {@link java.util.Comparator} contract
910      *
911      * @since 1.8
912      */
913     @SuppressWarnings("unchecked")
parallelSort(T[] a, Comparator<? super T> cmp)914     public static <T> void parallelSort(T[] a, Comparator<? super T> cmp) {
915         if (cmp == null)
916             cmp = NaturalOrder.INSTANCE;
917         int n = a.length, p, g;
918         if (n <= MIN_ARRAY_SORT_GRAN ||
919             (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
920             TimSort.sort(a, 0, n, cmp, null, 0, 0);
921         else
922             new ArraysParallelSortHelpers.FJObject.Sorter<>
923                 (null, a,
924                  (T[])Array.newInstance(a.getClass().getComponentType(), n),
925                  0, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
926                  MIN_ARRAY_SORT_GRAN : g, cmp).invoke();
927     }
928 
929     /**
930      * Sorts the specified range of the specified array of objects according
931      * to the order induced by the specified comparator.  The range to be
932      * sorted extends from index {@code fromIndex}, inclusive, to index
933      * {@code toIndex}, exclusive.  (If {@code fromIndex==toIndex}, the
934      * range to be sorted is empty.)  All elements in the range must be
935      * <i>mutually comparable</i> by the specified comparator (that is,
936      * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
937      * for any elements {@code e1} and {@code e2} in the range).
938      *
939      * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
940      * not be reordered as a result of the sort.
941      *
942      * @implNote The sorting algorithm is a parallel sort-merge that breaks the
943      * array into sub-arrays that are themselves sorted and then merged. When
944      * the sub-array length reaches a minimum granularity, the sub-array is
945      * sorted using the appropriate {@link Arrays#sort(Object[]) Arrays.sort}
946      * method. If the length of the specified array is less than the minimum
947      * granularity, then it is sorted using the appropriate {@link
948      * Arrays#sort(Object[]) Arrays.sort} method. The algorithm requires a working
949      * space no greater than the size of the specified range of the original
950      * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is
951      * used to execute any parallel tasks.
952      *
953      * @param <T> the class of the objects to be sorted
954      * @param a the array to be sorted
955      * @param fromIndex the index of the first element (inclusive) to be
956      *        sorted
957      * @param toIndex the index of the last element (exclusive) to be sorted
958      * @param cmp the comparator to determine the order of the array.  A
959      *        {@code null} value indicates that the elements'
960      *        {@linkplain Comparable natural ordering} should be used.
961      * @throws IllegalArgumentException if {@code fromIndex > toIndex} or
962      *         (optional) if the natural ordering of the array elements is
963      *         found to violate the {@link Comparable} contract
964      * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
965      *         {@code toIndex > a.length}
966      * @throws ClassCastException if the array contains elements that are
967      *         not <i>mutually comparable</i> (for example, strings and
968      *         integers).
969      *
970      * @since 1.8
971      */
972     @SuppressWarnings("unchecked")
parallelSort(T[] a, int fromIndex, int toIndex, Comparator<? super T> cmp)973     public static <T> void parallelSort(T[] a, int fromIndex, int toIndex,
974                                         Comparator<? super T> cmp) {
975         rangeCheck(a.length, fromIndex, toIndex);
976         if (cmp == null)
977             cmp = NaturalOrder.INSTANCE;
978         int n = toIndex - fromIndex, p, g;
979         if (n <= MIN_ARRAY_SORT_GRAN ||
980             (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
981             TimSort.sort(a, fromIndex, toIndex, cmp, null, 0, 0);
982         else
983             new ArraysParallelSortHelpers.FJObject.Sorter<>
984                 (null, a,
985                  (T[])Array.newInstance(a.getClass().getComponentType(), n),
986                  fromIndex, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
987                  MIN_ARRAY_SORT_GRAN : g, cmp).invoke();
988     }
989 
990     /*
991      * Sorting of complex type arrays.
992      */
993 
994     // BEGIN Android-removed: LegacyMergeSort class (unused on Android).
995     /*
996     /**
997      * Old merge sort implementation can be selected (for
998      * compatibility with broken comparators) using a system property.
999      * Cannot be a static boolean in the enclosing class due to
1000      * circular dependencies. To be removed in a future release.
1001      *
1002     static final class LegacyMergeSort {
1003         @SuppressWarnings("removal")
1004         private static final boolean userRequested =
1005             java.security.AccessController.doPrivileged(
1006                 new sun.security.action.GetBooleanAction(
1007                     "java.util.Arrays.useLegacyMergeSort")).booleanValue();
1008     }
1009     */
1010     // END Android-removed: LegacyMergeSort class (unused on Android).
1011 
1012     /**
1013      * Sorts the specified array of objects into ascending order, according
1014      * to the {@linkplain Comparable natural ordering} of its elements.
1015      * All elements in the array must implement the {@link Comparable}
1016      * interface.  Furthermore, all elements in the array must be
1017      * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)} must
1018      * not throw a {@code ClassCastException} for any elements {@code e1}
1019      * and {@code e2} in the array).
1020      *
1021      * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
1022      * not be reordered as a result of the sort.
1023      *
1024      * <p>Implementation note: This implementation is a stable, adaptive,
1025      * iterative mergesort that requires far fewer than n lg(n) comparisons
1026      * when the input array is partially sorted, while offering the
1027      * performance of a traditional mergesort when the input array is
1028      * randomly ordered.  If the input array is nearly sorted, the
1029      * implementation requires approximately n comparisons.  Temporary
1030      * storage requirements vary from a small constant for nearly sorted
1031      * input arrays to n/2 object references for randomly ordered input
1032      * arrays.
1033      *
1034      * <p>The implementation takes equal advantage of ascending and
1035      * descending order in its input array, and can take advantage of
1036      * ascending and descending order in different parts of the same
1037      * input array.  It is well-suited to merging two or more sorted arrays:
1038      * simply concatenate the arrays and sort the resulting array.
1039      *
1040      * <p>The implementation was adapted from Tim Peters's list sort for Python
1041      * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
1042      * TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic
1043      * Sorting and Information Theoretic Complexity", in Proceedings of the
1044      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
1045      * January 1993.
1046      *
1047      * @param a the array to be sorted
1048      * @throws ClassCastException if the array contains elements that are not
1049      *         <i>mutually comparable</i> (for example, strings and integers)
1050      * @throws IllegalArgumentException (optional) if the natural
1051      *         ordering of the array elements is found to violate the
1052      *         {@link Comparable} contract
1053      */
sort(Object[] a)1054     public static void sort(Object[] a) {
1055         // BEGIN Android-removed: LegacyMergeSort support.
1056         /*
1057         if (LegacyMergeSort.userRequested)
1058             legacyMergeSort(a);
1059         else
1060         */
1061         // END Android-removed: LegacyMergeSort support.
1062             ComparableTimSort.sort(a, 0, a.length, null, 0, 0);
1063     }
1064 
1065     // BEGIN Android-removed: legacyMergeSort() (unused on Android).
1066     /*
1067     /** To be removed in a future release.
1068     private static void legacyMergeSort(Object[] a) {
1069         Object[] aux = a.clone();
1070         mergeSort(aux, a, 0, a.length, 0);
1071     }
1072     */
1073     // END Android-removed: legacyMergeSort() (unused on Android).
1074 
1075     /**
1076      * Sorts the specified range of the specified array of objects into
1077      * ascending order, according to the
1078      * {@linkplain Comparable natural ordering} of its
1079      * elements.  The range to be sorted extends from index
1080      * {@code fromIndex}, inclusive, to index {@code toIndex}, exclusive.
1081      * (If {@code fromIndex==toIndex}, the range to be sorted is empty.)  All
1082      * elements in this range must implement the {@link Comparable}
1083      * interface.  Furthermore, all elements in this range must be <i>mutually
1084      * comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a
1085      * {@code ClassCastException} for any elements {@code e1} and
1086      * {@code e2} in the array).
1087      *
1088      * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
1089      * not be reordered as a result of the sort.
1090      *
1091      * <p>Implementation note: This implementation is a stable, adaptive,
1092      * iterative mergesort that requires far fewer than n lg(n) comparisons
1093      * when the input array is partially sorted, while offering the
1094      * performance of a traditional mergesort when the input array is
1095      * randomly ordered.  If the input array is nearly sorted, the
1096      * implementation requires approximately n comparisons.  Temporary
1097      * storage requirements vary from a small constant for nearly sorted
1098      * input arrays to n/2 object references for randomly ordered input
1099      * arrays.
1100      *
1101      * <p>The implementation takes equal advantage of ascending and
1102      * descending order in its input array, and can take advantage of
1103      * ascending and descending order in different parts of the same
1104      * input array.  It is well-suited to merging two or more sorted arrays:
1105      * simply concatenate the arrays and sort the resulting array.
1106      *
1107      * <p>The implementation was adapted from Tim Peters's list sort for Python
1108      * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
1109      * TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic
1110      * Sorting and Information Theoretic Complexity", in Proceedings of the
1111      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
1112      * January 1993.
1113      *
1114      * @param a the array to be sorted
1115      * @param fromIndex the index of the first element (inclusive) to be
1116      *        sorted
1117      * @param toIndex the index of the last element (exclusive) to be sorted
1118      * @throws IllegalArgumentException if {@code fromIndex > toIndex} or
1119      *         (optional) if the natural ordering of the array elements is
1120      *         found to violate the {@link Comparable} contract
1121      * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
1122      *         {@code toIndex > a.length}
1123      * @throws ClassCastException if the array contains elements that are
1124      *         not <i>mutually comparable</i> (for example, strings and
1125      *         integers).
1126      */
sort(Object[] a, int fromIndex, int toIndex)1127     public static void sort(Object[] a, int fromIndex, int toIndex) {
1128         rangeCheck(a.length, fromIndex, toIndex);
1129         // BEGIN Android-removed: LegacyMergeSort support.
1130         /*
1131         if (LegacyMergeSort.userRequested)
1132             legacyMergeSort(a, fromIndex, toIndex);
1133         else
1134         */
1135         // END Android-removed: LegacyMergeSort support.
1136             ComparableTimSort.sort(a, fromIndex, toIndex, null, 0, 0);
1137     }
1138 
1139     // BEGIN Android-removed: legacyMergeSort() (unused on Android).
1140     /*
1141     /** To be removed in a future release. *
1142     private static void legacyMergeSort(Object[] a,
1143                                         int fromIndex, int toIndex) {
1144         Object[] aux = copyOfRange(a, fromIndex, toIndex);
1145         mergeSort(aux, a, fromIndex, toIndex, -fromIndex);
1146     }
1147     */
1148     // END Android-removed: legacyMergeSort() (unused on Android).
1149 
1150 
1151     /**
1152      * Tuning parameter: list size at or below which insertion sort will be
1153      * used in preference to mergesort.
1154      * To be removed in a future release.
1155      */
1156     private static final int INSERTIONSORT_THRESHOLD = 7;
1157 
1158     /**
1159      * Src is the source array that starts at index 0
1160      * Dest is the (possibly larger) array destination with a possible offset
1161      * low is the index in dest to start sorting
1162      * high is the end index in dest to end sorting
1163      * off is the offset to generate corresponding low, high in src
1164      * To be removed in a future release.
1165      */
1166     @SuppressWarnings({"unchecked", "rawtypes"})
mergeSort(Object[] src, Object[] dest, int low, int high, int off)1167     private static void mergeSort(Object[] src,
1168                                   Object[] dest,
1169                                   int low,
1170                                   int high,
1171                                   int off) {
1172         int length = high - low;
1173 
1174         // Insertion sort on smallest arrays
1175         if (length < INSERTIONSORT_THRESHOLD) {
1176             for (int i=low; i<high; i++)
1177                 for (int j=i; j>low &&
1178                          ((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)
1179                     swap(dest, j, j-1);
1180             return;
1181         }
1182 
1183         // Recursively sort halves of dest into src
1184         int destLow  = low;
1185         int destHigh = high;
1186         low  += off;
1187         high += off;
1188         int mid = (low + high) >>> 1;
1189         mergeSort(dest, src, low, mid, -off);
1190         mergeSort(dest, src, mid, high, -off);
1191 
1192         // If list is already sorted, just copy from src to dest.  This is an
1193         // optimization that results in faster sorts for nearly ordered lists.
1194         if (((Comparable)src[mid-1]).compareTo(src[mid]) <= 0) {
1195             System.arraycopy(src, low, dest, destLow, length);
1196             return;
1197         }
1198 
1199         // Merge sorted halves (now in src) into dest
1200         for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
1201             if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0)
1202                 dest[i] = src[p++];
1203             else
1204                 dest[i] = src[q++];
1205         }
1206     }
1207 
1208     /**
1209      * Swaps x[a] with x[b].
1210      */
swap(Object[] x, int a, int b)1211     private static void swap(Object[] x, int a, int b) {
1212         Object t = x[a];
1213         x[a] = x[b];
1214         x[b] = t;
1215     }
1216 
1217     /**
1218      * Sorts the specified array of objects according to the order induced by
1219      * the specified comparator.  All elements in the array must be
1220      * <i>mutually comparable</i> by the specified comparator (that is,
1221      * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
1222      * for any elements {@code e1} and {@code e2} in the array).
1223      *
1224      * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
1225      * not be reordered as a result of the sort.
1226      *
1227      * <p>Implementation note: This implementation is a stable, adaptive,
1228      * iterative mergesort that requires far fewer than n lg(n) comparisons
1229      * when the input array is partially sorted, while offering the
1230      * performance of a traditional mergesort when the input array is
1231      * randomly ordered.  If the input array is nearly sorted, the
1232      * implementation requires approximately n comparisons.  Temporary
1233      * storage requirements vary from a small constant for nearly sorted
1234      * input arrays to n/2 object references for randomly ordered input
1235      * arrays.
1236      *
1237      * <p>The implementation takes equal advantage of ascending and
1238      * descending order in its input array, and can take advantage of
1239      * ascending and descending order in different parts of the same
1240      * input array.  It is well-suited to merging two or more sorted arrays:
1241      * simply concatenate the arrays and sort the resulting array.
1242      *
1243      * <p>The implementation was adapted from Tim Peters's list sort for Python
1244      * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
1245      * TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic
1246      * Sorting and Information Theoretic Complexity", in Proceedings of the
1247      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
1248      * January 1993.
1249      *
1250      * @param <T> the class of the objects to be sorted
1251      * @param a the array to be sorted
1252      * @param c the comparator to determine the order of the array.  A
1253      *        {@code null} value indicates that the elements'
1254      *        {@linkplain Comparable natural ordering} should be used.
1255      * @throws ClassCastException if the array contains elements that are
1256      *         not <i>mutually comparable</i> using the specified comparator
1257      * @throws IllegalArgumentException (optional) if the comparator is
1258      *         found to violate the {@link Comparator} contract
1259      */
sort(T[] a, Comparator<? super T> c)1260     public static <T> void sort(T[] a, Comparator<? super T> c) {
1261         if (c == null) {
1262             sort(a);
1263         } else {
1264             // BEGIN Android-removed: LegacyMergeSort support.
1265             /*
1266             if (LegacyMergeSort.userRequested)
1267                 legacyMergeSort(a, c);
1268             else
1269             */
1270             // END Android-removed: LegacyMergeSort support.
1271                 TimSort.sort(a, 0, a.length, c, null, 0, 0);
1272         }
1273     }
1274 
1275     // BEGIN Android-removed: legacyMergeSort() (unused on Android).
1276     /** To be removed in a future release. *
1277     private static <T> void legacyMergeSort(T[] a, Comparator<? super T> c) {
1278         T[] aux = a.clone();
1279         if (c==null)
1280             mergeSort(aux, a, 0, a.length, 0);
1281         else
1282             mergeSort(aux, a, 0, a.length, 0, c);
1283     }
1284     */
1285     // END Android-removed: legacyMergeSort() (unused on Android).
1286 
1287     /**
1288      * Sorts the specified range of the specified array of objects according
1289      * to the order induced by the specified comparator.  The range to be
1290      * sorted extends from index {@code fromIndex}, inclusive, to index
1291      * {@code toIndex}, exclusive.  (If {@code fromIndex==toIndex}, the
1292      * range to be sorted is empty.)  All elements in the range must be
1293      * <i>mutually comparable</i> by the specified comparator (that is,
1294      * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
1295      * for any elements {@code e1} and {@code e2} in the range).
1296      *
1297      * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
1298      * not be reordered as a result of the sort.
1299      *
1300      * <p>Implementation note: This implementation is a stable, adaptive,
1301      * iterative mergesort that requires far fewer than n lg(n) comparisons
1302      * when the input array is partially sorted, while offering the
1303      * performance of a traditional mergesort when the input array is
1304      * randomly ordered.  If the input array is nearly sorted, the
1305      * implementation requires approximately n comparisons.  Temporary
1306      * storage requirements vary from a small constant for nearly sorted
1307      * input arrays to n/2 object references for randomly ordered input
1308      * arrays.
1309      *
1310      * <p>The implementation takes equal advantage of ascending and
1311      * descending order in its input array, and can take advantage of
1312      * ascending and descending order in different parts of the same
1313      * input array.  It is well-suited to merging two or more sorted arrays:
1314      * simply concatenate the arrays and sort the resulting array.
1315      *
1316      * <p>The implementation was adapted from Tim Peters's list sort for Python
1317      * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
1318      * TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic
1319      * Sorting and Information Theoretic Complexity", in Proceedings of the
1320      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
1321      * January 1993.
1322      *
1323      * @param <T> the class of the objects to be sorted
1324      * @param a the array to be sorted
1325      * @param fromIndex the index of the first element (inclusive) to be
1326      *        sorted
1327      * @param toIndex the index of the last element (exclusive) to be sorted
1328      * @param c the comparator to determine the order of the array.  A
1329      *        {@code null} value indicates that the elements'
1330      *        {@linkplain Comparable natural ordering} should be used.
1331      * @throws ClassCastException if the array contains elements that are not
1332      *         <i>mutually comparable</i> using the specified comparator.
1333      * @throws IllegalArgumentException if {@code fromIndex > toIndex} or
1334      *         (optional) if the comparator is found to violate the
1335      *         {@link Comparator} contract
1336      * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
1337      *         {@code toIndex > a.length}
1338      */
sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)1339     public static <T> void sort(T[] a, int fromIndex, int toIndex,
1340                                 Comparator<? super T> c) {
1341         if (c == null) {
1342             sort(a, fromIndex, toIndex);
1343         } else {
1344             rangeCheck(a.length, fromIndex, toIndex);
1345             // BEGIN Android-removed: LegacyMergeSort support.
1346             /*
1347             if (LegacyMergeSort.userRequested)
1348                 legacyMergeSort(a, fromIndex, toIndex, c);
1349             else
1350             */
1351             // END Android-removed: LegacyMergeSort support.
1352                 TimSort.sort(a, fromIndex, toIndex, c, null, 0, 0);
1353         }
1354     }
1355 
1356     // BEGIN Android-removed: legacyMergeSort() and mergeSort() (unused on Android).
1357     /*
1358     /** To be removed in a future release. *
1359     private static <T> void legacyMergeSort(T[] a, int fromIndex, int toIndex,
1360                                             Comparator<? super T> c) {
1361         T[] aux = copyOfRange(a, fromIndex, toIndex);
1362         if (c==null)
1363             mergeSort(aux, a, fromIndex, toIndex, -fromIndex);
1364         else
1365             mergeSort(aux, a, fromIndex, toIndex, -fromIndex, c);
1366     }
1367 
1368     /**
1369      * Src is the source array that starts at index 0
1370      * Dest is the (possibly larger) array destination with a possible offset
1371      * low is the index in dest to start sorting
1372      * high is the end index in dest to end sorting
1373      * off is the offset into src corresponding to low in dest
1374      * To be removed in a future release.
1375      *
1376     @SuppressWarnings({"rawtypes", "unchecked"})
1377     private static void mergeSort(Object[] src,
1378                                   Object[] dest,
1379                                   int low, int high, int off,
1380                                   Comparator c) {
1381         int length = high - low;
1382 
1383         // Insertion sort on smallest arrays
1384         if (length < INSERTIONSORT_THRESHOLD) {
1385             for (int i=low; i<high; i++)
1386                 for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)
1387                     swap(dest, j, j-1);
1388             return;
1389         }
1390 
1391         // Recursively sort halves of dest into src
1392         int destLow  = low;
1393         int destHigh = high;
1394         low  += off;
1395         high += off;
1396         int mid = (low + high) >>> 1;
1397         mergeSort(dest, src, low, mid, -off, c);
1398         mergeSort(dest, src, mid, high, -off, c);
1399 
1400         // If list is already sorted, just copy from src to dest.  This is an
1401         // optimization that results in faster sorts for nearly ordered lists.
1402         if (c.compare(src[mid-1], src[mid]) <= 0) {
1403            System.arraycopy(src, low, dest, destLow, length);
1404            return;
1405         }
1406 
1407         // Merge sorted halves (now in src) into dest
1408         for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
1409             if (q >= high || p < mid && c.compare(src[p], src[q]) <= 0)
1410                 dest[i] = src[p++];
1411             else
1412                 dest[i] = src[q++];
1413         }
1414     }
1415     */
1416     // END Android-removed: legacyMergeSort() and mergeSort() (unused on Android).
1417 
1418     // Parallel prefix
1419 
1420     /**
1421      * Cumulates, in parallel, each element of the given array in place,
1422      * using the supplied function. For example if the array initially
1423      * holds {@code [2, 1, 0, 3]} and the operation performs addition,
1424      * then upon return the array holds {@code [2, 3, 3, 6]}.
1425      * Parallel prefix computation is usually more efficient than
1426      * sequential loops for large arrays.
1427      *
1428      * @param <T> the class of the objects in the array
1429      * @param array the array, which is modified in-place by this method
1430      * @param op a side-effect-free, associative function to perform the
1431      * cumulation
1432      * @throws NullPointerException if the specified array or function is null
1433      * @since 1.8
1434      */
parallelPrefix(T[] array, BinaryOperator<T> op)1435     public static <T> void parallelPrefix(T[] array, BinaryOperator<T> op) {
1436         Objects.requireNonNull(op);
1437         if (array.length > 0)
1438             new ArrayPrefixHelpers.CumulateTask<>
1439                     (null, op, array, 0, array.length).invoke();
1440     }
1441 
1442     /**
1443      * Performs {@link #parallelPrefix(Object[], BinaryOperator)}
1444      * for the given subrange of the array.
1445      *
1446      * @param <T> the class of the objects in the array
1447      * @param array the array
1448      * @param fromIndex the index of the first element, inclusive
1449      * @param toIndex the index of the last element, exclusive
1450      * @param op a side-effect-free, associative function to perform the
1451      * cumulation
1452      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
1453      * @throws ArrayIndexOutOfBoundsException
1454      *     if {@code fromIndex < 0} or {@code toIndex > array.length}
1455      * @throws NullPointerException if the specified array or function is null
1456      * @since 1.8
1457      */
parallelPrefix(T[] array, int fromIndex, int toIndex, BinaryOperator<T> op)1458     public static <T> void parallelPrefix(T[] array, int fromIndex,
1459                                           int toIndex, BinaryOperator<T> op) {
1460         Objects.requireNonNull(op);
1461         rangeCheck(array.length, fromIndex, toIndex);
1462         if (fromIndex < toIndex)
1463             new ArrayPrefixHelpers.CumulateTask<>
1464                     (null, op, array, fromIndex, toIndex).invoke();
1465     }
1466 
1467     /**
1468      * Cumulates, in parallel, each element of the given array in place,
1469      * using the supplied function. For example if the array initially
1470      * holds {@code [2, 1, 0, 3]} and the operation performs addition,
1471      * then upon return the array holds {@code [2, 3, 3, 6]}.
1472      * Parallel prefix computation is usually more efficient than
1473      * sequential loops for large arrays.
1474      *
1475      * @param array the array, which is modified in-place by this method
1476      * @param op a side-effect-free, associative function to perform the
1477      * cumulation
1478      * @throws NullPointerException if the specified array or function is null
1479      * @since 1.8
1480      */
parallelPrefix(long[] array, LongBinaryOperator op)1481     public static void parallelPrefix(long[] array, LongBinaryOperator op) {
1482         Objects.requireNonNull(op);
1483         if (array.length > 0)
1484             new ArrayPrefixHelpers.LongCumulateTask
1485                     (null, op, array, 0, array.length).invoke();
1486     }
1487 
1488     /**
1489      * Performs {@link #parallelPrefix(long[], LongBinaryOperator)}
1490      * for the given subrange of the array.
1491      *
1492      * @param array the array
1493      * @param fromIndex the index of the first element, inclusive
1494      * @param toIndex the index of the last element, exclusive
1495      * @param op a side-effect-free, associative function to perform the
1496      * cumulation
1497      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
1498      * @throws ArrayIndexOutOfBoundsException
1499      *     if {@code fromIndex < 0} or {@code toIndex > array.length}
1500      * @throws NullPointerException if the specified array or function is null
1501      * @since 1.8
1502      */
parallelPrefix(long[] array, int fromIndex, int toIndex, LongBinaryOperator op)1503     public static void parallelPrefix(long[] array, int fromIndex,
1504                                       int toIndex, LongBinaryOperator op) {
1505         Objects.requireNonNull(op);
1506         rangeCheck(array.length, fromIndex, toIndex);
1507         if (fromIndex < toIndex)
1508             new ArrayPrefixHelpers.LongCumulateTask
1509                     (null, op, array, fromIndex, toIndex).invoke();
1510     }
1511 
1512     /**
1513      * Cumulates, in parallel, each element of the given array in place,
1514      * using the supplied function. For example if the array initially
1515      * holds {@code [2.0, 1.0, 0.0, 3.0]} and the operation performs addition,
1516      * then upon return the array holds {@code [2.0, 3.0, 3.0, 6.0]}.
1517      * Parallel prefix computation is usually more efficient than
1518      * sequential loops for large arrays.
1519      *
1520      * <p> Because floating-point operations may not be strictly associative,
1521      * the returned result may not be identical to the value that would be
1522      * obtained if the operation was performed sequentially.
1523      *
1524      * @param array the array, which is modified in-place by this method
1525      * @param op a side-effect-free function to perform the cumulation
1526      * @throws NullPointerException if the specified array or function is null
1527      * @since 1.8
1528      */
parallelPrefix(double[] array, DoubleBinaryOperator op)1529     public static void parallelPrefix(double[] array, DoubleBinaryOperator op) {
1530         Objects.requireNonNull(op);
1531         if (array.length > 0)
1532             new ArrayPrefixHelpers.DoubleCumulateTask
1533                     (null, op, array, 0, array.length).invoke();
1534     }
1535 
1536     /**
1537      * Performs {@link #parallelPrefix(double[], DoubleBinaryOperator)}
1538      * for the given subrange of the array.
1539      *
1540      * @param array the array
1541      * @param fromIndex the index of the first element, inclusive
1542      * @param toIndex the index of the last element, exclusive
1543      * @param op a side-effect-free, associative function to perform the
1544      * cumulation
1545      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
1546      * @throws ArrayIndexOutOfBoundsException
1547      *     if {@code fromIndex < 0} or {@code toIndex > array.length}
1548      * @throws NullPointerException if the specified array or function is null
1549      * @since 1.8
1550      */
parallelPrefix(double[] array, int fromIndex, int toIndex, DoubleBinaryOperator op)1551     public static void parallelPrefix(double[] array, int fromIndex,
1552                                       int toIndex, DoubleBinaryOperator op) {
1553         Objects.requireNonNull(op);
1554         rangeCheck(array.length, fromIndex, toIndex);
1555         if (fromIndex < toIndex)
1556             new ArrayPrefixHelpers.DoubleCumulateTask
1557                     (null, op, array, fromIndex, toIndex).invoke();
1558     }
1559 
1560     /**
1561      * Cumulates, in parallel, each element of the given array in place,
1562      * using the supplied function. For example if the array initially
1563      * holds {@code [2, 1, 0, 3]} and the operation performs addition,
1564      * then upon return the array holds {@code [2, 3, 3, 6]}.
1565      * Parallel prefix computation is usually more efficient than
1566      * sequential loops for large arrays.
1567      *
1568      * @param array the array, which is modified in-place by this method
1569      * @param op a side-effect-free, associative function to perform the
1570      * cumulation
1571      * @throws NullPointerException if the specified array or function is null
1572      * @since 1.8
1573      */
parallelPrefix(int[] array, IntBinaryOperator op)1574     public static void parallelPrefix(int[] array, IntBinaryOperator op) {
1575         Objects.requireNonNull(op);
1576         if (array.length > 0)
1577             new ArrayPrefixHelpers.IntCumulateTask
1578                     (null, op, array, 0, array.length).invoke();
1579     }
1580 
1581     /**
1582      * Performs {@link #parallelPrefix(int[], IntBinaryOperator)}
1583      * for the given subrange of the array.
1584      *
1585      * @param array the array
1586      * @param fromIndex the index of the first element, inclusive
1587      * @param toIndex the index of the last element, exclusive
1588      * @param op a side-effect-free, associative function to perform the
1589      * cumulation
1590      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
1591      * @throws ArrayIndexOutOfBoundsException
1592      *     if {@code fromIndex < 0} or {@code toIndex > array.length}
1593      * @throws NullPointerException if the specified array or function is null
1594      * @since 1.8
1595      */
parallelPrefix(int[] array, int fromIndex, int toIndex, IntBinaryOperator op)1596     public static void parallelPrefix(int[] array, int fromIndex,
1597                                       int toIndex, IntBinaryOperator op) {
1598         Objects.requireNonNull(op);
1599         rangeCheck(array.length, fromIndex, toIndex);
1600         if (fromIndex < toIndex)
1601             new ArrayPrefixHelpers.IntCumulateTask
1602                     (null, op, array, fromIndex, toIndex).invoke();
1603     }
1604 
1605     // Searching
1606 
1607     /**
1608      * Searches the specified array of longs for the specified value using the
1609      * binary search algorithm.  The array must be sorted (as
1610      * by the {@link #sort(long[])} method) prior to making this call.  If it
1611      * is not sorted, the results are undefined.  If the array contains
1612      * multiple elements with the specified value, there is no guarantee which
1613      * one will be found.
1614      *
1615      * @param a the array to be searched
1616      * @param key the value to be searched for
1617      * @return index of the search key, if it is contained in the array;
1618      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
1619      *         <i>insertion point</i> is defined as the point at which the
1620      *         key would be inserted into the array: the index of the first
1621      *         element greater than the key, or {@code a.length} if all
1622      *         elements in the array are less than the specified key.  Note
1623      *         that this guarantees that the return value will be &gt;= 0 if
1624      *         and only if the key is found.
1625      */
binarySearch(long[] a, long key)1626     public static int binarySearch(long[] a, long key) {
1627         return binarySearch0(a, 0, a.length, key);
1628     }
1629 
1630     /**
1631      * Searches a range of
1632      * the specified array of longs for the specified value using the
1633      * binary search algorithm.
1634      * The range must be sorted (as
1635      * by the {@link #sort(long[], int, int)} method)
1636      * prior to making this call.  If it
1637      * is not sorted, the results are undefined.  If the range contains
1638      * multiple elements with the specified value, there is no guarantee which
1639      * one will be found.
1640      *
1641      * @param a the array to be searched
1642      * @param fromIndex the index of the first element (inclusive) to be
1643      *          searched
1644      * @param toIndex the index of the last element (exclusive) to be searched
1645      * @param key the value to be searched for
1646      * @return index of the search key, if it is contained in the array
1647      *         within the specified range;
1648      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
1649      *         <i>insertion point</i> is defined as the point at which the
1650      *         key would be inserted into the array: the index of the first
1651      *         element in the range greater than the key,
1652      *         or {@code toIndex} if all
1653      *         elements in the range are less than the specified key.  Note
1654      *         that this guarantees that the return value will be &gt;= 0 if
1655      *         and only if the key is found.
1656      * @throws IllegalArgumentException
1657      *         if {@code fromIndex > toIndex}
1658      * @throws ArrayIndexOutOfBoundsException
1659      *         if {@code fromIndex < 0 or toIndex > a.length}
1660      * @since 1.6
1661      */
binarySearch(long[] a, int fromIndex, int toIndex, long key)1662     public static int binarySearch(long[] a, int fromIndex, int toIndex,
1663                                    long key) {
1664         rangeCheck(a.length, fromIndex, toIndex);
1665         return binarySearch0(a, fromIndex, toIndex, key);
1666     }
1667 
1668     // Like public version, but without range checks.
binarySearch0(long[] a, int fromIndex, int toIndex, long key)1669     private static int binarySearch0(long[] a, int fromIndex, int toIndex,
1670                                      long key) {
1671         int low = fromIndex;
1672         int high = toIndex - 1;
1673 
1674         while (low <= high) {
1675             int mid = (low + high) >>> 1;
1676             long midVal = a[mid];
1677 
1678             if (midVal < key)
1679                 low = mid + 1;
1680             else if (midVal > key)
1681                 high = mid - 1;
1682             else
1683                 return mid; // key found
1684         }
1685         return -(low + 1);  // key not found.
1686     }
1687 
1688     /**
1689      * Searches the specified array of ints for the specified value using the
1690      * binary search algorithm.  The array must be sorted (as
1691      * by the {@link #sort(int[])} method) prior to making this call.  If it
1692      * is not sorted, the results are undefined.  If the array contains
1693      * multiple elements with the specified value, there is no guarantee which
1694      * one will be found.
1695      *
1696      * @param a the array to be searched
1697      * @param key the value to be searched for
1698      * @return index of the search key, if it is contained in the array;
1699      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
1700      *         <i>insertion point</i> is defined as the point at which the
1701      *         key would be inserted into the array: the index of the first
1702      *         element greater than the key, or {@code a.length} if all
1703      *         elements in the array are less than the specified key.  Note
1704      *         that this guarantees that the return value will be &gt;= 0 if
1705      *         and only if the key is found.
1706      */
binarySearch(int[] a, int key)1707     public static int binarySearch(int[] a, int key) {
1708         return binarySearch0(a, 0, a.length, key);
1709     }
1710 
1711     /**
1712      * Searches a range of
1713      * the specified array of ints for the specified value using the
1714      * binary search algorithm.
1715      * The range must be sorted (as
1716      * by the {@link #sort(int[], int, int)} method)
1717      * prior to making this call.  If it
1718      * is not sorted, the results are undefined.  If the range contains
1719      * multiple elements with the specified value, there is no guarantee which
1720      * one will be found.
1721      *
1722      * @param a the array to be searched
1723      * @param fromIndex the index of the first element (inclusive) to be
1724      *          searched
1725      * @param toIndex the index of the last element (exclusive) to be searched
1726      * @param key the value to be searched for
1727      * @return index of the search key, if it is contained in the array
1728      *         within the specified range;
1729      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
1730      *         <i>insertion point</i> is defined as the point at which the
1731      *         key would be inserted into the array: the index of the first
1732      *         element in the range greater than the key,
1733      *         or {@code toIndex} if all
1734      *         elements in the range are less than the specified key.  Note
1735      *         that this guarantees that the return value will be &gt;= 0 if
1736      *         and only if the key is found.
1737      * @throws IllegalArgumentException
1738      *         if {@code fromIndex > toIndex}
1739      * @throws ArrayIndexOutOfBoundsException
1740      *         if {@code fromIndex < 0 or toIndex > a.length}
1741      * @since 1.6
1742      */
binarySearch(int[] a, int fromIndex, int toIndex, int key)1743     public static int binarySearch(int[] a, int fromIndex, int toIndex,
1744                                    int key) {
1745         rangeCheck(a.length, fromIndex, toIndex);
1746         return binarySearch0(a, fromIndex, toIndex, key);
1747     }
1748 
1749     // Like public version, but without range checks.
binarySearch0(int[] a, int fromIndex, int toIndex, int key)1750     private static int binarySearch0(int[] a, int fromIndex, int toIndex,
1751                                      int key) {
1752         int low = fromIndex;
1753         int high = toIndex - 1;
1754 
1755         while (low <= high) {
1756             int mid = (low + high) >>> 1;
1757             int midVal = a[mid];
1758 
1759             if (midVal < key)
1760                 low = mid + 1;
1761             else if (midVal > key)
1762                 high = mid - 1;
1763             else
1764                 return mid; // key found
1765         }
1766         return -(low + 1);  // key not found.
1767     }
1768 
1769     /**
1770      * Searches the specified array of shorts for the specified value using
1771      * the binary search algorithm.  The array must be sorted
1772      * (as by the {@link #sort(short[])} method) prior to making this call.  If
1773      * it is not sorted, the results are undefined.  If the array contains
1774      * multiple elements with the specified value, there is no guarantee which
1775      * one will be found.
1776      *
1777      * @param a the array to be searched
1778      * @param key the value to be searched for
1779      * @return index of the search key, if it is contained in the array;
1780      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
1781      *         <i>insertion point</i> is defined as the point at which the
1782      *         key would be inserted into the array: the index of the first
1783      *         element greater than the key, or {@code a.length} if all
1784      *         elements in the array are less than the specified key.  Note
1785      *         that this guarantees that the return value will be &gt;= 0 if
1786      *         and only if the key is found.
1787      */
binarySearch(short[] a, short key)1788     public static int binarySearch(short[] a, short key) {
1789         return binarySearch0(a, 0, a.length, key);
1790     }
1791 
1792     /**
1793      * Searches a range of
1794      * the specified array of shorts for the specified value using
1795      * the binary search algorithm.
1796      * The range must be sorted
1797      * (as by the {@link #sort(short[], int, int)} method)
1798      * prior to making this call.  If
1799      * it is not sorted, the results are undefined.  If the range contains
1800      * multiple elements with the specified value, there is no guarantee which
1801      * one will be found.
1802      *
1803      * @param a the array to be searched
1804      * @param fromIndex the index of the first element (inclusive) to be
1805      *          searched
1806      * @param toIndex the index of the last element (exclusive) to be searched
1807      * @param key the value to be searched for
1808      * @return index of the search key, if it is contained in the array
1809      *         within the specified range;
1810      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
1811      *         <i>insertion point</i> is defined as the point at which the
1812      *         key would be inserted into the array: the index of the first
1813      *         element in the range greater than the key,
1814      *         or {@code toIndex} if all
1815      *         elements in the range are less than the specified key.  Note
1816      *         that this guarantees that the return value will be &gt;= 0 if
1817      *         and only if the key is found.
1818      * @throws IllegalArgumentException
1819      *         if {@code fromIndex > toIndex}
1820      * @throws ArrayIndexOutOfBoundsException
1821      *         if {@code fromIndex < 0 or toIndex > a.length}
1822      * @since 1.6
1823      */
binarySearch(short[] a, int fromIndex, int toIndex, short key)1824     public static int binarySearch(short[] a, int fromIndex, int toIndex,
1825                                    short key) {
1826         rangeCheck(a.length, fromIndex, toIndex);
1827         return binarySearch0(a, fromIndex, toIndex, key);
1828     }
1829 
1830     // Like public version, but without range checks.
binarySearch0(short[] a, int fromIndex, int toIndex, short key)1831     private static int binarySearch0(short[] a, int fromIndex, int toIndex,
1832                                      short key) {
1833         int low = fromIndex;
1834         int high = toIndex - 1;
1835 
1836         while (low <= high) {
1837             int mid = (low + high) >>> 1;
1838             short midVal = a[mid];
1839 
1840             if (midVal < key)
1841                 low = mid + 1;
1842             else if (midVal > key)
1843                 high = mid - 1;
1844             else
1845                 return mid; // key found
1846         }
1847         return -(low + 1);  // key not found.
1848     }
1849 
1850     /**
1851      * Searches the specified array of chars for the specified value using the
1852      * binary search algorithm.  The array must be sorted (as
1853      * by the {@link #sort(char[])} method) prior to making this call.  If it
1854      * is not sorted, the results are undefined.  If the array contains
1855      * multiple elements with the specified value, there is no guarantee which
1856      * one will be found.
1857      *
1858      * @param a the array to be searched
1859      * @param key the value to be searched for
1860      * @return index of the search key, if it is contained in the array;
1861      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
1862      *         <i>insertion point</i> is defined as the point at which the
1863      *         key would be inserted into the array: the index of the first
1864      *         element greater than the key, or {@code a.length} if all
1865      *         elements in the array are less than the specified key.  Note
1866      *         that this guarantees that the return value will be &gt;= 0 if
1867      *         and only if the key is found.
1868      */
binarySearch(char[] a, char key)1869     public static int binarySearch(char[] a, char key) {
1870         return binarySearch0(a, 0, a.length, key);
1871     }
1872 
1873     /**
1874      * Searches a range of
1875      * the specified array of chars for the specified value using the
1876      * binary search algorithm.
1877      * The range must be sorted (as
1878      * by the {@link #sort(char[], int, int)} method)
1879      * prior to making this call.  If it
1880      * is not sorted, the results are undefined.  If the range contains
1881      * multiple elements with the specified value, there is no guarantee which
1882      * one will be found.
1883      *
1884      * @param a the array to be searched
1885      * @param fromIndex the index of the first element (inclusive) to be
1886      *          searched
1887      * @param toIndex the index of the last element (exclusive) to be searched
1888      * @param key the value to be searched for
1889      * @return index of the search key, if it is contained in the array
1890      *         within the specified range;
1891      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
1892      *         <i>insertion point</i> is defined as the point at which the
1893      *         key would be inserted into the array: the index of the first
1894      *         element in the range greater than the key,
1895      *         or {@code toIndex} if all
1896      *         elements in the range are less than the specified key.  Note
1897      *         that this guarantees that the return value will be &gt;= 0 if
1898      *         and only if the key is found.
1899      * @throws IllegalArgumentException
1900      *         if {@code fromIndex > toIndex}
1901      * @throws ArrayIndexOutOfBoundsException
1902      *         if {@code fromIndex < 0 or toIndex > a.length}
1903      * @since 1.6
1904      */
binarySearch(char[] a, int fromIndex, int toIndex, char key)1905     public static int binarySearch(char[] a, int fromIndex, int toIndex,
1906                                    char key) {
1907         rangeCheck(a.length, fromIndex, toIndex);
1908         return binarySearch0(a, fromIndex, toIndex, key);
1909     }
1910 
1911     // Like public version, but without range checks.
binarySearch0(char[] a, int fromIndex, int toIndex, char key)1912     private static int binarySearch0(char[] a, int fromIndex, int toIndex,
1913                                      char key) {
1914         int low = fromIndex;
1915         int high = toIndex - 1;
1916 
1917         while (low <= high) {
1918             int mid = (low + high) >>> 1;
1919             char midVal = a[mid];
1920 
1921             if (midVal < key)
1922                 low = mid + 1;
1923             else if (midVal > key)
1924                 high = mid - 1;
1925             else
1926                 return mid; // key found
1927         }
1928         return -(low + 1);  // key not found.
1929     }
1930 
1931     /**
1932      * Searches the specified array of bytes for the specified value using the
1933      * binary search algorithm.  The array must be sorted (as
1934      * by the {@link #sort(byte[])} method) prior to making this call.  If it
1935      * is not sorted, the results are undefined.  If the array contains
1936      * multiple elements with the specified value, there is no guarantee which
1937      * one will be found.
1938      *
1939      * @param a the array to be searched
1940      * @param key the value to be searched for
1941      * @return index of the search key, if it is contained in the array;
1942      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
1943      *         <i>insertion point</i> is defined as the point at which the
1944      *         key would be inserted into the array: the index of the first
1945      *         element greater than the key, or {@code a.length} if all
1946      *         elements in the array are less than the specified key.  Note
1947      *         that this guarantees that the return value will be &gt;= 0 if
1948      *         and only if the key is found.
1949      */
binarySearch(byte[] a, byte key)1950     public static int binarySearch(byte[] a, byte key) {
1951         return binarySearch0(a, 0, a.length, key);
1952     }
1953 
1954     /**
1955      * Searches a range of
1956      * the specified array of bytes for the specified value using the
1957      * binary search algorithm.
1958      * The range must be sorted (as
1959      * by the {@link #sort(byte[], int, int)} method)
1960      * prior to making this call.  If it
1961      * is not sorted, the results are undefined.  If the range contains
1962      * multiple elements with the specified value, there is no guarantee which
1963      * one will be found.
1964      *
1965      * @param a the array to be searched
1966      * @param fromIndex the index of the first element (inclusive) to be
1967      *          searched
1968      * @param toIndex the index of the last element (exclusive) to be searched
1969      * @param key the value to be searched for
1970      * @return index of the search key, if it is contained in the array
1971      *         within the specified range;
1972      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
1973      *         <i>insertion point</i> is defined as the point at which the
1974      *         key would be inserted into the array: the index of the first
1975      *         element in the range greater than the key,
1976      *         or {@code toIndex} if all
1977      *         elements in the range are less than the specified key.  Note
1978      *         that this guarantees that the return value will be &gt;= 0 if
1979      *         and only if the key is found.
1980      * @throws IllegalArgumentException
1981      *         if {@code fromIndex > toIndex}
1982      * @throws ArrayIndexOutOfBoundsException
1983      *         if {@code fromIndex < 0 or toIndex > a.length}
1984      * @since 1.6
1985      */
binarySearch(byte[] a, int fromIndex, int toIndex, byte key)1986     public static int binarySearch(byte[] a, int fromIndex, int toIndex,
1987                                    byte key) {
1988         rangeCheck(a.length, fromIndex, toIndex);
1989         return binarySearch0(a, fromIndex, toIndex, key);
1990     }
1991 
1992     // Like public version, but without range checks.
binarySearch0(byte[] a, int fromIndex, int toIndex, byte key)1993     private static int binarySearch0(byte[] a, int fromIndex, int toIndex,
1994                                      byte key) {
1995         int low = fromIndex;
1996         int high = toIndex - 1;
1997 
1998         while (low <= high) {
1999             int mid = (low + high) >>> 1;
2000             byte midVal = a[mid];
2001 
2002             if (midVal < key)
2003                 low = mid + 1;
2004             else if (midVal > key)
2005                 high = mid - 1;
2006             else
2007                 return mid; // key found
2008         }
2009         return -(low + 1);  // key not found.
2010     }
2011 
2012     /**
2013      * Searches the specified array of doubles for the specified value using
2014      * the binary search algorithm.  The array must be sorted
2015      * (as by the {@link #sort(double[])} method) prior to making this call.
2016      * If it is not sorted, the results are undefined.  If the array contains
2017      * multiple elements with the specified value, there is no guarantee which
2018      * one will be found.  This method considers all NaN values to be
2019      * equivalent and equal.
2020      *
2021      * @param a the array to be searched
2022      * @param key the value to be searched for
2023      * @return index of the search key, if it is contained in the array;
2024      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
2025      *         <i>insertion point</i> is defined as the point at which the
2026      *         key would be inserted into the array: the index of the first
2027      *         element greater than the key, or {@code a.length} if all
2028      *         elements in the array are less than the specified key.  Note
2029      *         that this guarantees that the return value will be &gt;= 0 if
2030      *         and only if the key is found.
2031      */
binarySearch(double[] a, double key)2032     public static int binarySearch(double[] a, double key) {
2033         return binarySearch0(a, 0, a.length, key);
2034     }
2035 
2036     /**
2037      * Searches a range of
2038      * the specified array of doubles for the specified value using
2039      * the binary search algorithm.
2040      * The range must be sorted
2041      * (as by the {@link #sort(double[], int, int)} method)
2042      * prior to making this call.
2043      * If it is not sorted, the results are undefined.  If the range contains
2044      * multiple elements with the specified value, there is no guarantee which
2045      * one will be found.  This method considers all NaN values to be
2046      * equivalent and equal.
2047      *
2048      * @param a the array to be searched
2049      * @param fromIndex the index of the first element (inclusive) to be
2050      *          searched
2051      * @param toIndex the index of the last element (exclusive) to be searched
2052      * @param key the value to be searched for
2053      * @return index of the search key, if it is contained in the array
2054      *         within the specified range;
2055      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
2056      *         <i>insertion point</i> is defined as the point at which the
2057      *         key would be inserted into the array: the index of the first
2058      *         element in the range greater than the key,
2059      *         or {@code toIndex} if all
2060      *         elements in the range are less than the specified key.  Note
2061      *         that this guarantees that the return value will be &gt;= 0 if
2062      *         and only if the key is found.
2063      * @throws IllegalArgumentException
2064      *         if {@code fromIndex > toIndex}
2065      * @throws ArrayIndexOutOfBoundsException
2066      *         if {@code fromIndex < 0 or toIndex > a.length}
2067      * @since 1.6
2068      */
binarySearch(double[] a, int fromIndex, int toIndex, double key)2069     public static int binarySearch(double[] a, int fromIndex, int toIndex,
2070                                    double key) {
2071         rangeCheck(a.length, fromIndex, toIndex);
2072         return binarySearch0(a, fromIndex, toIndex, key);
2073     }
2074 
2075     // Like public version, but without range checks.
binarySearch0(double[] a, int fromIndex, int toIndex, double key)2076     private static int binarySearch0(double[] a, int fromIndex, int toIndex,
2077                                      double key) {
2078         int low = fromIndex;
2079         int high = toIndex - 1;
2080 
2081         while (low <= high) {
2082             int mid = (low + high) >>> 1;
2083             double midVal = a[mid];
2084 
2085             if (midVal < key)
2086                 low = mid + 1;  // Neither val is NaN, thisVal is smaller
2087             else if (midVal > key)
2088                 high = mid - 1; // Neither val is NaN, thisVal is larger
2089             else {
2090                 long midBits = Double.doubleToLongBits(midVal);
2091                 long keyBits = Double.doubleToLongBits(key);
2092                 if (midBits == keyBits)     // Values are equal
2093                     return mid;             // Key found
2094                 else if (midBits < keyBits) // (-0.0, 0.0) or (!NaN, NaN)
2095                     low = mid + 1;
2096                 else                        // (0.0, -0.0) or (NaN, !NaN)
2097                     high = mid - 1;
2098             }
2099         }
2100         return -(low + 1);  // key not found.
2101     }
2102 
2103     /**
2104      * Searches the specified array of floats for the specified value using
2105      * the binary search algorithm. The array must be sorted
2106      * (as by the {@link #sort(float[])} method) prior to making this call. If
2107      * it is not sorted, the results are undefined. If the array contains
2108      * multiple elements with the specified value, there is no guarantee which
2109      * one will be found. This method considers all NaN values to be
2110      * equivalent and equal.
2111      *
2112      * @param a the array to be searched
2113      * @param key the value to be searched for
2114      * @return index of the search key, if it is contained in the array;
2115      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The
2116      *         <i>insertion point</i> is defined as the point at which the
2117      *         key would be inserted into the array: the index of the first
2118      *         element greater than the key, or {@code a.length} if all
2119      *         elements in the array are less than the specified key. Note
2120      *         that this guarantees that the return value will be &gt;= 0 if
2121      *         and only if the key is found.
2122      */
binarySearch(float[] a, float key)2123     public static int binarySearch(float[] a, float key) {
2124         return binarySearch0(a, 0, a.length, key);
2125     }
2126 
2127     /**
2128      * Searches a range of
2129      * the specified array of floats for the specified value using
2130      * the binary search algorithm.
2131      * The range must be sorted
2132      * (as by the {@link #sort(float[], int, int)} method)
2133      * prior to making this call. If
2134      * it is not sorted, the results are undefined. If the range contains
2135      * multiple elements with the specified value, there is no guarantee which
2136      * one will be found. This method considers all NaN values to be
2137      * equivalent and equal.
2138      *
2139      * @param a the array to be searched
2140      * @param fromIndex the index of the first element (inclusive) to be
2141      *          searched
2142      * @param toIndex the index of the last element (exclusive) to be searched
2143      * @param key the value to be searched for
2144      * @return index of the search key, if it is contained in the array
2145      *         within the specified range;
2146      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The
2147      *         <i>insertion point</i> is defined as the point at which the
2148      *         key would be inserted into the array: the index of the first
2149      *         element in the range greater than the key,
2150      *         or {@code toIndex} if all
2151      *         elements in the range are less than the specified key. Note
2152      *         that this guarantees that the return value will be &gt;= 0 if
2153      *         and only if the key is found.
2154      * @throws IllegalArgumentException
2155      *         if {@code fromIndex > toIndex}
2156      * @throws ArrayIndexOutOfBoundsException
2157      *         if {@code fromIndex < 0 or toIndex > a.length}
2158      * @since 1.6
2159      */
binarySearch(float[] a, int fromIndex, int toIndex, float key)2160     public static int binarySearch(float[] a, int fromIndex, int toIndex,
2161                                    float key) {
2162         rangeCheck(a.length, fromIndex, toIndex);
2163         return binarySearch0(a, fromIndex, toIndex, key);
2164     }
2165 
2166     // Like public version, but without range checks.
binarySearch0(float[] a, int fromIndex, int toIndex, float key)2167     private static int binarySearch0(float[] a, int fromIndex, int toIndex,
2168                                      float key) {
2169         int low = fromIndex;
2170         int high = toIndex - 1;
2171 
2172         while (low <= high) {
2173             int mid = (low + high) >>> 1;
2174             float midVal = a[mid];
2175 
2176             if (midVal < key)
2177                 low = mid + 1;  // Neither val is NaN, thisVal is smaller
2178             else if (midVal > key)
2179                 high = mid - 1; // Neither val is NaN, thisVal is larger
2180             else {
2181                 int midBits = Float.floatToIntBits(midVal);
2182                 int keyBits = Float.floatToIntBits(key);
2183                 if (midBits == keyBits)     // Values are equal
2184                     return mid;             // Key found
2185                 else if (midBits < keyBits) // (-0.0, 0.0) or (!NaN, NaN)
2186                     low = mid + 1;
2187                 else                        // (0.0, -0.0) or (NaN, !NaN)
2188                     high = mid - 1;
2189             }
2190         }
2191         return -(low + 1);  // key not found.
2192     }
2193 
2194     /**
2195      * Searches the specified array for the specified object using the binary
2196      * search algorithm. The array must be sorted into ascending order
2197      * according to the
2198      * {@linkplain Comparable natural ordering}
2199      * of its elements (as by the
2200      * {@link #sort(Object[])} method) prior to making this call.
2201      * If it is not sorted, the results are undefined.
2202      * (If the array contains elements that are not mutually comparable (for
2203      * example, strings and integers), it <i>cannot</i> be sorted according
2204      * to the natural ordering of its elements, hence results are undefined.)
2205      * If the array contains multiple
2206      * elements equal to the specified object, there is no guarantee which
2207      * one will be found.
2208      *
2209      * @param a the array to be searched
2210      * @param key the value to be searched for
2211      * @return index of the search key, if it is contained in the array;
2212      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
2213      *         <i>insertion point</i> is defined as the point at which the
2214      *         key would be inserted into the array: the index of the first
2215      *         element greater than the key, or {@code a.length} if all
2216      *         elements in the array are less than the specified key.  Note
2217      *         that this guarantees that the return value will be &gt;= 0 if
2218      *         and only if the key is found.
2219      * @throws ClassCastException if the search key is not comparable to the
2220      *         elements of the array.
2221      */
binarySearch(Object[] a, Object key)2222     public static int binarySearch(Object[] a, Object key) {
2223         return binarySearch0(a, 0, a.length, key);
2224     }
2225 
2226     /**
2227      * Searches a range of
2228      * the specified array for the specified object using the binary
2229      * search algorithm.
2230      * The range must be sorted into ascending order
2231      * according to the
2232      * {@linkplain Comparable natural ordering}
2233      * of its elements (as by the
2234      * {@link #sort(Object[], int, int)} method) prior to making this
2235      * call.  If it is not sorted, the results are undefined.
2236      * (If the range contains elements that are not mutually comparable (for
2237      * example, strings and integers), it <i>cannot</i> be sorted according
2238      * to the natural ordering of its elements, hence results are undefined.)
2239      * If the range contains multiple
2240      * elements equal to the specified object, there is no guarantee which
2241      * one will be found.
2242      *
2243      * @param a the array to be searched
2244      * @param fromIndex the index of the first element (inclusive) to be
2245      *          searched
2246      * @param toIndex the index of the last element (exclusive) to be searched
2247      * @param key the value to be searched for
2248      * @return index of the search key, if it is contained in the array
2249      *         within the specified range;
2250      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
2251      *         <i>insertion point</i> is defined as the point at which the
2252      *         key would be inserted into the array: the index of the first
2253      *         element in the range greater than the key,
2254      *         or {@code toIndex} if all
2255      *         elements in the range are less than the specified key.  Note
2256      *         that this guarantees that the return value will be &gt;= 0 if
2257      *         and only if the key is found.
2258      * @throws ClassCastException if the search key is not comparable to the
2259      *         elements of the array within the specified range.
2260      * @throws IllegalArgumentException
2261      *         if {@code fromIndex > toIndex}
2262      * @throws ArrayIndexOutOfBoundsException
2263      *         if {@code fromIndex < 0 or toIndex > a.length}
2264      * @since 1.6
2265      */
binarySearch(Object[] a, int fromIndex, int toIndex, Object key)2266     public static int binarySearch(Object[] a, int fromIndex, int toIndex,
2267                                    Object key) {
2268         rangeCheck(a.length, fromIndex, toIndex);
2269         return binarySearch0(a, fromIndex, toIndex, key);
2270     }
2271 
2272     // Like public version, but without range checks.
binarySearch0(Object[] a, int fromIndex, int toIndex, Object key)2273     private static int binarySearch0(Object[] a, int fromIndex, int toIndex,
2274                                      Object key) {
2275         int low = fromIndex;
2276         int high = toIndex - 1;
2277 
2278         while (low <= high) {
2279             int mid = (low + high) >>> 1;
2280             @SuppressWarnings("rawtypes")
2281             Comparable midVal = (Comparable)a[mid];
2282             @SuppressWarnings("unchecked")
2283             int cmp = midVal.compareTo(key);
2284 
2285             if (cmp < 0)
2286                 low = mid + 1;
2287             else if (cmp > 0)
2288                 high = mid - 1;
2289             else
2290                 return mid; // key found
2291         }
2292         return -(low + 1);  // key not found.
2293     }
2294 
2295     /**
2296      * Searches the specified array for the specified object using the binary
2297      * search algorithm.  The array must be sorted into ascending order
2298      * according to the specified comparator (as by the
2299      * {@link #sort(Object[], Comparator) sort(T[], Comparator)}
2300      * method) prior to making this call.  If it is
2301      * not sorted, the results are undefined.
2302      * If the array contains multiple
2303      * elements equal to the specified object, there is no guarantee which one
2304      * will be found.
2305      *
2306      * @param <T> the class of the objects in the array
2307      * @param a the array to be searched
2308      * @param key the value to be searched for
2309      * @param c the comparator by which the array is ordered.  A
2310      *        {@code null} value indicates that the elements'
2311      *        {@linkplain Comparable natural ordering} should be used.
2312      * @return index of the search key, if it is contained in the array;
2313      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
2314      *         <i>insertion point</i> is defined as the point at which the
2315      *         key would be inserted into the array: the index of the first
2316      *         element greater than the key, or {@code a.length} if all
2317      *         elements in the array are less than the specified key.  Note
2318      *         that this guarantees that the return value will be &gt;= 0 if
2319      *         and only if the key is found.
2320      * @throws ClassCastException if the array contains elements that are not
2321      *         <i>mutually comparable</i> using the specified comparator,
2322      *         or the search key is not comparable to the
2323      *         elements of the array using this comparator.
2324      */
binarySearch(T[] a, T key, Comparator<? super T> c)2325     public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c) {
2326         return binarySearch0(a, 0, a.length, key, c);
2327     }
2328 
2329     /**
2330      * Searches a range of
2331      * the specified array for the specified object using the binary
2332      * search algorithm.
2333      * The range must be sorted into ascending order
2334      * according to the specified comparator (as by the
2335      * {@link #sort(Object[], int, int, Comparator)
2336      * sort(T[], int, int, Comparator)}
2337      * method) prior to making this call.
2338      * If it is not sorted, the results are undefined.
2339      * If the range contains multiple elements equal to the specified object,
2340      * there is no guarantee which one will be found.
2341      *
2342      * @param <T> the class of the objects in the array
2343      * @param a the array to be searched
2344      * @param fromIndex the index of the first element (inclusive) to be
2345      *          searched
2346      * @param toIndex the index of the last element (exclusive) to be searched
2347      * @param key the value to be searched for
2348      * @param c the comparator by which the array is ordered.  A
2349      *        {@code null} value indicates that the elements'
2350      *        {@linkplain Comparable natural ordering} should be used.
2351      * @return index of the search key, if it is contained in the array
2352      *         within the specified range;
2353      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
2354      *         <i>insertion point</i> is defined as the point at which the
2355      *         key would be inserted into the array: the index of the first
2356      *         element in the range greater than the key,
2357      *         or {@code toIndex} if all
2358      *         elements in the range are less than the specified key.  Note
2359      *         that this guarantees that the return value will be &gt;= 0 if
2360      *         and only if the key is found.
2361      * @throws ClassCastException if the range contains elements that are not
2362      *         <i>mutually comparable</i> using the specified comparator,
2363      *         or the search key is not comparable to the
2364      *         elements in the range using this comparator.
2365      * @throws IllegalArgumentException
2366      *         if {@code fromIndex > toIndex}
2367      * @throws ArrayIndexOutOfBoundsException
2368      *         if {@code fromIndex < 0 or toIndex > a.length}
2369      * @since 1.6
2370      */
binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c)2371     public static <T> int binarySearch(T[] a, int fromIndex, int toIndex,
2372                                        T key, Comparator<? super T> c) {
2373         rangeCheck(a.length, fromIndex, toIndex);
2374         return binarySearch0(a, fromIndex, toIndex, key, c);
2375     }
2376 
2377     // Like public version, but without range checks.
binarySearch0(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c)2378     private static <T> int binarySearch0(T[] a, int fromIndex, int toIndex,
2379                                          T key, Comparator<? super T> c) {
2380         if (c == null) {
2381             return binarySearch0(a, fromIndex, toIndex, key);
2382         }
2383         int low = fromIndex;
2384         int high = toIndex - 1;
2385 
2386         while (low <= high) {
2387             int mid = (low + high) >>> 1;
2388             T midVal = a[mid];
2389             int cmp = c.compare(midVal, key);
2390             if (cmp < 0)
2391                 low = mid + 1;
2392             else if (cmp > 0)
2393                 high = mid - 1;
2394             else
2395                 return mid; // key found
2396         }
2397         return -(low + 1);  // key not found.
2398     }
2399 
2400     // Equality Testing
2401 
2402     /**
2403      * Returns {@code true} if the two specified arrays of longs are
2404      * <i>equal</i> to one another.  Two arrays are considered equal if both
2405      * arrays contain the same number of elements, and all corresponding pairs
2406      * of elements in the two arrays are equal.  In other words, two arrays
2407      * are equal if they contain the same elements in the same order.  Also,
2408      * two array references are considered equal if both are {@code null}.
2409      *
2410      * @param a one array to be tested for equality
2411      * @param a2 the other array to be tested for equality
2412      * @return {@code true} if the two arrays are equal
2413      */
equals(long[] a, long[] a2)2414     public static boolean equals(long[] a, long[] a2) {
2415         if (a==a2)
2416             return true;
2417         if (a==null || a2==null)
2418             return false;
2419 
2420         int length = a.length;
2421         if (a2.length != length)
2422             return false;
2423 
2424         // BEGIN Android-changed: keep for-loop implementation due to the absence of ArraySupport
2425         // intrinsics.
2426         // TODO(b/362153334) Assess whether it's worth writing intrinsics or not.
2427         // return ArraysSupport.mismatch(a, a2, length) < 0;
2428         for (int idx = 0; idx < length; ++idx) {
2429             if (a[idx] != a2[idx]) {
2430                 return false;
2431             }
2432         }
2433         return true;
2434         // END Android-changed: keep for-loop implementation due to the absence of ArraySupport
2435         // intrinsics.
2436     }
2437 
2438     /**
2439      * Returns true if the two specified arrays of longs, over the specified
2440      * ranges, are <i>equal</i> to one another.
2441      *
2442      * <p>Two arrays are considered equal if the number of elements covered by
2443      * each range is the same, and all corresponding pairs of elements over the
2444      * specified ranges in the two arrays are equal.  In other words, two arrays
2445      * are equal if they contain, over the specified ranges, the same elements
2446      * in the same order.
2447      *
2448      * @param a the first array to be tested for equality
2449      * @param aFromIndex the index (inclusive) of the first element in the
2450      *                   first array to be tested
2451      * @param aToIndex the index (exclusive) of the last element in the
2452      *                 first array to be tested
2453      * @param b the second array to be tested for equality
2454      * @param bFromIndex the index (inclusive) of the first element in the
2455      *                   second array to be tested
2456      * @param bToIndex the index (exclusive) of the last element in the
2457      *                 second array to be tested
2458      * @return {@code true} if the two arrays, over the specified ranges, are
2459      *         equal
2460      * @throws IllegalArgumentException
2461      *         if {@code aFromIndex > aToIndex} or
2462      *         if {@code bFromIndex > bToIndex}
2463      * @throws ArrayIndexOutOfBoundsException
2464      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
2465      *         if {@code bFromIndex < 0 or bToIndex > b.length}
2466      * @throws NullPointerException
2467      *         if either array is {@code null}
2468      * @since 9
2469      */
equals(long[] a, int aFromIndex, int aToIndex, long[] b, int bFromIndex, int bToIndex)2470     public static boolean equals(long[] a, int aFromIndex, int aToIndex,
2471                                  long[] b, int bFromIndex, int bToIndex) {
2472         rangeCheck(a.length, aFromIndex, aToIndex);
2473         rangeCheck(b.length, bFromIndex, bToIndex);
2474 
2475         int aLength = aToIndex - aFromIndex;
2476         int bLength = bToIndex - bFromIndex;
2477         if (aLength != bLength)
2478             return false;
2479 
2480         // BEGIN Android-changed: keep for-loop implementation due to the absence of ArraySupport
2481         // intrinsics.
2482         // TODO(b/362153334) Assess whether it's worth writing intrinsics or not.
2483         /*
2484         return ArraysSupport.mismatch(a, aFromIndex,
2485                                       b, bFromIndex,
2486                                       aLength) < 0;
2487         */
2488         for (int idx = 0; idx < aLength; ++idx) {
2489             if (a[aFromIndex++] != b[bFromIndex++]) {
2490                 return false;
2491             }
2492         }
2493         return true;
2494         // END Android-changed: keep for-loop implementation due to the absence of ArraySupport
2495         // intrinsics.
2496     }
2497 
2498     /**
2499      * Returns {@code true} if the two specified arrays of ints are
2500      * <i>equal</i> to one another.  Two arrays are considered equal if both
2501      * arrays contain the same number of elements, and all corresponding pairs
2502      * of elements in the two arrays are equal.  In other words, two arrays
2503      * are equal if they contain the same elements in the same order.  Also,
2504      * two array references are considered equal if both are {@code null}.
2505      *
2506      * @param a one array to be tested for equality
2507      * @param a2 the other array to be tested for equality
2508      * @return {@code true} if the two arrays are equal
2509      */
equals(int[] a, int[] a2)2510     public static boolean equals(int[] a, int[] a2) {
2511         if (a==a2)
2512             return true;
2513         if (a==null || a2==null)
2514             return false;
2515 
2516         int length = a.length;
2517         if (a2.length != length)
2518             return false;
2519 
2520         // BEGIN Android-changed: keep for-loop implementation due to the absence of ArraySupport
2521         // intrinsics.
2522         // TODO(b/362153334) Assess whether it's worth writing intrinsics or not.
2523         // return ArraysSupport.mismatch(a, a2, length) < 0;
2524         for (int idx = 0; idx < length; ++idx) {
2525             if (a[idx] != a2[idx]) {
2526                 return false;
2527             }
2528         }
2529         return true;
2530         // END Android-changed: keep for-loop implementation due to the absence of ArraySupport
2531         // intrinsics.
2532     }
2533 
2534     /**
2535      * Returns true if the two specified arrays of ints, over the specified
2536      * ranges, are <i>equal</i> to one another.
2537      *
2538      * <p>Two arrays are considered equal if the number of elements covered by
2539      * each range is the same, and all corresponding pairs of elements over the
2540      * specified ranges in the two arrays are equal.  In other words, two arrays
2541      * are equal if they contain, over the specified ranges, the same elements
2542      * in the same order.
2543      *
2544      * @param a the first array to be tested for equality
2545      * @param aFromIndex the index (inclusive) of the first element in the
2546      *                   first array to be tested
2547      * @param aToIndex the index (exclusive) of the last element in the
2548      *                 first array to be tested
2549      * @param b the second array to be tested for equality
2550      * @param bFromIndex the index (inclusive) of the first element in the
2551      *                   second array to be tested
2552      * @param bToIndex the index (exclusive) of the last element in the
2553      *                 second array to be tested
2554      * @return {@code true} if the two arrays, over the specified ranges, are
2555      *         equal
2556      * @throws IllegalArgumentException
2557      *         if {@code aFromIndex > aToIndex} or
2558      *         if {@code bFromIndex > bToIndex}
2559      * @throws ArrayIndexOutOfBoundsException
2560      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
2561      *         if {@code bFromIndex < 0 or bToIndex > b.length}
2562      * @throws NullPointerException
2563      *         if either array is {@code null}
2564      * @since 9
2565      */
equals(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)2566     public static boolean equals(int[] a, int aFromIndex, int aToIndex,
2567                                  int[] b, int bFromIndex, int bToIndex) {
2568         rangeCheck(a.length, aFromIndex, aToIndex);
2569         rangeCheck(b.length, bFromIndex, bToIndex);
2570 
2571         int aLength = aToIndex - aFromIndex;
2572         int bLength = bToIndex - bFromIndex;
2573         if (aLength != bLength)
2574             return false;
2575 
2576         // BEGIN Android-changed: keep for-loop implementation due to the absence of ArraySupport
2577         // intrinsics.
2578         // TODO(b/362153334) Assess whether it's worth writing intrinsics or not.
2579         /*
2580         return ArraysSupport.mismatch(a, aFromIndex,
2581                                       b, bFromIndex,
2582                                       aLength) < 0;
2583         */
2584         for (int idx = 0; idx < aLength; ++idx) {
2585             if (a[aFromIndex++] != b[bFromIndex++]) {
2586                 return false;
2587             }
2588         }
2589         return true;
2590         // END Android-changed: keep for-loop implementation due to the absence of ArraySupport
2591         // intrinsics.
2592     }
2593 
2594     /**
2595      * Returns {@code true} if the two specified arrays of shorts are
2596      * <i>equal</i> to one another.  Two arrays are considered equal if both
2597      * arrays contain the same number of elements, and all corresponding pairs
2598      * of elements in the two arrays are equal.  In other words, two arrays
2599      * are equal if they contain the same elements in the same order.  Also,
2600      * two array references are considered equal if both are {@code null}.
2601      *
2602      * @param a one array to be tested for equality
2603      * @param a2 the other array to be tested for equality
2604      * @return {@code true} if the two arrays are equal
2605      */
equals(short[] a, short[] a2)2606     public static boolean equals(short[] a, short[] a2) {
2607         if (a==a2)
2608             return true;
2609         if (a==null || a2==null)
2610             return false;
2611 
2612         int length = a.length;
2613         if (a2.length != length)
2614             return false;
2615 
2616         // BEGIN Android-changed: keep for-loop implementation due to the absence of ArraySupport
2617         // intrinsics.
2618         // TODO(b/362153334) Assess whether it's worth writing intrinsics or not.
2619         // return ArraysSupport.mismatch(a, a2, length) < 0;
2620         for (int idx = 0; idx < length; ++idx) {
2621             if (a[idx] != a2[idx]) {
2622                 return false;
2623             }
2624         }
2625         return true;
2626         // END Android-changed: keep for-loop implementation due to the absence of ArraySupport
2627         // intrinsics.
2628     }
2629 
2630     /**
2631      * Returns true if the two specified arrays of shorts, over the specified
2632      * ranges, are <i>equal</i> to one another.
2633      *
2634      * <p>Two arrays are considered equal if the number of elements covered by
2635      * each range is the same, and all corresponding pairs of elements over the
2636      * specified ranges in the two arrays are equal.  In other words, two arrays
2637      * are equal if they contain, over the specified ranges, the same elements
2638      * in the same order.
2639      *
2640      * @param a the first array to be tested for equality
2641      * @param aFromIndex the index (inclusive) of the first element in the
2642      *                   first array to be tested
2643      * @param aToIndex the index (exclusive) of the last element in the
2644      *                 first array to be tested
2645      * @param b the second array to be tested for equality
2646      * @param bFromIndex the index (inclusive) of the first element in the
2647      *                   second array to be tested
2648      * @param bToIndex the index (exclusive) of the last element in the
2649      *                 second array to be tested
2650      * @return {@code true} if the two arrays, over the specified ranges, are
2651      *         equal
2652      * @throws IllegalArgumentException
2653      *         if {@code aFromIndex > aToIndex} or
2654      *         if {@code bFromIndex > bToIndex}
2655      * @throws ArrayIndexOutOfBoundsException
2656      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
2657      *         if {@code bFromIndex < 0 or bToIndex > b.length}
2658      * @throws NullPointerException
2659      *         if either array is {@code null}
2660      * @since 9
2661      */
equals(short[] a, int aFromIndex, int aToIndex, short[] b, int bFromIndex, int bToIndex)2662     public static boolean equals(short[] a, int aFromIndex, int aToIndex,
2663                                  short[] b, int bFromIndex, int bToIndex) {
2664         rangeCheck(a.length, aFromIndex, aToIndex);
2665         rangeCheck(b.length, bFromIndex, bToIndex);
2666 
2667         int aLength = aToIndex - aFromIndex;
2668         int bLength = bToIndex - bFromIndex;
2669         if (aLength != bLength)
2670             return false;
2671 
2672         // BEGIN Android-changed: keep for-loop implementation due to the absence of ArraySupport
2673         // intrinsics.
2674         // TODO(b/362153334) Assess whether it's worth writing intrinsics or not.
2675         /*
2676         return ArraysSupport.mismatch(a, aFromIndex,
2677                                       b, bFromIndex,
2678                                       aLength) < 0;
2679         */
2680         for (int idx = 0; idx < aLength; ++idx) {
2681             if (a[aFromIndex++] != b[bFromIndex++]) {
2682                 return false;
2683             }
2684         }
2685         return true;
2686         // END Android-changed: keep for-loop implementation due to the absence of ArraySupport
2687         // intrinsics.
2688     }
2689 
2690     /**
2691      * Returns {@code true} if the two specified arrays of chars are
2692      * <i>equal</i> to one another.  Two arrays are considered equal if both
2693      * arrays contain the same number of elements, and all corresponding pairs
2694      * of elements in the two arrays are equal.  In other words, two arrays
2695      * are equal if they contain the same elements in the same order.  Also,
2696      * two array references are considered equal if both are {@code null}.
2697      *
2698      * @param a one array to be tested for equality
2699      * @param a2 the other array to be tested for equality
2700      * @return {@code true} if the two arrays are equal
2701      */
2702     @IntrinsicCandidate
equals(char[] a, char[] a2)2703     public static boolean equals(char[] a, char[] a2) {
2704         if (a==a2)
2705             return true;
2706         if (a==null || a2==null)
2707             return false;
2708 
2709         int length = a.length;
2710         if (a2.length != length)
2711             return false;
2712 
2713         // BEGIN Android-changed: keep for-loop implementation due to the absence of ArraySupport
2714         // intrinsics.
2715         // TODO(b/362153334) Assess whether it's worth writing intrinsics or not.
2716         // return ArraysSupport.mismatch(a, a2, length) < 0;
2717         for (int idx = 0; idx < length; ++idx) {
2718             if (a[idx] != a2[idx]) {
2719                 return false;
2720             }
2721         }
2722         return true;
2723         // END Android-changed: keep for-loop implementation due to the absence of ArraySupport
2724         // intrinsics.
2725     }
2726 
2727     /**
2728      * Returns true if the two specified arrays of chars, over the specified
2729      * ranges, are <i>equal</i> to one another.
2730      *
2731      * <p>Two arrays are considered equal if the number of elements covered by
2732      * each range is the same, and all corresponding pairs of elements over the
2733      * specified ranges in the two arrays are equal.  In other words, two arrays
2734      * are equal if they contain, over the specified ranges, the same elements
2735      * in the same order.
2736      *
2737      * @param a the first array to be tested for equality
2738      * @param aFromIndex the index (inclusive) of the first element in the
2739      *                   first array to be tested
2740      * @param aToIndex the index (exclusive) of the last element in the
2741      *                 first array to be tested
2742      * @param b the second array to be tested for equality
2743      * @param bFromIndex the index (inclusive) of the first element in the
2744      *                   second array to be tested
2745      * @param bToIndex the index (exclusive) of the last element in the
2746      *                 second array to be tested
2747      * @return {@code true} if the two arrays, over the specified ranges, are
2748      *         equal
2749      * @throws IllegalArgumentException
2750      *         if {@code aFromIndex > aToIndex} or
2751      *         if {@code bFromIndex > bToIndex}
2752      * @throws ArrayIndexOutOfBoundsException
2753      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
2754      *         if {@code bFromIndex < 0 or bToIndex > b.length}
2755      * @throws NullPointerException
2756      *         if either array is {@code null}
2757      * @since 9
2758      */
equals(char[] a, int aFromIndex, int aToIndex, char[] b, int bFromIndex, int bToIndex)2759     public static boolean equals(char[] a, int aFromIndex, int aToIndex,
2760                                  char[] b, int bFromIndex, int bToIndex) {
2761         rangeCheck(a.length, aFromIndex, aToIndex);
2762         rangeCheck(b.length, bFromIndex, bToIndex);
2763 
2764         int aLength = aToIndex - aFromIndex;
2765         int bLength = bToIndex - bFromIndex;
2766         if (aLength != bLength)
2767             return false;
2768 
2769         // BEGIN Android-changed: keep for-loop implementation due to the absence of ArraySupport
2770         // intrinsics.
2771         // TODO(b/362153334) Assess whether it's worth writing intrinsics or not.
2772         /*
2773         return ArraysSupport.mismatch(a, aFromIndex,
2774                                       b, bFromIndex,
2775                                       aLength) < 0;
2776         */
2777         for (int idx = 0; idx < aLength; ++idx) {
2778             if (a[aFromIndex++] != b[bFromIndex++]) {
2779                 return false;
2780             }
2781         }
2782         return true;
2783         // END Android-changed: keep for-loop implementation due to the absence of ArraySupport
2784         // intrinsics.
2785     }
2786 
2787     /**
2788      * Returns {@code true} if the two specified arrays of bytes are
2789      * <i>equal</i> to one another.  Two arrays are considered equal if both
2790      * arrays contain the same number of elements, and all corresponding pairs
2791      * of elements in the two arrays are equal.  In other words, two arrays
2792      * are equal if they contain the same elements in the same order.  Also,
2793      * two array references are considered equal if both are {@code null}.
2794      *
2795      * @param a one array to be tested for equality
2796      * @param a2 the other array to be tested for equality
2797      * @return {@code true} if the two arrays are equal
2798      */
2799     @IntrinsicCandidate
equals(byte[] a, byte[] a2)2800     public static boolean equals(byte[] a, byte[] a2) {
2801         if (a==a2)
2802             return true;
2803         if (a==null || a2==null)
2804             return false;
2805 
2806         int length = a.length;
2807         if (a2.length != length)
2808             return false;
2809 
2810         // BEGIN Android-changed: keep for-loop implementation due to the absence of ArraySupport
2811         // intrinsics.
2812         // TODO(b/362153334) Assess whether it's worth writing intrinsics or not.
2813         // return ArraysSupport.mismatch(a, a2, length) < 0;
2814         for (int idx = 0; idx < length; ++idx) {
2815             if (a[idx] != a2[idx]) {
2816                 return false;
2817             }
2818         }
2819         return true;
2820         // END Android-changed: keep for-loop implementation due to the absence of ArraySupport
2821         // intrinsics.
2822     }
2823 
2824     /**
2825      * Returns true if the two specified arrays of bytes, over the specified
2826      * ranges, are <i>equal</i> to one another.
2827      *
2828      * <p>Two arrays are considered equal if the number of elements covered by
2829      * each range is the same, and all corresponding pairs of elements over the
2830      * specified ranges in the two arrays are equal.  In other words, two arrays
2831      * are equal if they contain, over the specified ranges, the same elements
2832      * in the same order.
2833      *
2834      * @param a the first array to be tested for equality
2835      * @param aFromIndex the index (inclusive) of the first element in the
2836      *                   first array to be tested
2837      * @param aToIndex the index (exclusive) of the last element in the
2838      *                 first array to be tested
2839      * @param b the second array to be tested for equality
2840      * @param bFromIndex the index (inclusive) of the first element in the
2841      *                   second array to be tested
2842      * @param bToIndex the index (exclusive) of the last element in the
2843      *                 second array to be tested
2844      * @return {@code true} if the two arrays, over the specified ranges, are
2845      *         equal
2846      * @throws IllegalArgumentException
2847      *         if {@code aFromIndex > aToIndex} or
2848      *         if {@code bFromIndex > bToIndex}
2849      * @throws ArrayIndexOutOfBoundsException
2850      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
2851      *         if {@code bFromIndex < 0 or bToIndex > b.length}
2852      * @throws NullPointerException
2853      *         if either array is {@code null}
2854      * @since 9
2855      */
equals(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex)2856     public static boolean equals(byte[] a, int aFromIndex, int aToIndex,
2857                                  byte[] b, int bFromIndex, int bToIndex) {
2858         rangeCheck(a.length, aFromIndex, aToIndex);
2859         rangeCheck(b.length, bFromIndex, bToIndex);
2860 
2861         int aLength = aToIndex - aFromIndex;
2862         int bLength = bToIndex - bFromIndex;
2863         if (aLength != bLength)
2864             return false;
2865 
2866         // BEGIN Android-changed: keep for-loop implementation due to the absence of ArraySupport
2867         // intrinsics.
2868         // TODO(b/362153334) Assess whether it's worth writing intrinsics or not.
2869         /*
2870         return ArraysSupport.mismatch(a, aFromIndex,
2871                                       b, bFromIndex,
2872                                       aLength) < 0;
2873         */
2874         for (int idx = 0; idx < aLength; ++idx) {
2875             if (a[aFromIndex++] != b[bFromIndex++]) {
2876                 return false;
2877             }
2878         }
2879         return true;
2880         // END Android-changed: keep for-loop implementation due to the absence of ArraySupport
2881         // intrinsics.
2882     }
2883 
2884     /**
2885      * Returns {@code true} if the two specified arrays of booleans are
2886      * <i>equal</i> to one another.  Two arrays are considered equal if both
2887      * arrays contain the same number of elements, and all corresponding pairs
2888      * of elements in the two arrays are equal.  In other words, two arrays
2889      * are equal if they contain the same elements in the same order.  Also,
2890      * two array references are considered equal if both are {@code null}.
2891      *
2892      * @param a one array to be tested for equality
2893      * @param a2 the other array to be tested for equality
2894      * @return {@code true} if the two arrays are equal
2895      */
equals(boolean[] a, boolean[] a2)2896     public static boolean equals(boolean[] a, boolean[] a2) {
2897         if (a==a2)
2898             return true;
2899         if (a==null || a2==null)
2900             return false;
2901 
2902         int length = a.length;
2903         if (a2.length != length)
2904             return false;
2905 
2906         // BEGIN Android-changed: keep for-loop implementation due to the absence of ArraySupport
2907         // intrinsics.
2908         // TODO(b/362153334) Assess whether it's worth writing intrinsics or not.
2909         // return ArraysSupport.mismatch(a, a2, length) < 0;
2910         for (int idx = 0; idx < length; ++idx) {
2911             if (a[idx] != a2[idx]) {
2912                 return false;
2913             }
2914         }
2915         return true;
2916         // END Android-changed: keep for-loop implementation due to the absence of ArraySupport
2917         // intrinsics.
2918     }
2919 
2920     /**
2921      * Returns true if the two specified arrays of booleans, over the specified
2922      * ranges, are <i>equal</i> to one another.
2923      *
2924      * <p>Two arrays are considered equal if the number of elements covered by
2925      * each range is the same, and all corresponding pairs of elements over the
2926      * specified ranges in the two arrays are equal.  In other words, two arrays
2927      * are equal if they contain, over the specified ranges, the same elements
2928      * in the same order.
2929      *
2930      * @param a the first array to be tested for equality
2931      * @param aFromIndex the index (inclusive) of the first element in the
2932      *                   first array to be tested
2933      * @param aToIndex the index (exclusive) of the last element in the
2934      *                 first array to be tested
2935      * @param b the second array to be tested for equality
2936      * @param bFromIndex the index (inclusive) of the first element in the
2937      *                   second array to be tested
2938      * @param bToIndex the index (exclusive) of the last element in the
2939      *                 second array to be tested
2940      * @return {@code true} if the two arrays, over the specified ranges, are
2941      *         equal
2942      * @throws IllegalArgumentException
2943      *         if {@code aFromIndex > aToIndex} or
2944      *         if {@code bFromIndex > bToIndex}
2945      * @throws ArrayIndexOutOfBoundsException
2946      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
2947      *         if {@code bFromIndex < 0 or bToIndex > b.length}
2948      * @throws NullPointerException
2949      *         if either array is {@code null}
2950      * @since 9
2951      */
equals(boolean[] a, int aFromIndex, int aToIndex, boolean[] b, int bFromIndex, int bToIndex)2952     public static boolean equals(boolean[] a, int aFromIndex, int aToIndex,
2953                                  boolean[] b, int bFromIndex, int bToIndex) {
2954         rangeCheck(a.length, aFromIndex, aToIndex);
2955         rangeCheck(b.length, bFromIndex, bToIndex);
2956 
2957         int aLength = aToIndex - aFromIndex;
2958         int bLength = bToIndex - bFromIndex;
2959         if (aLength != bLength)
2960             return false;
2961 
2962         // BEGIN Android-changed: keep for-loop implementation due to the absence of ArraySupport
2963         // intrinsics.
2964         // TODO(b/362153334) Assess whether it's worth writing intrinsics or not.
2965         /*
2966         return ArraysSupport.mismatch(a, aFromIndex,
2967                                       b, bFromIndex,
2968                                       aLength) < 0;
2969         */
2970         for (int idx = 0; idx < aLength; ++idx) {
2971             if (a[aFromIndex++] != b[bFromIndex++]) {
2972                 return false;
2973             }
2974         }
2975 
2976         return true;
2977         // END Android-changed: keep for-loop implementation due to the absence of ArraySupport
2978         // intrinsics.
2979     }
2980 
2981     /**
2982      * Returns {@code true} if the two specified arrays of doubles are
2983      * <i>equal</i> to one another.  Two arrays are considered equal if both
2984      * arrays contain the same number of elements, and all corresponding pairs
2985      * of elements in the two arrays are equal.  In other words, two arrays
2986      * are equal if they contain the same elements in the same order.  Also,
2987      * two array references are considered equal if both are {@code null}.
2988      *
2989      * Two doubles {@code d1} and {@code d2} are considered equal if:
2990      * <pre>    {@code Double.valueOf(d1).equals(Double.valueOf(d2))}</pre>
2991      * (Unlike the {@code ==} operator, this method considers
2992      * {@code NaN} equal to itself, and 0.0d unequal to -0.0d.)
2993      *
2994      * @param a one array to be tested for equality
2995      * @param a2 the other array to be tested for equality
2996      * @return {@code true} if the two arrays are equal
2997      * @see Double#equals(Object)
2998      */
equals(double[] a, double[] a2)2999     public static boolean equals(double[] a, double[] a2) {
3000         if (a==a2)
3001             return true;
3002         if (a==null || a2==null)
3003             return false;
3004 
3005         int length = a.length;
3006         if (a2.length != length)
3007             return false;
3008 
3009         // BEGIN Android-changed: keep for-loop implementation due to the absence of ArraySupport
3010         // intrinsics.
3011         // TODO(b/362153334) Assess whether it's worth writing intrinsics or not.
3012         // return ArraysSupport.mismatch(a, a2, length) < 0;
3013         for (int idx = 0; idx < length; ++idx) {
3014             if (Double.doubleToLongBits(a[idx]) != Double.doubleToLongBits(a2[idx])) {
3015                 return false;
3016             }
3017         }
3018         return true;
3019         // END Android-changed: keep for-loop implementation due to the absence of ArraySupport
3020         // intrinsics.
3021     }
3022 
3023     /**
3024      * Returns true if the two specified arrays of doubles, over the specified
3025      * ranges, are <i>equal</i> to one another.
3026      *
3027      * <p>Two arrays are considered equal if the number of elements covered by
3028      * each range is the same, and all corresponding pairs of elements over the
3029      * specified ranges in the two arrays are equal.  In other words, two arrays
3030      * are equal if they contain, over the specified ranges, the same elements
3031      * in the same order.
3032      *
3033      * <p>Two doubles {@code d1} and {@code d2} are considered equal if:
3034      * <pre>    {@code Double.valueOf(d1).equals(Double.valueOf(d2))}</pre>
3035      * (Unlike the {@code ==} operator, this method considers
3036      * {@code NaN} equal to itself, and 0.0d unequal to -0.0d.)
3037      *
3038      * @param a the first array to be tested for equality
3039      * @param aFromIndex the index (inclusive) of the first element in the
3040      *                   first array to be tested
3041      * @param aToIndex the index (exclusive) of the last element in the
3042      *                 first array to be tested
3043      * @param b the second array to be tested for equality
3044      * @param bFromIndex the index (inclusive) of the first element in the
3045      *                   second array to be tested
3046      * @param bToIndex the index (exclusive) of the last element in the
3047      *                 second array to be tested
3048      * @return {@code true} if the two arrays, over the specified ranges, are
3049      *         equal
3050      * @throws IllegalArgumentException
3051      *         if {@code aFromIndex > aToIndex} or
3052      *         if {@code bFromIndex > bToIndex}
3053      * @throws ArrayIndexOutOfBoundsException
3054      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
3055      *         if {@code bFromIndex < 0 or bToIndex > b.length}
3056      * @throws NullPointerException
3057      *         if either array is {@code null}
3058      * @see Double#equals(Object)
3059      * @since 9
3060      */
equals(double[] a, int aFromIndex, int aToIndex, double[] b, int bFromIndex, int bToIndex)3061     public static boolean equals(double[] a, int aFromIndex, int aToIndex,
3062                                  double[] b, int bFromIndex, int bToIndex) {
3063         rangeCheck(a.length, aFromIndex, aToIndex);
3064         rangeCheck(b.length, bFromIndex, bToIndex);
3065 
3066         int aLength = aToIndex - aFromIndex;
3067         int bLength = bToIndex - bFromIndex;
3068         if (aLength != bLength)
3069             return false;
3070 
3071         // BEGIN Android-changed: keep for-loop implementation due to the absence of ArraySupport
3072         // intrinsics.
3073         // TODO(b/362153334) Assess whether it's worth writing intrinsics or not.
3074         /*
3075         return ArraysSupport.mismatch(a, aFromIndex,
3076                                       b, bFromIndex, aLength) < 0;
3077         */
3078         for (int idx = 0; idx < aLength; ++idx) {
3079             if (Double.doubleToLongBits(a[aFromIndex++]) !=
3080                     Double.doubleToLongBits(b[bFromIndex++])) {
3081                 return false;
3082             }
3083         }
3084         return true;
3085         // END Android-changed: keep for-loop implementation due to the absence of ArraySupport
3086         // intrinsics.
3087     }
3088 
3089     /**
3090      * Returns {@code true} if the two specified arrays of floats are
3091      * <i>equal</i> to one another.  Two arrays are considered equal if both
3092      * arrays contain the same number of elements, and all corresponding pairs
3093      * of elements in the two arrays are equal.  In other words, two arrays
3094      * are equal if they contain the same elements in the same order.  Also,
3095      * two array references are considered equal if both are {@code null}.
3096      *
3097      * Two floats {@code f1} and {@code f2} are considered equal if:
3098      * <pre>    {@code Float.valueOf(f1).equals(Float.valueOf(f2))}</pre>
3099      * (Unlike the {@code ==} operator, this method considers
3100      * {@code NaN} equal to itself, and 0.0f unequal to -0.0f.)
3101      *
3102      * @param a one array to be tested for equality
3103      * @param a2 the other array to be tested for equality
3104      * @return {@code true} if the two arrays are equal
3105      * @see Float#equals(Object)
3106      */
equals(float[] a, float[] a2)3107     public static boolean equals(float[] a, float[] a2) {
3108         if (a==a2)
3109             return true;
3110         if (a==null || a2==null)
3111             return false;
3112 
3113         int length = a.length;
3114         if (a2.length != length)
3115             return false;
3116         // BEGIN Android-changed: keep for-loop implementation due to the absence of ArraySupport
3117         // intrinsics.
3118         // TODO(b/362153334) Assess whether it's worth writing intrinsics or not.
3119         // return ArraysSupport.mismatch(a, a2, length) < 0;
3120         for (int idx = 0; idx < length; ++idx) {
3121             if (Float.floatToIntBits(a[idx]) != Float.floatToIntBits(a2[idx])) {
3122                 return false;
3123             }
3124         }
3125         return true;
3126         // END Android-changed: keep for-loop implementation due to the absence of ArraySupport
3127         // intrinsics.
3128     }
3129 
3130     /**
3131      * Returns true if the two specified arrays of floats, over the specified
3132      * ranges, are <i>equal</i> to one another.
3133      *
3134      * <p>Two arrays are considered equal if the number of elements covered by
3135      * each range is the same, and all corresponding pairs of elements over the
3136      * specified ranges in the two arrays are equal.  In other words, two arrays
3137      * are equal if they contain, over the specified ranges, the same elements
3138      * in the same order.
3139      *
3140      * <p>Two floats {@code f1} and {@code f2} are considered equal if:
3141      * <pre>    {@code Float.valueOf(f1).equals(Float.valueOf(f2))}</pre>
3142      * (Unlike the {@code ==} operator, this method considers
3143      * {@code NaN} equal to itself, and 0.0f unequal to -0.0f.)
3144      *
3145      * @param a the first array to be tested for equality
3146      * @param aFromIndex the index (inclusive) of the first element in the
3147      *                   first array to be tested
3148      * @param aToIndex the index (exclusive) of the last element in the
3149      *                 first array to be tested
3150      * @param b the second array to be tested for equality
3151      * @param bFromIndex the index (inclusive) of the first element in the
3152      *                   second array to be tested
3153      * @param bToIndex the index (exclusive) of the last element in the
3154      *                 second array to be tested
3155      * @return {@code true} if the two arrays, over the specified ranges, are
3156      *         equal
3157      * @throws IllegalArgumentException
3158      *         if {@code aFromIndex > aToIndex} or
3159      *         if {@code bFromIndex > bToIndex}
3160      * @throws ArrayIndexOutOfBoundsException
3161      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
3162      *         if {@code bFromIndex < 0 or bToIndex > b.length}
3163      * @throws NullPointerException
3164      *         if either array is {@code null}
3165      * @see Float#equals(Object)
3166      * @since 9
3167      */
equals(float[] a, int aFromIndex, int aToIndex, float[] b, int bFromIndex, int bToIndex)3168     public static boolean equals(float[] a, int aFromIndex, int aToIndex,
3169                                  float[] b, int bFromIndex, int bToIndex) {
3170         rangeCheck(a.length, aFromIndex, aToIndex);
3171         rangeCheck(b.length, bFromIndex, bToIndex);
3172 
3173         int aLength = aToIndex - aFromIndex;
3174         int bLength = bToIndex - bFromIndex;
3175         if (aLength != bLength)
3176             return false;
3177 
3178         // BEGIN Android-changed: keep for-loop implementation due to the absence of ArraySupport
3179         // intrinsics.
3180         // TODO(b/362153334) Assess whether it's worth writing intrinsics or not.
3181         /*
3182         return ArraysSupport.mismatch(a, aFromIndex,
3183                                       b, bFromIndex, aLength) < 0;
3184         */
3185         for (int idx = 0; idx < aLength; ++idx) {
3186             if (Float.floatToIntBits(a[aFromIndex++]) != Float.floatToIntBits(b[bFromIndex++])) {
3187                 return false;
3188             }
3189         }
3190         return true;
3191         // END Android-changed: keep for-loop implementation due to the absence of ArraySupport
3192         // intrinsics.
3193     }
3194 
3195     /**
3196      * Returns {@code true} if the two specified arrays of Objects are
3197      * <i>equal</i> to one another.  The two arrays are considered equal if
3198      * both arrays contain the same number of elements, and all corresponding
3199      * pairs of elements in the two arrays are equal.  Two objects {@code e1}
3200      * and {@code e2} are considered <i>equal</i> if
3201      * {@code Objects.equals(e1, e2)}.
3202      * In other words, the two arrays are equal if
3203      * they contain the same elements in the same order.  Also, two array
3204      * references are considered equal if both are {@code null}.
3205      *
3206      * @param a one array to be tested for equality
3207      * @param a2 the other array to be tested for equality
3208      * @return {@code true} if the two arrays are equal
3209      */
equals(Object[] a, Object[] a2)3210     public static boolean equals(Object[] a, Object[] a2) {
3211         if (a==a2)
3212             return true;
3213         if (a==null || a2==null)
3214             return false;
3215 
3216         int length = a.length;
3217         if (a2.length != length)
3218             return false;
3219 
3220         for (int i=0; i<length; i++) {
3221             if (!Objects.equals(a[i], a2[i]))
3222                 return false;
3223         }
3224 
3225         return true;
3226     }
3227 
3228     /**
3229      * Returns true if the two specified arrays of Objects, over the specified
3230      * ranges, are <i>equal</i> to one another.
3231      *
3232      * <p>Two arrays are considered equal if the number of elements covered by
3233      * each range is the same, and all corresponding pairs of elements over the
3234      * specified ranges in the two arrays are equal.  In other words, two arrays
3235      * are equal if they contain, over the specified ranges, the same elements
3236      * in the same order.
3237      *
3238      * <p>Two objects {@code e1} and {@code e2} are considered <i>equal</i> if
3239      * {@code Objects.equals(e1, e2)}.
3240      *
3241      * @param a the first array to be tested for equality
3242      * @param aFromIndex the index (inclusive) of the first element in the
3243      *                   first array to be tested
3244      * @param aToIndex the index (exclusive) of the last element in the
3245      *                 first array to be tested
3246      * @param b the second array to be tested for equality
3247      * @param bFromIndex the index (inclusive) of the first element in the
3248      *                   second array to be tested
3249      * @param bToIndex the index (exclusive) of the last element in the
3250      *                 second array to be tested
3251      * @return {@code true} if the two arrays, over the specified ranges, are
3252      *         equal
3253      * @throws IllegalArgumentException
3254      *         if {@code aFromIndex > aToIndex} or
3255      *         if {@code bFromIndex > bToIndex}
3256      * @throws ArrayIndexOutOfBoundsException
3257      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
3258      *         if {@code bFromIndex < 0 or bToIndex > b.length}
3259      * @throws NullPointerException
3260      *         if either array is {@code null}
3261      * @since 9
3262      */
equals(Object[] a, int aFromIndex, int aToIndex, Object[] b, int bFromIndex, int bToIndex)3263     public static boolean equals(Object[] a, int aFromIndex, int aToIndex,
3264                                  Object[] b, int bFromIndex, int bToIndex) {
3265         rangeCheck(a.length, aFromIndex, aToIndex);
3266         rangeCheck(b.length, bFromIndex, bToIndex);
3267 
3268         int aLength = aToIndex - aFromIndex;
3269         int bLength = bToIndex - bFromIndex;
3270         if (aLength != bLength)
3271             return false;
3272 
3273         for (int i = 0; i < aLength; i++) {
3274             if (!Objects.equals(a[aFromIndex++], b[bFromIndex++]))
3275                 return false;
3276         }
3277 
3278         return true;
3279     }
3280 
3281     /**
3282      * Returns {@code true} if the two specified arrays of Objects are
3283      * <i>equal</i> to one another.
3284      *
3285      * <p>Two arrays are considered equal if both arrays contain the same number
3286      * of elements, and all corresponding pairs of elements in the two arrays
3287      * are equal.  In other words, the two arrays are equal if they contain the
3288      * same elements in the same order.  Also, two array references are
3289      * considered equal if both are {@code null}.
3290      *
3291      * <p>Two objects {@code e1} and {@code e2} are considered <i>equal</i> if,
3292      * given the specified comparator, {@code cmp.compare(e1, e2) == 0}.
3293      *
3294      * @param a one array to be tested for equality
3295      * @param a2 the other array to be tested for equality
3296      * @param cmp the comparator to compare array elements
3297      * @param <T> the type of array elements
3298      * @return {@code true} if the two arrays are equal
3299      * @throws NullPointerException if the comparator is {@code null}
3300      * @since 9
3301      */
equals(T[] a, T[] a2, Comparator<? super T> cmp)3302     public static <T> boolean equals(T[] a, T[] a2, Comparator<? super T> cmp) {
3303         Objects.requireNonNull(cmp);
3304         if (a==a2)
3305             return true;
3306         if (a==null || a2==null)
3307             return false;
3308 
3309         int length = a.length;
3310         if (a2.length != length)
3311             return false;
3312 
3313         for (int i=0; i<length; i++) {
3314             if (cmp.compare(a[i], a2[i]) != 0)
3315                 return false;
3316         }
3317 
3318         return true;
3319     }
3320 
3321     /**
3322      * Returns true if the two specified arrays of Objects, over the specified
3323      * ranges, are <i>equal</i> to one another.
3324      *
3325      * <p>Two arrays are considered equal if the number of elements covered by
3326      * each range is the same, and all corresponding pairs of elements over the
3327      * specified ranges in the two arrays are equal.  In other words, two arrays
3328      * are equal if they contain, over the specified ranges, the same elements
3329      * in the same order.
3330      *
3331      * <p>Two objects {@code e1} and {@code e2} are considered <i>equal</i> if,
3332      * given the specified comparator, {@code cmp.compare(e1, e2) == 0}.
3333      *
3334      * @param a the first array to be tested for equality
3335      * @param aFromIndex the index (inclusive) of the first element in the
3336      *                   first array to be tested
3337      * @param aToIndex the index (exclusive) of the last element in the
3338      *                 first array to be tested
3339      * @param b the second array to be tested for equality
3340      * @param bFromIndex the index (inclusive) of the first element in the
3341      *                   second array to be tested
3342      * @param bToIndex the index (exclusive) of the last element in the
3343      *                 second array to be tested
3344      * @param cmp the comparator to compare array elements
3345      * @param <T> the type of array elements
3346      * @return {@code true} if the two arrays, over the specified ranges, are
3347      *         equal
3348      * @throws IllegalArgumentException
3349      *         if {@code aFromIndex > aToIndex} or
3350      *         if {@code bFromIndex > bToIndex}
3351      * @throws ArrayIndexOutOfBoundsException
3352      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
3353      *         if {@code bFromIndex < 0 or bToIndex > b.length}
3354      * @throws NullPointerException
3355      *         if either array or the comparator is {@code null}
3356      * @since 9
3357      */
equals(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex, Comparator<? super T> cmp)3358     public static <T> boolean equals(T[] a, int aFromIndex, int aToIndex,
3359                                      T[] b, int bFromIndex, int bToIndex,
3360                                      Comparator<? super T> cmp) {
3361         Objects.requireNonNull(cmp);
3362         rangeCheck(a.length, aFromIndex, aToIndex);
3363         rangeCheck(b.length, bFromIndex, bToIndex);
3364 
3365         int aLength = aToIndex - aFromIndex;
3366         int bLength = bToIndex - bFromIndex;
3367         if (aLength != bLength)
3368             return false;
3369 
3370         for (int i = 0; i < aLength; i++) {
3371             if (cmp.compare(a[aFromIndex++], b[bFromIndex++]) != 0)
3372                 return false;
3373         }
3374 
3375         return true;
3376     }
3377 
3378     // Filling
3379 
3380     /**
3381      * Assigns the specified long value to each element of the specified array
3382      * of longs.
3383      *
3384      * @param a the array to be filled
3385      * @param val the value to be stored in all elements of the array
3386      */
fill(long[] a, long val)3387     public static void fill(long[] a, long val) {
3388         for (int i = 0, len = a.length; i < len; i++)
3389             a[i] = val;
3390     }
3391 
3392     /**
3393      * Assigns the specified long value to each element of the specified
3394      * range of the specified array of longs.  The range to be filled
3395      * extends from index {@code fromIndex}, inclusive, to index
3396      * {@code toIndex}, exclusive.  (If {@code fromIndex==toIndex}, the
3397      * range to be filled is empty.)
3398      *
3399      * @param a the array to be filled
3400      * @param fromIndex the index of the first element (inclusive) to be
3401      *        filled with the specified value
3402      * @param toIndex the index of the last element (exclusive) to be
3403      *        filled with the specified value
3404      * @param val the value to be stored in all elements of the array
3405      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
3406      * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
3407      *         {@code toIndex > a.length}
3408      */
fill(long[] a, int fromIndex, int toIndex, long val)3409     public static void fill(long[] a, int fromIndex, int toIndex, long val) {
3410         rangeCheck(a.length, fromIndex, toIndex);
3411         for (int i = fromIndex; i < toIndex; i++)
3412             a[i] = val;
3413     }
3414 
3415     /**
3416      * Assigns the specified int value to each element of the specified array
3417      * of ints.
3418      *
3419      * @param a the array to be filled
3420      * @param val the value to be stored in all elements of the array
3421      */
fill(int[] a, int val)3422     public static void fill(int[] a, int val) {
3423         for (int i = 0, len = a.length; i < len; i++)
3424             a[i] = val;
3425     }
3426 
3427     /**
3428      * Assigns the specified int value to each element of the specified
3429      * range of the specified array of ints.  The range to be filled
3430      * extends from index {@code fromIndex}, inclusive, to index
3431      * {@code toIndex}, exclusive.  (If {@code fromIndex==toIndex}, the
3432      * range to be filled is empty.)
3433      *
3434      * @param a the array to be filled
3435      * @param fromIndex the index of the first element (inclusive) to be
3436      *        filled with the specified value
3437      * @param toIndex the index of the last element (exclusive) to be
3438      *        filled with the specified value
3439      * @param val the value to be stored in all elements of the array
3440      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
3441      * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
3442      *         {@code toIndex > a.length}
3443      */
fill(int[] a, int fromIndex, int toIndex, int val)3444     public static void fill(int[] a, int fromIndex, int toIndex, int val) {
3445         rangeCheck(a.length, fromIndex, toIndex);
3446         for (int i = fromIndex; i < toIndex; i++)
3447             a[i] = val;
3448     }
3449 
3450     /**
3451      * Assigns the specified short value to each element of the specified array
3452      * of shorts.
3453      *
3454      * @param a the array to be filled
3455      * @param val the value to be stored in all elements of the array
3456      */
fill(short[] a, short val)3457     public static void fill(short[] a, short val) {
3458         for (int i = 0, len = a.length; i < len; i++)
3459             a[i] = val;
3460     }
3461 
3462     /**
3463      * Assigns the specified short value to each element of the specified
3464      * range of the specified array of shorts.  The range to be filled
3465      * extends from index {@code fromIndex}, inclusive, to index
3466      * {@code toIndex}, exclusive.  (If {@code fromIndex==toIndex}, the
3467      * range to be filled is empty.)
3468      *
3469      * @param a the array to be filled
3470      * @param fromIndex the index of the first element (inclusive) to be
3471      *        filled with the specified value
3472      * @param toIndex the index of the last element (exclusive) to be
3473      *        filled with the specified value
3474      * @param val the value to be stored in all elements of the array
3475      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
3476      * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
3477      *         {@code toIndex > a.length}
3478      */
fill(short[] a, int fromIndex, int toIndex, short val)3479     public static void fill(short[] a, int fromIndex, int toIndex, short val) {
3480         rangeCheck(a.length, fromIndex, toIndex);
3481         for (int i = fromIndex; i < toIndex; i++)
3482             a[i] = val;
3483     }
3484 
3485     /**
3486      * Assigns the specified char value to each element of the specified array
3487      * of chars.
3488      *
3489      * @param a the array to be filled
3490      * @param val the value to be stored in all elements of the array
3491      */
fill(char[] a, char val)3492     public static void fill(char[] a, char val) {
3493         for (int i = 0, len = a.length; i < len; i++)
3494             a[i] = val;
3495     }
3496 
3497     /**
3498      * Assigns the specified char value to each element of the specified
3499      * range of the specified array of chars.  The range to be filled
3500      * extends from index {@code fromIndex}, inclusive, to index
3501      * {@code toIndex}, exclusive.  (If {@code fromIndex==toIndex}, the
3502      * range to be filled is empty.)
3503      *
3504      * @param a the array to be filled
3505      * @param fromIndex the index of the first element (inclusive) to be
3506      *        filled with the specified value
3507      * @param toIndex the index of the last element (exclusive) to be
3508      *        filled with the specified value
3509      * @param val the value to be stored in all elements of the array
3510      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
3511      * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
3512      *         {@code toIndex > a.length}
3513      */
fill(char[] a, int fromIndex, int toIndex, char val)3514     public static void fill(char[] a, int fromIndex, int toIndex, char val) {
3515         rangeCheck(a.length, fromIndex, toIndex);
3516         for (int i = fromIndex; i < toIndex; i++)
3517             a[i] = val;
3518     }
3519 
3520     /**
3521      * Assigns the specified byte value to each element of the specified array
3522      * of bytes.
3523      *
3524      * @param a the array to be filled
3525      * @param val the value to be stored in all elements of the array
3526      */
fill(byte[] a, byte val)3527     public static void fill(byte[] a, byte val) {
3528         for (int i = 0, len = a.length; i < len; i++)
3529             a[i] = val;
3530     }
3531 
3532     /**
3533      * Assigns the specified byte value to each element of the specified
3534      * range of the specified array of bytes.  The range to be filled
3535      * extends from index {@code fromIndex}, inclusive, to index
3536      * {@code toIndex}, exclusive.  (If {@code fromIndex==toIndex}, the
3537      * range to be filled is empty.)
3538      *
3539      * @param a the array to be filled
3540      * @param fromIndex the index of the first element (inclusive) to be
3541      *        filled with the specified value
3542      * @param toIndex the index of the last element (exclusive) to be
3543      *        filled with the specified value
3544      * @param val the value to be stored in all elements of the array
3545      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
3546      * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
3547      *         {@code toIndex > a.length}
3548      */
fill(byte[] a, int fromIndex, int toIndex, byte val)3549     public static void fill(byte[] a, int fromIndex, int toIndex, byte val) {
3550         rangeCheck(a.length, fromIndex, toIndex);
3551         for (int i = fromIndex; i < toIndex; i++)
3552             a[i] = val;
3553     }
3554 
3555     /**
3556      * Assigns the specified boolean value to each element of the specified
3557      * array of booleans.
3558      *
3559      * @param a the array to be filled
3560      * @param val the value to be stored in all elements of the array
3561      */
fill(boolean[] a, boolean val)3562     public static void fill(boolean[] a, boolean val) {
3563         for (int i = 0, len = a.length; i < len; i++)
3564             a[i] = val;
3565     }
3566 
3567     /**
3568      * Assigns the specified boolean value to each element of the specified
3569      * range of the specified array of booleans.  The range to be filled
3570      * extends from index {@code fromIndex}, inclusive, to index
3571      * {@code toIndex}, exclusive.  (If {@code fromIndex==toIndex}, the
3572      * range to be filled is empty.)
3573      *
3574      * @param a the array to be filled
3575      * @param fromIndex the index of the first element (inclusive) to be
3576      *        filled with the specified value
3577      * @param toIndex the index of the last element (exclusive) to be
3578      *        filled with the specified value
3579      * @param val the value to be stored in all elements of the array
3580      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
3581      * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
3582      *         {@code toIndex > a.length}
3583      */
fill(boolean[] a, int fromIndex, int toIndex, boolean val)3584     public static void fill(boolean[] a, int fromIndex, int toIndex,
3585                             boolean val) {
3586         rangeCheck(a.length, fromIndex, toIndex);
3587         for (int i = fromIndex; i < toIndex; i++)
3588             a[i] = val;
3589     }
3590 
3591     /**
3592      * Assigns the specified double value to each element of the specified
3593      * array of doubles.
3594      *
3595      * @param a the array to be filled
3596      * @param val the value to be stored in all elements of the array
3597      */
fill(double[] a, double val)3598     public static void fill(double[] a, double val) {
3599         for (int i = 0, len = a.length; i < len; i++)
3600             a[i] = val;
3601     }
3602 
3603     /**
3604      * Assigns the specified double value to each element of the specified
3605      * range of the specified array of doubles.  The range to be filled
3606      * extends from index {@code fromIndex}, inclusive, to index
3607      * {@code toIndex}, exclusive.  (If {@code fromIndex==toIndex}, the
3608      * range to be filled is empty.)
3609      *
3610      * @param a the array to be filled
3611      * @param fromIndex the index of the first element (inclusive) to be
3612      *        filled with the specified value
3613      * @param toIndex the index of the last element (exclusive) to be
3614      *        filled with the specified value
3615      * @param val the value to be stored in all elements of the array
3616      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
3617      * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
3618      *         {@code toIndex > a.length}
3619      */
fill(double[] a, int fromIndex, int toIndex,double val)3620     public static void fill(double[] a, int fromIndex, int toIndex,double val){
3621         rangeCheck(a.length, fromIndex, toIndex);
3622         for (int i = fromIndex; i < toIndex; i++)
3623             a[i] = val;
3624     }
3625 
3626     /**
3627      * Assigns the specified float value to each element of the specified array
3628      * of floats.
3629      *
3630      * @param a the array to be filled
3631      * @param val the value to be stored in all elements of the array
3632      */
fill(float[] a, float val)3633     public static void fill(float[] a, float val) {
3634         for (int i = 0, len = a.length; i < len; i++)
3635             a[i] = val;
3636     }
3637 
3638     /**
3639      * Assigns the specified float value to each element of the specified
3640      * range of the specified array of floats.  The range to be filled
3641      * extends from index {@code fromIndex}, inclusive, to index
3642      * {@code toIndex}, exclusive.  (If {@code fromIndex==toIndex}, the
3643      * range to be filled is empty.)
3644      *
3645      * @param a the array to be filled
3646      * @param fromIndex the index of the first element (inclusive) to be
3647      *        filled with the specified value
3648      * @param toIndex the index of the last element (exclusive) to be
3649      *        filled with the specified value
3650      * @param val the value to be stored in all elements of the array
3651      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
3652      * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
3653      *         {@code toIndex > a.length}
3654      */
fill(float[] a, int fromIndex, int toIndex, float val)3655     public static void fill(float[] a, int fromIndex, int toIndex, float val) {
3656         rangeCheck(a.length, fromIndex, toIndex);
3657         for (int i = fromIndex; i < toIndex; i++)
3658             a[i] = val;
3659     }
3660 
3661     /**
3662      * Assigns the specified Object reference to each element of the specified
3663      * array of Objects.
3664      *
3665      * @param a the array to be filled
3666      * @param val the value to be stored in all elements of the array
3667      * @throws ArrayStoreException if the specified value is not of a
3668      *         runtime type that can be stored in the specified array
3669      */
fill(Object[] a, Object val)3670     public static void fill(Object[] a, Object val) {
3671         for (int i = 0, len = a.length; i < len; i++)
3672             a[i] = val;
3673     }
3674 
3675     /**
3676      * Assigns the specified Object reference to each element of the specified
3677      * range of the specified array of Objects.  The range to be filled
3678      * extends from index {@code fromIndex}, inclusive, to index
3679      * {@code toIndex}, exclusive.  (If {@code fromIndex==toIndex}, the
3680      * range to be filled is empty.)
3681      *
3682      * @param a the array to be filled
3683      * @param fromIndex the index of the first element (inclusive) to be
3684      *        filled with the specified value
3685      * @param toIndex the index of the last element (exclusive) to be
3686      *        filled with the specified value
3687      * @param val the value to be stored in all elements of the array
3688      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
3689      * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
3690      *         {@code toIndex > a.length}
3691      * @throws ArrayStoreException if the specified value is not of a
3692      *         runtime type that can be stored in the specified array
3693      */
fill(Object[] a, int fromIndex, int toIndex, Object val)3694     public static void fill(Object[] a, int fromIndex, int toIndex, Object val) {
3695         rangeCheck(a.length, fromIndex, toIndex);
3696         for (int i = fromIndex; i < toIndex; i++)
3697             a[i] = val;
3698     }
3699 
3700     // Cloning
3701 
3702     /**
3703      * Copies the specified array, truncating or padding with nulls (if necessary)
3704      * so the copy has the specified length.  For all indices that are
3705      * valid in both the original array and the copy, the two arrays will
3706      * contain identical values.  For any indices that are valid in the
3707      * copy but not the original, the copy will contain {@code null}.
3708      * Such indices will exist if and only if the specified length
3709      * is greater than that of the original array.
3710      * The resulting array is of exactly the same class as the original array.
3711      *
3712      * @param <T> the class of the objects in the array
3713      * @param original the array to be copied
3714      * @param newLength the length of the copy to be returned
3715      * @return a copy of the original array, truncated or padded with nulls
3716      *     to obtain the specified length
3717      * @throws NegativeArraySizeException if {@code newLength} is negative
3718      * @throws NullPointerException if {@code original} is null
3719      * @since 1.6
3720      */
3721     @SuppressWarnings("unchecked")
copyOf(T[] original, int newLength)3722     public static <T> T[] copyOf(T[] original, int newLength) {
3723         return (T[]) copyOf(original, newLength, original.getClass());
3724     }
3725 
3726     /**
3727      * Copies the specified array, truncating or padding with nulls (if necessary)
3728      * so the copy has the specified length.  For all indices that are
3729      * valid in both the original array and the copy, the two arrays will
3730      * contain identical values.  For any indices that are valid in the
3731      * copy but not the original, the copy will contain {@code null}.
3732      * Such indices will exist if and only if the specified length
3733      * is greater than that of the original array.
3734      * The resulting array is of the class {@code newType}.
3735      *
3736      * @param <U> the class of the objects in the original array
3737      * @param <T> the class of the objects in the returned array
3738      * @param original the array to be copied
3739      * @param newLength the length of the copy to be returned
3740      * @param newType the class of the copy to be returned
3741      * @return a copy of the original array, truncated or padded with nulls
3742      *     to obtain the specified length
3743      * @throws NegativeArraySizeException if {@code newLength} is negative
3744      * @throws NullPointerException if {@code original} is null
3745      * @throws ArrayStoreException if an element copied from
3746      *     {@code original} is not of a runtime type that can be stored in
3747      *     an array of class {@code newType}
3748      * @since 1.6
3749      */
3750     @IntrinsicCandidate
copyOf(U[] original, int newLength, Class<? extends T[]> newType)3751     public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
3752         @SuppressWarnings("unchecked")
3753         T[] copy = ((Object)newType == (Object)Object[].class)
3754             ? (T[]) new Object[newLength]
3755             : (T[]) Array.newInstance(newType.getComponentType(), newLength);
3756         System.arraycopy(original, 0, copy, 0,
3757                          Math.min(original.length, newLength));
3758         return copy;
3759     }
3760 
3761     /**
3762      * Copies the specified array, truncating or padding with zeros (if necessary)
3763      * so the copy has the specified length.  For all indices that are
3764      * valid in both the original array and the copy, the two arrays will
3765      * contain identical values.  For any indices that are valid in the
3766      * copy but not the original, the copy will contain {@code (byte)0}.
3767      * Such indices will exist if and only if the specified length
3768      * is greater than that of the original array.
3769      *
3770      * @param original the array to be copied
3771      * @param newLength the length of the copy to be returned
3772      * @return a copy of the original array, truncated or padded with zeros
3773      *     to obtain the specified length
3774      * @throws NegativeArraySizeException if {@code newLength} is negative
3775      * @throws NullPointerException if {@code original} is null
3776      * @since 1.6
3777      */
copyOf(byte[] original, int newLength)3778     public static byte[] copyOf(byte[] original, int newLength) {
3779         // Android-removed: TODO(b/359517996) .clone() is slower than System.arraycopy.
3780         /*
3781         if (newLength == original.length) {
3782             return original.clone();
3783         }
3784         */
3785         byte[] copy = new byte[newLength];
3786         System.arraycopy(original, 0, copy, 0,
3787                          Math.min(original.length, newLength));
3788         return copy;
3789     }
3790 
3791     /**
3792      * Copies the specified array, truncating or padding with zeros (if necessary)
3793      * so the copy has the specified length.  For all indices that are
3794      * valid in both the original array and the copy, the two arrays will
3795      * contain identical values.  For any indices that are valid in the
3796      * copy but not the original, the copy will contain {@code (short)0}.
3797      * Such indices will exist if and only if the specified length
3798      * is greater than that of the original array.
3799      *
3800      * @param original the array to be copied
3801      * @param newLength the length of the copy to be returned
3802      * @return a copy of the original array, truncated or padded with zeros
3803      *     to obtain the specified length
3804      * @throws NegativeArraySizeException if {@code newLength} is negative
3805      * @throws NullPointerException if {@code original} is null
3806      * @since 1.6
3807      */
copyOf(short[] original, int newLength)3808     public static short[] copyOf(short[] original, int newLength) {
3809         // Android-removed: TODO(b/359517996) .clone() is slower than System.arraycopy.
3810         /*
3811         if (newLength == original.length) {
3812             return original.clone();
3813         }
3814         */
3815         short[] copy = new short[newLength];
3816         System.arraycopy(original, 0, copy, 0,
3817                          Math.min(original.length, newLength));
3818         return copy;
3819     }
3820 
3821     /**
3822      * Copies the specified array, truncating or padding with zeros (if necessary)
3823      * so the copy has the specified length.  For all indices that are
3824      * valid in both the original array and the copy, the two arrays will
3825      * contain identical values.  For any indices that are valid in the
3826      * copy but not the original, the copy will contain {@code 0}.
3827      * Such indices will exist if and only if the specified length
3828      * is greater than that of the original array.
3829      *
3830      * @param original the array to be copied
3831      * @param newLength the length of the copy to be returned
3832      * @return a copy of the original array, truncated or padded with zeros
3833      *     to obtain the specified length
3834      * @throws NegativeArraySizeException if {@code newLength} is negative
3835      * @throws NullPointerException if {@code original} is null
3836      * @since 1.6
3837      */
copyOf(int[] original, int newLength)3838     public static int[] copyOf(int[] original, int newLength) {
3839         // Android-removed: TODO(b/359517996) .clone() is slower than System.arraycopy.
3840         /*
3841         if (newLength == original.length) {
3842             return original.clone();
3843         }
3844         */
3845         int[] copy = new int[newLength];
3846         System.arraycopy(original, 0, copy, 0,
3847                          Math.min(original.length, newLength));
3848         return copy;
3849     }
3850 
3851 
3852     /**
3853      * Copies the specified array, truncating or padding with zeros (if necessary)
3854      * so the copy has the specified length.  For all indices that are
3855      * valid in both the original array and the copy, the two arrays will
3856      * contain identical values.  For any indices that are valid in the
3857      * copy but not the original, the copy will contain {@code 0L}.
3858      * Such indices will exist if and only if the specified length
3859      * is greater than that of the original array.
3860      *
3861      * @param original the array to be copied
3862      * @param newLength the length of the copy to be returned
3863      * @return a copy of the original array, truncated or padded with zeros
3864      *     to obtain the specified length
3865      * @throws NegativeArraySizeException if {@code newLength} is negative
3866      * @throws NullPointerException if {@code original} is null
3867      * @since 1.6
3868      */
copyOf(long[] original, int newLength)3869     public static long[] copyOf(long[] original, int newLength) {
3870         // Android-removed: TODO(b/359517996) .clone() is slower than System.arraycopy.
3871         /*
3872         if (newLength == original.length) {
3873             return original.clone();
3874         }
3875         */
3876         long[] copy = new long[newLength];
3877         System.arraycopy(original, 0, copy, 0,
3878                          Math.min(original.length, newLength));
3879         return copy;
3880     }
3881 
3882     /**
3883      * Copies the specified array, truncating or padding with null characters (if necessary)
3884      * so the copy has the specified length.  For all indices that are valid
3885      * in both the original array and the copy, the two arrays will contain
3886      * identical values.  For any indices that are valid in the copy but not
3887      * the original, the copy will contain {@code '\u005cu0000'}.  Such indices
3888      * will exist if and only if the specified length is greater than that of
3889      * the original array.
3890      *
3891      * @param original the array to be copied
3892      * @param newLength the length of the copy to be returned
3893      * @return a copy of the original array, truncated or padded with null characters
3894      *     to obtain the specified length
3895      * @throws NegativeArraySizeException if {@code newLength} is negative
3896      * @throws NullPointerException if {@code original} is null
3897      * @since 1.6
3898      */
copyOf(char[] original, int newLength)3899     public static char[] copyOf(char[] original, int newLength) {
3900         // Android-removed: TODO(b/359517996) .clone() is slower than System.arraycopy.
3901         /*
3902         if (newLength == original.length) {
3903             return original.clone();
3904         }
3905         */
3906         char[] copy = new char[newLength];
3907         System.arraycopy(original, 0, copy, 0,
3908                          Math.min(original.length, newLength));
3909         return copy;
3910     }
3911 
3912     /**
3913      * Copies the specified array, truncating or padding with zeros (if necessary)
3914      * so the copy has the specified length.  For all indices that are
3915      * valid in both the original array and the copy, the two arrays will
3916      * contain identical values.  For any indices that are valid in the
3917      * copy but not the original, the copy will contain {@code 0f}.
3918      * Such indices will exist if and only if the specified length
3919      * is greater than that of the original array.
3920      *
3921      * @param original the array to be copied
3922      * @param newLength the length of the copy to be returned
3923      * @return a copy of the original array, truncated or padded with zeros
3924      *     to obtain the specified length
3925      * @throws NegativeArraySizeException if {@code newLength} is negative
3926      * @throws NullPointerException if {@code original} is null
3927      * @since 1.6
3928      */
copyOf(float[] original, int newLength)3929     public static float[] copyOf(float[] original, int newLength) {
3930         // Android-removed: TODO(b/359517996) .clone() is slower than System.arraycopy.
3931         /*
3932         if (newLength == original.length) {
3933             return original.clone();
3934         }
3935         */
3936         float[] copy = new float[newLength];
3937         System.arraycopy(original, 0, copy, 0,
3938                          Math.min(original.length, newLength));
3939         return copy;
3940     }
3941 
3942     /**
3943      * Copies the specified array, truncating or padding with zeros (if necessary)
3944      * so the copy has the specified length.  For all indices that are
3945      * valid in both the original array and the copy, the two arrays will
3946      * contain identical values.  For any indices that are valid in the
3947      * copy but not the original, the copy will contain {@code 0d}.
3948      * Such indices will exist if and only if the specified length
3949      * is greater than that of the original array.
3950      *
3951      * @param original the array to be copied
3952      * @param newLength the length of the copy to be returned
3953      * @return a copy of the original array, truncated or padded with zeros
3954      *     to obtain the specified length
3955      * @throws NegativeArraySizeException if {@code newLength} is negative
3956      * @throws NullPointerException if {@code original} is null
3957      * @since 1.6
3958      */
copyOf(double[] original, int newLength)3959     public static double[] copyOf(double[] original, int newLength) {
3960         // Android-removed: TODO(b/359517996) .clone() is slower than System.arraycopy.
3961         /*
3962         if (newLength == original.length) {
3963             return original.clone();
3964         }
3965         */
3966         double[] copy = new double[newLength];
3967         System.arraycopy(original, 0, copy, 0,
3968                          Math.min(original.length, newLength));
3969         return copy;
3970     }
3971 
3972     /**
3973      * Copies the specified array, truncating or padding with {@code false} (if necessary)
3974      * so the copy has the specified length.  For all indices that are
3975      * valid in both the original array and the copy, the two arrays will
3976      * contain identical values.  For any indices that are valid in the
3977      * copy but not the original, the copy will contain {@code false}.
3978      * Such indices will exist if and only if the specified length
3979      * is greater than that of the original array.
3980      *
3981      * @param original the array to be copied
3982      * @param newLength the length of the copy to be returned
3983      * @return a copy of the original array, truncated or padded with false elements
3984      *     to obtain the specified length
3985      * @throws NegativeArraySizeException if {@code newLength} is negative
3986      * @throws NullPointerException if {@code original} is null
3987      * @since 1.6
3988      */
copyOf(boolean[] original, int newLength)3989     public static boolean[] copyOf(boolean[] original, int newLength) {
3990         // Android-removed: TODO(b/359517996) .clone() is slower than System.arraycopy.
3991         /*
3992         if (newLength == original.length) {
3993             return original.clone();
3994         }
3995         */
3996         boolean[] copy = new boolean[newLength];
3997         System.arraycopy(original, 0, copy, 0,
3998                          Math.min(original.length, newLength));
3999         return copy;
4000     }
4001 
4002     /**
4003      * Copies the specified range of the specified array into a new array.
4004      * The initial index of the range ({@code from}) must lie between zero
4005      * and {@code original.length}, inclusive.  The value at
4006      * {@code original[from]} is placed into the initial element of the copy
4007      * (unless {@code from == original.length} or {@code from == to}).
4008      * Values from subsequent elements in the original array are placed into
4009      * subsequent elements in the copy.  The final index of the range
4010      * ({@code to}), which must be greater than or equal to {@code from},
4011      * may be greater than {@code original.length}, in which case
4012      * {@code null} is placed in all elements of the copy whose index is
4013      * greater than or equal to {@code original.length - from}.  The length
4014      * of the returned array will be {@code to - from}.
4015      * <p>
4016      * The resulting array is of exactly the same class as the original array.
4017      *
4018      * @param <T> the class of the objects in the array
4019      * @param original the array from which a range is to be copied
4020      * @param from the initial index of the range to be copied, inclusive
4021      * @param to the final index of the range to be copied, exclusive.
4022      *     (This index may lie outside the array.)
4023      * @return a new array containing the specified range from the original array,
4024      *     truncated or padded with nulls to obtain the required length
4025      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
4026      *     or {@code from > original.length}
4027      * @throws IllegalArgumentException if {@code from > to}
4028      * @throws NullPointerException if {@code original} is null
4029      * @since 1.6
4030      */
4031     @SuppressWarnings("unchecked")
copyOfRange(T[] original, int from, int to)4032     public static <T> T[] copyOfRange(T[] original, int from, int to) {
4033         return copyOfRange(original, from, to, (Class<? extends T[]>) original.getClass());
4034     }
4035 
4036     /**
4037      * Copies the specified range of the specified array into a new array.
4038      * The initial index of the range ({@code from}) must lie between zero
4039      * and {@code original.length}, inclusive.  The value at
4040      * {@code original[from]} is placed into the initial element of the copy
4041      * (unless {@code from == original.length} or {@code from == to}).
4042      * Values from subsequent elements in the original array are placed into
4043      * subsequent elements in the copy.  The final index of the range
4044      * ({@code to}), which must be greater than or equal to {@code from},
4045      * may be greater than {@code original.length}, in which case
4046      * {@code null} is placed in all elements of the copy whose index is
4047      * greater than or equal to {@code original.length - from}.  The length
4048      * of the returned array will be {@code to - from}.
4049      * The resulting array is of the class {@code newType}.
4050      *
4051      * @param <U> the class of the objects in the original array
4052      * @param <T> the class of the objects in the returned array
4053      * @param original the array from which a range is to be copied
4054      * @param from the initial index of the range to be copied, inclusive
4055      * @param to the final index of the range to be copied, exclusive.
4056      *     (This index may lie outside the array.)
4057      * @param newType the class of the copy to be returned
4058      * @return a new array containing the specified range from the original array,
4059      *     truncated or padded with nulls to obtain the required length
4060      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
4061      *     or {@code from > original.length}
4062      * @throws IllegalArgumentException if {@code from > to}
4063      * @throws NullPointerException if {@code original} is null
4064      * @throws ArrayStoreException if an element copied from
4065      *     {@code original} is not of a runtime type that can be stored in
4066      *     an array of class {@code newType}.
4067      * @since 1.6
4068      */
4069     @IntrinsicCandidate
copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)4070     public static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {
4071         int newLength = to - from;
4072         if (newLength < 0)
4073             throw new IllegalArgumentException(from + " > " + to);
4074         @SuppressWarnings("unchecked")
4075         T[] copy = ((Object)newType == (Object)Object[].class)
4076             ? (T[]) new Object[newLength]
4077             : (T[]) Array.newInstance(newType.getComponentType(), newLength);
4078         System.arraycopy(original, from, copy, 0,
4079                          Math.min(original.length - from, newLength));
4080         return copy;
4081     }
4082 
4083     @ForceInline
checkLength(int from, int to)4084     private static void checkLength(int from, int to) {
4085         if (to < from) {
4086             throw new IllegalArgumentException(from + " > " + to);
4087         }
4088     }
4089 
4090     /**
4091      * Copies the specified range of the specified array into a new array.
4092      * The initial index of the range ({@code from}) must lie between zero
4093      * and {@code original.length}, inclusive.  The value at
4094      * {@code original[from]} is placed into the initial element of the copy
4095      * (unless {@code from == original.length} or {@code from == to}).
4096      * Values from subsequent elements in the original array are placed into
4097      * subsequent elements in the copy.  The final index of the range
4098      * ({@code to}), which must be greater than or equal to {@code from},
4099      * may be greater than {@code original.length}, in which case
4100      * {@code (byte)0} is placed in all elements of the copy whose index is
4101      * greater than or equal to {@code original.length - from}.  The length
4102      * of the returned array will be {@code to - from}.
4103      *
4104      * @param original the array from which a range is to be copied
4105      * @param from the initial index of the range to be copied, inclusive
4106      * @param to the final index of the range to be copied, exclusive.
4107      *     (This index may lie outside the array.)
4108      * @return a new array containing the specified range from the original array,
4109      *     truncated or padded with zeros to obtain the required length
4110      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
4111      *     or {@code from > original.length}
4112      * @throws IllegalArgumentException if {@code from > to}
4113      * @throws NullPointerException if {@code original} is null
4114      * @since 1.6
4115      */
copyOfRange(byte[] original, int from, int to)4116     public static byte[] copyOfRange(byte[] original, int from, int to) {
4117         // Tickle the JIT to fold special cases optimally
4118         // Android-changed: TODO(b/359517996) .clone() is slower than System.arraycopy.
4119         /*
4120         if (from != 0 || to != original.length)
4121             return copyOfRangeByte(original, from, to);
4122         else // from == 0 && to == original.length
4123             return original.clone();
4124         */
4125         return copyOfRangeByte(original, from, to);
4126     }
4127 
4128     @ForceInline
copyOfRangeByte(byte[] original, int from, int to)4129     private static byte[] copyOfRangeByte(byte[] original, int from, int to) {
4130         checkLength(from, to);
4131         int newLength = to - from;
4132         byte[] copy = new byte[newLength];
4133         System.arraycopy(original, from, copy, 0,
4134                          Math.min(original.length - from, newLength));
4135         return copy;
4136     }
4137 
4138     /**
4139      * Copies the specified range of the specified array into a new array.
4140      * The initial index of the range ({@code from}) must lie between zero
4141      * and {@code original.length}, inclusive.  The value at
4142      * {@code original[from]} is placed into the initial element of the copy
4143      * (unless {@code from == original.length} or {@code from == to}).
4144      * Values from subsequent elements in the original array are placed into
4145      * subsequent elements in the copy.  The final index of the range
4146      * ({@code to}), which must be greater than or equal to {@code from},
4147      * may be greater than {@code original.length}, in which case
4148      * {@code (short)0} is placed in all elements of the copy whose index is
4149      * greater than or equal to {@code original.length - from}.  The length
4150      * of the returned array will be {@code to - from}.
4151      *
4152      * @param original the array from which a range is to be copied
4153      * @param from the initial index of the range to be copied, inclusive
4154      * @param to the final index of the range to be copied, exclusive.
4155      *     (This index may lie outside the array.)
4156      * @return a new array containing the specified range from the original array,
4157      *     truncated or padded with zeros to obtain the required length
4158      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
4159      *     or {@code from > original.length}
4160      * @throws IllegalArgumentException if {@code from > to}
4161      * @throws NullPointerException if {@code original} is null
4162      * @since 1.6
4163      */
copyOfRange(short[] original, int from, int to)4164     public static short[] copyOfRange(short[] original, int from, int to) {
4165         // Tickle the JIT to fold special cases optimally
4166         // Android-changed: TODO(b/359517996) .clone() is slower than System.arraycopy.
4167         /*
4168         if (from != 0 || to != original.length)
4169             return copyOfRangeShort(original, from, to);
4170         else // from == 0 && to == original.length
4171             return original.clone();
4172         */
4173         return copyOfRangeShort(original, from, to);
4174     }
4175 
4176     @ForceInline
copyOfRangeShort(short[] original, int from, int to)4177     private static short[] copyOfRangeShort(short[] original, int from, int to) {
4178         checkLength(from, to);
4179         int newLength = to - from;
4180         short[] copy = new short[newLength];
4181         System.arraycopy(original, from, copy, 0,
4182                          Math.min(original.length - from, newLength));
4183         return copy;
4184     }
4185 
4186     /**
4187      * Copies the specified range of the specified array into a new array.
4188      * The initial index of the range ({@code from}) must lie between zero
4189      * and {@code original.length}, inclusive.  The value at
4190      * {@code original[from]} is placed into the initial element of the copy
4191      * (unless {@code from == original.length} or {@code from == to}).
4192      * Values from subsequent elements in the original array are placed into
4193      * subsequent elements in the copy.  The final index of the range
4194      * ({@code to}), which must be greater than or equal to {@code from},
4195      * may be greater than {@code original.length}, in which case
4196      * {@code 0} is placed in all elements of the copy whose index is
4197      * greater than or equal to {@code original.length - from}.  The length
4198      * of the returned array will be {@code to - from}.
4199      *
4200      * @param original the array from which a range is to be copied
4201      * @param from the initial index of the range to be copied, inclusive
4202      * @param to the final index of the range to be copied, exclusive.
4203      *     (This index may lie outside the array.)
4204      * @return a new array containing the specified range from the original array,
4205      *     truncated or padded with zeros to obtain the required length
4206      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
4207      *     or {@code from > original.length}
4208      * @throws IllegalArgumentException if {@code from > to}
4209      * @throws NullPointerException if {@code original} is null
4210      * @since 1.6
4211      */
copyOfRange(int[] original, int from, int to)4212     public static int[] copyOfRange(int[] original, int from, int to) {
4213         // Tickle the JIT to fold special cases optimally
4214         // Android-changed: TODO(b/359517996) .clone() is slower than System.arraycopy.
4215         /*
4216         if (from != 0 || to != original.length)
4217             return copyOfRangeInt(original, from, to);
4218         else // from == 0 && to == original.length
4219             return original.clone();
4220         */
4221         return copyOfRangeInt(original, from, to);
4222     }
4223 
4224     @ForceInline
copyOfRangeInt(int[] original, int from, int to)4225     private static int[] copyOfRangeInt(int[] original, int from, int to) {
4226         checkLength(from, to);
4227         int newLength = to - from;
4228         int[] copy = new int[newLength];
4229         System.arraycopy(original, from, copy, 0,
4230                          Math.min(original.length - from, newLength));
4231         return copy;
4232     }
4233 
4234     /**
4235      * Copies the specified range of the specified array into a new array.
4236      * The initial index of the range ({@code from}) must lie between zero
4237      * and {@code original.length}, inclusive.  The value at
4238      * {@code original[from]} is placed into the initial element of the copy
4239      * (unless {@code from == original.length} or {@code from == to}).
4240      * Values from subsequent elements in the original array are placed into
4241      * subsequent elements in the copy.  The final index of the range
4242      * ({@code to}), which must be greater than or equal to {@code from},
4243      * may be greater than {@code original.length}, in which case
4244      * {@code 0L} is placed in all elements of the copy whose index is
4245      * greater than or equal to {@code original.length - from}.  The length
4246      * of the returned array will be {@code to - from}.
4247      *
4248      * @param original the array from which a range is to be copied
4249      * @param from the initial index of the range to be copied, inclusive
4250      * @param to the final index of the range to be copied, exclusive.
4251      *     (This index may lie outside the array.)
4252      * @return a new array containing the specified range from the original array,
4253      *     truncated or padded with zeros to obtain the required length
4254      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
4255      *     or {@code from > original.length}
4256      * @throws IllegalArgumentException if {@code from > to}
4257      * @throws NullPointerException if {@code original} is null
4258      * @since 1.6
4259      */
copyOfRange(long[] original, int from, int to)4260     public static long[] copyOfRange(long[] original, int from, int to) {
4261         // Tickle the JIT to fold special cases optimally
4262         // Android-changed: TODO(b/359517996) .clone() is slower than System.arraycopy.
4263         /*
4264         if (from != 0 || to != original.length)
4265             return copyOfRangeLong(original, from, to);
4266         else // from == 0 && to == original.length
4267             return original.clone();
4268         */
4269         return copyOfRangeLong(original, from, to);
4270     }
4271 
4272     @ForceInline
copyOfRangeLong(long[] original, int from, int to)4273     private static long[] copyOfRangeLong(long[] original, int from, int to) {
4274         checkLength(from, to);
4275         int newLength = to - from;
4276         long[] copy = new long[newLength];
4277         System.arraycopy(original, from, copy, 0,
4278                          Math.min(original.length - from, newLength));
4279         return copy;
4280     }
4281 
4282     /**
4283      * Copies the specified range of the specified array into a new array.
4284      * The initial index of the range ({@code from}) must lie between zero
4285      * and {@code original.length}, inclusive.  The value at
4286      * {@code original[from]} is placed into the initial element of the copy
4287      * (unless {@code from == original.length} or {@code from == to}).
4288      * Values from subsequent elements in the original array are placed into
4289      * subsequent elements in the copy.  The final index of the range
4290      * ({@code to}), which must be greater than or equal to {@code from},
4291      * may be greater than {@code original.length}, in which case
4292      * {@code '\u005cu0000'} is placed in all elements of the copy whose index is
4293      * greater than or equal to {@code original.length - from}.  The length
4294      * of the returned array will be {@code to - from}.
4295      *
4296      * @param original the array from which a range is to be copied
4297      * @param from the initial index of the range to be copied, inclusive
4298      * @param to the final index of the range to be copied, exclusive.
4299      *     (This index may lie outside the array.)
4300      * @return a new array containing the specified range from the original array,
4301      *     truncated or padded with null characters to obtain the required length
4302      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
4303      *     or {@code from > original.length}
4304      * @throws IllegalArgumentException if {@code from > to}
4305      * @throws NullPointerException if {@code original} is null
4306      * @since 1.6
4307      */
copyOfRange(char[] original, int from, int to)4308     public static char[] copyOfRange(char[] original, int from, int to) {
4309         // Tickle the JIT to fold special cases optimally
4310         // Android-changed: TODO(b/359517996) .clone() is slower than System.arraycopy.
4311         /*
4312         if (from != 0 || to != original.length)
4313             return copyOfRangeChar(original, from, to);
4314         else // from == 0 && to == original.length
4315             return original.clone();
4316         */
4317         return copyOfRangeChar(original, from, to);
4318     }
4319 
4320 
4321     @ForceInline
copyOfRangeChar(char[] original, int from, int to)4322     private static char[] copyOfRangeChar(char[] original, int from, int to) {
4323         checkLength(from, to);
4324         int newLength = to - from;
4325         char[] copy = new char[newLength];
4326         System.arraycopy(original, from, copy, 0,
4327                          Math.min(original.length - from, newLength));
4328         return copy;
4329     }
4330 
4331     /**
4332      * Copies the specified range of the specified array into a new array.
4333      * The initial index of the range ({@code from}) must lie between zero
4334      * and {@code original.length}, inclusive.  The value at
4335      * {@code original[from]} is placed into the initial element of the copy
4336      * (unless {@code from == original.length} or {@code from == to}).
4337      * Values from subsequent elements in the original array are placed into
4338      * subsequent elements in the copy.  The final index of the range
4339      * ({@code to}), which must be greater than or equal to {@code from},
4340      * may be greater than {@code original.length}, in which case
4341      * {@code 0f} is placed in all elements of the copy whose index is
4342      * greater than or equal to {@code original.length - from}.  The length
4343      * of the returned array will be {@code to - from}.
4344      *
4345      * @param original the array from which a range is to be copied
4346      * @param from the initial index of the range to be copied, inclusive
4347      * @param to the final index of the range to be copied, exclusive.
4348      *     (This index may lie outside the array.)
4349      * @return a new array containing the specified range from the original array,
4350      *     truncated or padded with zeros to obtain the required length
4351      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
4352      *     or {@code from > original.length}
4353      * @throws IllegalArgumentException if {@code from > to}
4354      * @throws NullPointerException if {@code original} is null
4355      * @since 1.6
4356      */
copyOfRange(float[] original, int from, int to)4357     public static float[] copyOfRange(float[] original, int from, int to) {
4358         // Tickle the JIT to fold special cases optimally
4359         // Android-changed: TODO(b/359517996) .clone() is slower than System.arraycopy.
4360         /*
4361         if (from != 0 || to != original.length)
4362             return copyOfRangeFloat(original, from, to);
4363         else // from == 0 && to == original.length
4364             return original.clone();
4365         */
4366         return copyOfRangeFloat(original, from, to);
4367     }
4368 
4369 
4370     @ForceInline
copyOfRangeFloat(float[] original, int from, int to)4371     private static float[] copyOfRangeFloat(float[] original, int from, int to) {
4372         checkLength(from, to);
4373         int newLength = to - from;
4374         float[] copy = new float[newLength];
4375         System.arraycopy(original, from, copy, 0,
4376                          Math.min(original.length - from, newLength));
4377         return copy;
4378     }
4379 
4380     /**
4381      * Copies the specified range of the specified array into a new array.
4382      * The initial index of the range ({@code from}) must lie between zero
4383      * and {@code original.length}, inclusive.  The value at
4384      * {@code original[from]} is placed into the initial element of the copy
4385      * (unless {@code from == original.length} or {@code from == to}).
4386      * Values from subsequent elements in the original array are placed into
4387      * subsequent elements in the copy.  The final index of the range
4388      * ({@code to}), which must be greater than or equal to {@code from},
4389      * may be greater than {@code original.length}, in which case
4390      * {@code 0d} is placed in all elements of the copy whose index is
4391      * greater than or equal to {@code original.length - from}.  The length
4392      * of the returned array will be {@code to - from}.
4393      *
4394      * @param original the array from which a range is to be copied
4395      * @param from the initial index of the range to be copied, inclusive
4396      * @param to the final index of the range to be copied, exclusive.
4397      *     (This index may lie outside the array.)
4398      * @return a new array containing the specified range from the original array,
4399      *     truncated or padded with zeros to obtain the required length
4400      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
4401      *     or {@code from > original.length}
4402      * @throws IllegalArgumentException if {@code from > to}
4403      * @throws NullPointerException if {@code original} is null
4404      * @since 1.6
4405      */
copyOfRange(double[] original, int from, int to)4406     public static double[] copyOfRange(double[] original, int from, int to) {
4407         // Tickle the JIT to fold special cases optimally
4408         // Android-changed: TODO(b/359517996) .clone() is slower than System.arraycopy.
4409         /*
4410         if (from != 0 || to != original.length)
4411             return copyOfRangeDouble(original, from, to);
4412         else // from == 0 && to == original.length
4413             return original.clone();
4414         */
4415         return copyOfRangeDouble(original, from, to);
4416     }
4417 
4418 
4419     @ForceInline
copyOfRangeDouble(double[] original, int from, int to)4420     private static double[] copyOfRangeDouble(double[] original, int from, int to) {
4421         checkLength(from, to);
4422         int newLength = to - from;
4423         double[] copy = new double[newLength];
4424         System.arraycopy(original, from, copy, 0,
4425                          Math.min(original.length - from, newLength));
4426         return copy;
4427     }
4428 
4429     /**
4430      * Copies the specified range of the specified array into a new array.
4431      * The initial index of the range ({@code from}) must lie between zero
4432      * and {@code original.length}, inclusive.  The value at
4433      * {@code original[from]} is placed into the initial element of the copy
4434      * (unless {@code from == original.length} or {@code from == to}).
4435      * Values from subsequent elements in the original array are placed into
4436      * subsequent elements in the copy.  The final index of the range
4437      * ({@code to}), which must be greater than or equal to {@code from},
4438      * may be greater than {@code original.length}, in which case
4439      * {@code false} is placed in all elements of the copy whose index is
4440      * greater than or equal to {@code original.length - from}.  The length
4441      * of the returned array will be {@code to - from}.
4442      *
4443      * @param original the array from which a range is to be copied
4444      * @param from the initial index of the range to be copied, inclusive
4445      * @param to the final index of the range to be copied, exclusive.
4446      *     (This index may lie outside the array.)
4447      * @return a new array containing the specified range from the original array,
4448      *     truncated or padded with false elements to obtain the required length
4449      * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
4450      *     or {@code from > original.length}
4451      * @throws IllegalArgumentException if {@code from > to}
4452      * @throws NullPointerException if {@code original} is null
4453      * @since 1.6
4454      */
copyOfRange(boolean[] original, int from, int to)4455     public static boolean[] copyOfRange(boolean[] original, int from, int to) {
4456         // Tickle the JIT to fold special cases optimally
4457         // Android-changed: TODO(b/359517996) .clone() is slower than System.arraycopy.
4458         /*
4459         if (from != 0 || to != original.length)
4460             return copyOfRangeBoolean(original, from, to);
4461         else // from == 0 && to == original.length
4462             return original.clone();
4463         */
4464         return copyOfRangeBoolean(original, from, to);
4465     }
4466 
4467 
4468     @ForceInline
copyOfRangeBoolean(boolean[] original, int from, int to)4469     private static boolean[] copyOfRangeBoolean(boolean[] original, int from, int to) {
4470         checkLength(from, to);
4471         int newLength = to - from;
4472         boolean[] copy = new boolean[newLength];
4473         System.arraycopy(original, from, copy, 0,
4474                          Math.min(original.length - from, newLength));
4475         return copy;
4476     }
4477 
4478     // Misc
4479 
4480     /**
4481      * Returns a fixed-size list backed by the specified array. Changes made to
4482      * the array will be visible in the returned list, and changes made to the
4483      * list will be visible in the array. The returned list is
4484      * {@link Serializable} and implements {@link RandomAccess}.
4485      *
4486      * <p>The returned list implements the optional {@code Collection} methods, except
4487      * those that would change the size of the returned list. Those methods leave
4488      * the list unchanged and throw {@link UnsupportedOperationException}.
4489      *
4490      * <p>If the specified array's actual component type differs from the type
4491      * parameter T, this can result in operations on the returned list throwing an
4492      * {@code ArrayStoreException}.
4493      *
4494      * @apiNote
4495      * This method acts as bridge between array-based and collection-based
4496      * APIs, in combination with {@link Collection#toArray}.
4497      *
4498      * <p>This method provides a way to wrap an existing array:
4499      * <pre>{@code
4500      *     Integer[] numbers = ...
4501      *     ...
4502      *     List<Integer> values = Arrays.asList(numbers);
4503      * }</pre>
4504      *
4505      * <p>This method also provides a convenient way to create a fixed-size
4506      * list initialized to contain several elements:
4507      * <pre>{@code
4508      *     List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
4509      * }</pre>
4510      *
4511      * <p><em>The list returned by this method is modifiable.</em>
4512      * To create an unmodifiable list, use
4513      * {@link Collections#unmodifiableList Collections.unmodifiableList}
4514      * or <a href="List.html#unmodifiable">Unmodifiable Lists</a>.
4515      *
4516      * @param <T> the class of the objects in the array
4517      * @param a the array by which the list will be backed
4518      * @return a list view of the specified array
4519      * @throws NullPointerException if the specified array is {@code null}
4520      */
4521     @SafeVarargs
4522     @SuppressWarnings("varargs")
asList(T... a)4523     public static <T> List<T> asList(T... a) {
4524         return new ArrayList<>(a);
4525     }
4526 
4527     /**
4528      * Since Android 15 Arrays.asList(...).toArray()'s component type is {@link Object},
4529      * not the underlying array's elements type. So the following code will throw
4530      * {@link ClassCastException}:
4531      * <pre>{@code
4532      * String[] elements = (String[]) Arrays.asList("one", "two").toArray();
4533      * }</pre>
4534      * You can overcome this by using {@link Collection#toArray(Object[])}:
4535      * <pre>{@code
4536      * String[] elements = Arrays.asList("two", "one").toArray(new String[0]);
4537      * }</pre>
4538      * @hide
4539      */
4540     @ChangeId
4541     @EnabledSince(targetSdkVersion = VersionCodes.VANILLA_ICE_CREAM)
4542     public static final long DO_NOT_CLONE_IN_ARRAYS_AS_LIST = 202956589L;
4543 
4544     /**
4545      * @serial include
4546      */
4547     private static class ArrayList<E> extends AbstractList<E>
4548         implements RandomAccess, java.io.Serializable
4549     {
4550         @java.io.Serial
4551         private static final long serialVersionUID = -2764017481108945198L;
4552         private final E[] a;
4553 
ArrayList(E[] array)4554         ArrayList(E[] array) {
4555             a = Objects.requireNonNull(array);
4556         }
4557 
4558         @Override
size()4559         public int size() {
4560             return a.length;
4561         }
4562 
4563         @Override
toArray()4564         public Object[] toArray() {
4565             // Android-changed: there are applications which expect this method
4566             // to return array with component type E, not just Object.
4567             // Keeping pre-Java 9 behaviour for compatibility's sake.
4568             // See b/204397945.
4569             if (VMRuntime.getSdkVersion() >= VersionCodes.VANILLA_ICE_CREAM
4570                     && Compatibility.isChangeEnabled(DO_NOT_CLONE_IN_ARRAYS_AS_LIST)) {
4571                 return toArrayWithoutComponentType();
4572             }
4573             return toArrayPreserveComponentType();
4574         }
4575 
toArrayWithoutComponentType()4576         private Object[] toArrayWithoutComponentType() {
4577             return Arrays.copyOf(a, a.length, Object[].class);
4578         }
4579 
toArrayPreserveComponentType()4580         private Object[] toArrayPreserveComponentType() {
4581             return a.clone();
4582         }
4583 
4584         @Override
4585         @SuppressWarnings("unchecked")
toArray(T[] a)4586         public <T> T[] toArray(T[] a) {
4587             int size = size();
4588             if (a.length < size)
4589                 return Arrays.copyOf(this.a, size,
4590                                      (Class<? extends T[]>) a.getClass());
4591             System.arraycopy(this.a, 0, a, 0, size);
4592             if (a.length > size)
4593                 a[size] = null;
4594             return a;
4595         }
4596 
4597         @Override
get(int index)4598         public E get(int index) {
4599             return a[index];
4600         }
4601 
4602         @Override
set(int index, E element)4603         public E set(int index, E element) {
4604             E oldValue = a[index];
4605             a[index] = element;
4606             return oldValue;
4607         }
4608 
4609         @Override
indexOf(Object o)4610         public int indexOf(Object o) {
4611             E[] a = this.a;
4612             if (o == null) {
4613                 for (int i = 0; i < a.length; i++)
4614                     if (a[i] == null)
4615                         return i;
4616             } else {
4617                 for (int i = 0; i < a.length; i++)
4618                     if (o.equals(a[i]))
4619                         return i;
4620             }
4621             return -1;
4622         }
4623 
4624         @Override
contains(Object o)4625         public boolean contains(Object o) {
4626             return indexOf(o) >= 0;
4627         }
4628 
4629         @Override
spliterator()4630         public Spliterator<E> spliterator() {
4631             return Spliterators.spliterator(a, Spliterator.ORDERED);
4632         }
4633 
4634         @Override
forEach(Consumer<? super E> action)4635         public void forEach(Consumer<? super E> action) {
4636             Objects.requireNonNull(action);
4637             for (E e : a) {
4638                 action.accept(e);
4639             }
4640         }
4641 
4642         @Override
replaceAll(UnaryOperator<E> operator)4643         public void replaceAll(UnaryOperator<E> operator) {
4644             Objects.requireNonNull(operator);
4645             E[] a = this.a;
4646             for (int i = 0; i < a.length; i++) {
4647                 a[i] = operator.apply(a[i]);
4648             }
4649         }
4650 
4651         @Override
sort(Comparator<? super E> c)4652         public void sort(Comparator<? super E> c) {
4653             Arrays.sort(a, c);
4654         }
4655 
4656         @Override
iterator()4657         public Iterator<E> iterator() {
4658             return new ArrayItr<>(a);
4659         }
4660     }
4661 
4662     private static class ArrayItr<E> implements Iterator<E> {
4663         private int cursor;
4664         private final E[] a;
4665 
ArrayItr(E[] a)4666         ArrayItr(E[] a) {
4667             this.a = a;
4668         }
4669 
4670         @Override
hasNext()4671         public boolean hasNext() {
4672             return cursor < a.length;
4673         }
4674 
4675         @Override
next()4676         public E next() {
4677             int i = cursor;
4678             if (i >= a.length) {
4679                 throw new NoSuchElementException();
4680             }
4681             cursor = i + 1;
4682             return a[i];
4683         }
4684     }
4685 
4686     /**
4687      * Returns a hash code based on the contents of the specified array.
4688      * For any two {@code long} arrays {@code a} and {@code b}
4689      * such that {@code Arrays.equals(a, b)}, it is also the case that
4690      * {@code Arrays.hashCode(a) == Arrays.hashCode(b)}.
4691      *
4692      * <p>The value returned by this method is the same value that would be
4693      * obtained by invoking the {@link List#hashCode() hashCode}
4694      * method on a {@link List} containing a sequence of {@link Long}
4695      * instances representing the elements of {@code a} in the same order.
4696      * If {@code a} is {@code null}, this method returns 0.
4697      *
4698      * @param a the array whose hash value to compute
4699      * @return a content-based hash code for {@code a}
4700      * @since 1.5
4701      */
hashCode(long[] a)4702     public static int hashCode(long[] a) {
4703         if (a == null) {
4704             return 0;
4705         }
4706         int result = 1;
4707         for (long element : a) {
4708             int elementHash = (int)(element ^ (element >>> 32));
4709             result = 31 * result + elementHash;
4710         }
4711         return result;
4712     }
4713 
4714     /**
4715      * Returns a hash code based on the contents of the specified array.
4716      * For any two non-null {@code int} arrays {@code a} and {@code b}
4717      * such that {@code Arrays.equals(a, b)}, it is also the case that
4718      * {@code Arrays.hashCode(a) == Arrays.hashCode(b)}.
4719      *
4720      * <p>The value returned by this method is the same value that would be
4721      * obtained by invoking the {@link List#hashCode() hashCode}
4722      * method on a {@link List} containing a sequence of {@link Integer}
4723      * instances representing the elements of {@code a} in the same order.
4724      * If {@code a} is {@code null}, this method returns 0.
4725      *
4726      * @param a the array whose hash value to compute
4727      * @return a content-based hash code for {@code a}
4728      * @since 1.5
4729      */
hashCode(int[] a)4730     public static int hashCode(int[] a) {
4731         if (a == null) {
4732             return 0;
4733         }
4734         return switch (a.length) {
4735             case 0 -> 1;
4736             case 1 -> 31 + a[0];
4737             default -> ArraysSupport.vectorizedHashCode(a, 0, a.length, 1, ArraysSupport.T_INT);
4738         };
4739     }
4740 
4741     /**
4742      * Returns a hash code based on the contents of the specified array.
4743      * For any two {@code short} arrays {@code a} and {@code b}
4744      * such that {@code Arrays.equals(a, b)}, it is also the case that
4745      * {@code Arrays.hashCode(a) == Arrays.hashCode(b)}.
4746      *
4747      * <p>The value returned by this method is the same value that would be
4748      * obtained by invoking the {@link List#hashCode() hashCode}
4749      * method on a {@link List} containing a sequence of {@link Short}
4750      * instances representing the elements of {@code a} in the same order.
4751      * If {@code a} is {@code null}, this method returns 0.
4752      *
4753      * @param a the array whose hash value to compute
4754      * @return a content-based hash code for {@code a}
4755      * @since 1.5
4756      */
hashCode(short[] a)4757     public static int hashCode(short[] a) {
4758         if (a == null) {
4759             return 0;
4760         }
4761         return switch (a.length) {
4762             case 0 -> 1;
4763             case 1 -> 31 + (int)a[0];
4764             default -> ArraysSupport.vectorizedHashCode(a, 0, a.length, 1, ArraysSupport.T_SHORT);
4765         };
4766     }
4767 
4768     /**
4769      * Returns a hash code based on the contents of the specified array.
4770      * For any two {@code char} arrays {@code a} and {@code b}
4771      * such that {@code Arrays.equals(a, b)}, it is also the case that
4772      * {@code Arrays.hashCode(a) == Arrays.hashCode(b)}.
4773      *
4774      * <p>The value returned by this method is the same value that would be
4775      * obtained by invoking the {@link List#hashCode() hashCode}
4776      * method on a {@link List} containing a sequence of {@link Character}
4777      * instances representing the elements of {@code a} in the same order.
4778      * If {@code a} is {@code null}, this method returns 0.
4779      *
4780      * @param a the array whose hash value to compute
4781      * @return a content-based hash code for {@code a}
4782      * @since 1.5
4783      */
4784     public static int hashCode(char[] a) {
4785         if (a == null) {
4786             return 0;
4787         }
4788         return switch (a.length) {
4789             case 0 -> 1;
4790             case 1 -> 31 + (int)a[0];
4791             default -> ArraysSupport.vectorizedHashCode(a, 0, a.length, 1, ArraysSupport.T_CHAR);
4792         };
4793     }
4794 
4795     /**
4796      * Returns a hash code based on the contents of the specified array.
4797      * For any two {@code byte} arrays {@code a} and {@code b}
4798      * such that {@code Arrays.equals(a, b)}, it is also the case that
4799      * {@code Arrays.hashCode(a) == Arrays.hashCode(b)}.
4800      *
4801      * <p>The value returned by this method is the same value that would be
4802      * obtained by invoking the {@link List#hashCode() hashCode}
4803      * method on a {@link List} containing a sequence of {@link Byte}
4804      * instances representing the elements of {@code a} in the same order.
4805      * If {@code a} is {@code null}, this method returns 0.
4806      *
4807      * @param a the array whose hash value to compute
4808      * @return a content-based hash code for {@code a}
4809      * @since 1.5
4810      */
4811     public static int hashCode(byte[] a) {
4812         if (a == null) {
4813             return 0;
4814         }
4815         return switch (a.length) {
4816             case 0 -> 1;
4817             case 1 -> 31 + (int)a[0];
4818             default -> ArraysSupport.vectorizedHashCode(a, 0, a.length, 1, ArraysSupport.T_BYTE);
4819         };
4820     }
4821 
4822     /**
4823      * Returns a hash code based on the contents of the specified array.
4824      * For any two {@code boolean} arrays {@code a} and {@code b}
4825      * such that {@code Arrays.equals(a, b)}, it is also the case that
4826      * {@code Arrays.hashCode(a) == Arrays.hashCode(b)}.
4827      *
4828      * <p>The value returned by this method is the same value that would be
4829      * obtained by invoking the {@link List#hashCode() hashCode}
4830      * method on a {@link List} containing a sequence of {@link Boolean}
4831      * instances representing the elements of {@code a} in the same order.
4832      * If {@code a} is {@code null}, this method returns 0.
4833      *
4834      * @param a the array whose hash value to compute
4835      * @return a content-based hash code for {@code a}
4836      * @since 1.5
4837      */
4838     public static int hashCode(boolean[] a) {
4839         if (a == null)
4840             return 0;
4841 
4842         int result = 1;
4843         for (boolean element : a)
4844             result = 31 * result + (element ? 1231 : 1237);
4845 
4846         return result;
4847     }
4848 
4849     /**
4850      * Returns a hash code based on the contents of the specified array.
4851      * For any two {@code float} arrays {@code a} and {@code b}
4852      * such that {@code Arrays.equals(a, b)}, it is also the case that
4853      * {@code Arrays.hashCode(a) == Arrays.hashCode(b)}.
4854      *
4855      * <p>The value returned by this method is the same value that would be
4856      * obtained by invoking the {@link List#hashCode() hashCode}
4857      * method on a {@link List} containing a sequence of {@link Float}
4858      * instances representing the elements of {@code a} in the same order.
4859      * If {@code a} is {@code null}, this method returns 0.
4860      *
4861      * @param a the array whose hash value to compute
4862      * @return a content-based hash code for {@code a}
4863      * @since 1.5
4864      */
4865     public static int hashCode(float[] a) {
4866         if (a == null)
4867             return 0;
4868 
4869         int result = 1;
4870         for (float element : a)
4871             result = 31 * result + Float.floatToIntBits(element);
4872 
4873         return result;
4874     }
4875 
4876     /**
4877      * Returns a hash code based on the contents of the specified array.
4878      * For any two {@code double} arrays {@code a} and {@code b}
4879      * such that {@code Arrays.equals(a, b)}, it is also the case that
4880      * {@code Arrays.hashCode(a) == Arrays.hashCode(b)}.
4881      *
4882      * <p>The value returned by this method is the same value that would be
4883      * obtained by invoking the {@link List#hashCode() hashCode}
4884      * method on a {@link List} containing a sequence of {@link Double}
4885      * instances representing the elements of {@code a} in the same order.
4886      * If {@code a} is {@code null}, this method returns 0.
4887      *
4888      * @param a the array whose hash value to compute
4889      * @return a content-based hash code for {@code a}
4890      * @since 1.5
4891      */
4892     public static int hashCode(double[] a) {
4893         if (a == null)
4894             return 0;
4895 
4896         int result = 1;
4897         for (double element : a) {
4898             long bits = Double.doubleToLongBits(element);
4899             result = 31 * result + (int)(bits ^ (bits >>> 32));
4900         }
4901         return result;
4902     }
4903 
4904     /**
4905      * Returns a hash code based on the contents of the specified array.  If
4906      * the array contains other arrays as elements, the hash code is based on
4907      * their identities rather than their contents.  It is therefore
4908      * acceptable to invoke this method on an array that contains itself as an
4909      * element,  either directly or indirectly through one or more levels of
4910      * arrays.
4911      *
4912      * <p>For any two arrays {@code a} and {@code b} such that
4913      * {@code Arrays.equals(a, b)}, it is also the case that
4914      * {@code Arrays.hashCode(a) == Arrays.hashCode(b)}.
4915      *
4916      * <p>The value returned by this method is equal to the value that would
4917      * be returned by {@code Arrays.asList(a).hashCode()}, unless {@code a}
4918      * is {@code null}, in which case {@code 0} is returned.
4919      *
4920      * @param a the array whose content-based hash code to compute
4921      * @return a content-based hash code for {@code a}
4922      * @see #deepHashCode(Object[])
4923      * @since 1.5
4924      */
4925     public static int hashCode(Object[] a) {
4926         if (a == null)
4927             return 0;
4928 
4929         int result = 1;
4930 
4931         for (Object element : a)
4932             result = 31 * result + (element == null ? 0 : element.hashCode());
4933 
4934         return result;
4935     }
4936 
4937     /**
4938      * Returns a hash code based on the "deep contents" of the specified
4939      * array.  If the array contains other arrays as elements, the
4940      * hash code is based on their contents and so on, ad infinitum.
4941      * It is therefore unacceptable to invoke this method on an array that
4942      * contains itself as an element, either directly or indirectly through
4943      * one or more levels of arrays.  The behavior of such an invocation is
4944      * undefined.
4945      *
4946      * <p>For any two arrays {@code a} and {@code b} such that
4947      * {@code Arrays.deepEquals(a, b)}, it is also the case that
4948      * {@code Arrays.deepHashCode(a) == Arrays.deepHashCode(b)}.
4949      *
4950      * <p>The computation of the value returned by this method is similar to
4951      * that of the value returned by {@link List#hashCode()} on a list
4952      * containing the same elements as {@code a} in the same order, with one
4953      * difference: If an element {@code e} of {@code a} is itself an array,
4954      * its hash code is computed not by calling {@code e.hashCode()}, but as
4955      * by calling the appropriate overloading of {@code Arrays.hashCode(e)}
4956      * if {@code e} is an array of a primitive type, or as by calling
4957      * {@code Arrays.deepHashCode(e)} recursively if {@code e} is an array
4958      * of a reference type.  If {@code a} is {@code null}, this method
4959      * returns 0.
4960      *
4961      * @param a the array whose deep-content-based hash code to compute
4962      * @return a deep-content-based hash code for {@code a}
4963      * @see #hashCode(Object[])
4964      * @since 1.5
4965      */
4966     public static int deepHashCode(Object[] a) {
4967         if (a == null)
4968             return 0;
4969 
4970         int result = 1;
4971 
4972         for (Object element : a) {
4973             final int elementHash;
4974             final Class<?> cl;
4975             if (element == null)
4976                 elementHash = 0;
4977             else if ((cl = element.getClass().getComponentType()) == null)
4978                 elementHash = element.hashCode();
4979             else if (element instanceof Object[])
4980                 elementHash = deepHashCode((Object[]) element);
4981             else
4982                 elementHash = primitiveArrayHashCode(element, cl);
4983 
4984             result = 31 * result + elementHash;
4985         }
4986 
4987         return result;
4988     }
4989 
4990     private static int primitiveArrayHashCode(Object a, Class<?> cl) {
4991         return
4992             (cl == byte.class)    ? hashCode((byte[]) a)    :
4993             (cl == int.class)     ? hashCode((int[]) a)     :
4994             (cl == long.class)    ? hashCode((long[]) a)    :
4995             (cl == char.class)    ? hashCode((char[]) a)    :
4996             (cl == short.class)   ? hashCode((short[]) a)   :
4997             (cl == boolean.class) ? hashCode((boolean[]) a) :
4998             (cl == double.class)  ? hashCode((double[]) a)  :
4999             // If new primitive types are ever added, this method must be
5000             // expanded or we will fail here with ClassCastException.
5001             hashCode((float[]) a);
5002     }
5003 
5004     /**
5005      * Returns {@code true} if the two specified arrays are <i>deeply
5006      * equal</i> to one another.  Unlike the {@link #equals(Object[],Object[])}
5007      * method, this method is appropriate for use with nested arrays of
5008      * arbitrary depth.
5009      *
5010      * <p>Two array references are considered deeply equal if both
5011      * are {@code null}, or if they refer to arrays that contain the same
5012      * number of elements and all corresponding pairs of elements in the two
5013      * arrays are deeply equal.
5014      *
5015      * <p>Two possibly {@code null} elements {@code e1} and {@code e2} are
5016      * deeply equal if any of the following conditions hold:
5017      * <ul>
5018      *    <li> {@code e1} and {@code e2} are both arrays of object reference
5019      *         types, and {@code Arrays.deepEquals(e1, e2) would return true}
5020      *    <li> {@code e1} and {@code e2} are arrays of the same primitive
5021      *         type, and the appropriate overloading of
5022      *         {@code Arrays.equals(e1, e2)} would return true.
5023      *    <li> {@code e1 == e2}
5024      *    <li> {@code e1.equals(e2)} would return true.
5025      * </ul>
5026      * Note that this definition permits {@code null} elements at any depth.
5027      *
5028      * <p>If either of the specified arrays contain themselves as elements
5029      * either directly or indirectly through one or more levels of arrays,
5030      * the behavior of this method is undefined.
5031      *
5032      * @param a1 one array to be tested for equality
5033      * @param a2 the other array to be tested for equality
5034      * @return {@code true} if the two arrays are equal
5035      * @see #equals(Object[],Object[])
5036      * @see Objects#deepEquals(Object, Object)
5037      * @since 1.5
5038      */
5039     public static boolean deepEquals(Object[] a1, Object[] a2) {
5040         if (a1 == a2)
5041             return true;
5042         if (a1 == null || a2==null)
5043             return false;
5044         int length = a1.length;
5045         if (a2.length != length)
5046             return false;
5047 
5048         for (int i = 0; i < length; i++) {
5049             Object e1 = a1[i];
5050             Object e2 = a2[i];
5051 
5052             if (e1 == e2)
5053                 continue;
5054             if (e1 == null)
5055                 return false;
5056 
5057             // Figure out whether the two elements are equal
5058             boolean eq = deepEquals0(e1, e2);
5059 
5060             if (!eq)
5061                 return false;
5062         }
5063         return true;
5064     }
5065 
5066     static boolean deepEquals0(Object e1, Object e2) {
5067         assert e1 != null;
5068         boolean eq;
5069         if (e1 instanceof Object[] && e2 instanceof Object[])
5070             eq = deepEquals ((Object[]) e1, (Object[]) e2);
5071         else if (e1 instanceof byte[] && e2 instanceof byte[])
5072             eq = equals((byte[]) e1, (byte[]) e2);
5073         else if (e1 instanceof short[] && e2 instanceof short[])
5074             eq = equals((short[]) e1, (short[]) e2);
5075         else if (e1 instanceof int[] && e2 instanceof int[])
5076             eq = equals((int[]) e1, (int[]) e2);
5077         else if (e1 instanceof long[] && e2 instanceof long[])
5078             eq = equals((long[]) e1, (long[]) e2);
5079         else if (e1 instanceof char[] && e2 instanceof char[])
5080             eq = equals((char[]) e1, (char[]) e2);
5081         else if (e1 instanceof float[] && e2 instanceof float[])
5082             eq = equals((float[]) e1, (float[]) e2);
5083         else if (e1 instanceof double[] && e2 instanceof double[])
5084             eq = equals((double[]) e1, (double[]) e2);
5085         else if (e1 instanceof boolean[] && e2 instanceof boolean[])
5086             eq = equals((boolean[]) e1, (boolean[]) e2);
5087         else
5088             eq = e1.equals(e2);
5089         return eq;
5090     }
5091 
5092     /**
5093      * Returns a string representation of the contents of the specified array.
5094      * The string representation consists of a list of the array's elements,
5095      * enclosed in square brackets ({@code "[]"}).  Adjacent elements are
5096      * separated by the characters {@code ", "} (a comma followed by a
5097      * space).  Elements are converted to strings as by
5098      * {@code String.valueOf(long)}.  Returns {@code "null"} if {@code a}
5099      * is {@code null}.
5100      *
5101      * @param a the array whose string representation to return
5102      * @return a string representation of {@code a}
5103      * @since 1.5
5104      */
5105     public static String toString(long[] a) {
5106         if (a == null)
5107             return "null";
5108         int iMax = a.length - 1;
5109         if (iMax == -1)
5110             return "[]";
5111 
5112         StringBuilder b = new StringBuilder();
5113         b.append('[');
5114         for (int i = 0; ; i++) {
5115             b.append(a[i]);
5116             if (i == iMax)
5117                 return b.append(']').toString();
5118             b.append(", ");
5119         }
5120     }
5121 
5122     /**
5123      * Returns a string representation of the contents of the specified array.
5124      * The string representation consists of a list of the array's elements,
5125      * enclosed in square brackets ({@code "[]"}).  Adjacent elements are
5126      * separated by the characters {@code ", "} (a comma followed by a
5127      * space).  Elements are converted to strings as by
5128      * {@code String.valueOf(int)}.  Returns {@code "null"} if {@code a} is
5129      * {@code null}.
5130      *
5131      * @param a the array whose string representation to return
5132      * @return a string representation of {@code a}
5133      * @since 1.5
5134      */
5135     public static String toString(int[] a) {
5136         if (a == null)
5137             return "null";
5138         int iMax = a.length - 1;
5139         if (iMax == -1)
5140             return "[]";
5141 
5142         StringBuilder b = new StringBuilder();
5143         b.append('[');
5144         for (int i = 0; ; i++) {
5145             b.append(a[i]);
5146             if (i == iMax)
5147                 return b.append(']').toString();
5148             b.append(", ");
5149         }
5150     }
5151 
5152     /**
5153      * Returns a string representation of the contents of the specified array.
5154      * The string representation consists of a list of the array's elements,
5155      * enclosed in square brackets ({@code "[]"}).  Adjacent elements are
5156      * separated by the characters {@code ", "} (a comma followed by a
5157      * space).  Elements are converted to strings as by
5158      * {@code String.valueOf(short)}.  Returns {@code "null"} if {@code a}
5159      * is {@code null}.
5160      *
5161      * @param a the array whose string representation to return
5162      * @return a string representation of {@code a}
5163      * @since 1.5
5164      */
5165     public static String toString(short[] a) {
5166         if (a == null)
5167             return "null";
5168         int iMax = a.length - 1;
5169         if (iMax == -1)
5170             return "[]";
5171 
5172         StringBuilder b = new StringBuilder();
5173         b.append('[');
5174         for (int i = 0; ; i++) {
5175             b.append(a[i]);
5176             if (i == iMax)
5177                 return b.append(']').toString();
5178             b.append(", ");
5179         }
5180     }
5181 
5182     /**
5183      * Returns a string representation of the contents of the specified array.
5184      * The string representation consists of a list of the array's elements,
5185      * enclosed in square brackets ({@code "[]"}).  Adjacent elements are
5186      * separated by the characters {@code ", "} (a comma followed by a
5187      * space).  Elements are converted to strings as by
5188      * {@code String.valueOf(char)}.  Returns {@code "null"} if {@code a}
5189      * is {@code null}.
5190      *
5191      * @param a the array whose string representation to return
5192      * @return a string representation of {@code a}
5193      * @since 1.5
5194      */
5195     public static String toString(char[] a) {
5196         if (a == null)
5197             return "null";
5198         int iMax = a.length - 1;
5199         if (iMax == -1)
5200             return "[]";
5201 
5202         StringBuilder b = new StringBuilder();
5203         b.append('[');
5204         for (int i = 0; ; i++) {
5205             b.append(a[i]);
5206             if (i == iMax)
5207                 return b.append(']').toString();
5208             b.append(", ");
5209         }
5210     }
5211 
5212     /**
5213      * Returns a string representation of the contents of the specified array.
5214      * The string representation consists of a list of the array's elements,
5215      * enclosed in square brackets ({@code "[]"}).  Adjacent elements
5216      * are separated by the characters {@code ", "} (a comma followed
5217      * by a space).  Elements are converted to strings as by
5218      * {@code String.valueOf(byte)}.  Returns {@code "null"} if
5219      * {@code a} is {@code null}.
5220      *
5221      * @param a the array whose string representation to return
5222      * @return a string representation of {@code a}
5223      * @since 1.5
5224      */
5225     public static String toString(byte[] a) {
5226         if (a == null)
5227             return "null";
5228         int iMax = a.length - 1;
5229         if (iMax == -1)
5230             return "[]";
5231 
5232         StringBuilder b = new StringBuilder();
5233         b.append('[');
5234         for (int i = 0; ; i++) {
5235             b.append(a[i]);
5236             if (i == iMax)
5237                 return b.append(']').toString();
5238             b.append(", ");
5239         }
5240     }
5241 
5242     /**
5243      * Returns a string representation of the contents of the specified array.
5244      * The string representation consists of a list of the array's elements,
5245      * enclosed in square brackets ({@code "[]"}).  Adjacent elements are
5246      * separated by the characters {@code ", "} (a comma followed by a
5247      * space).  Elements are converted to strings as by
5248      * {@code String.valueOf(boolean)}.  Returns {@code "null"} if
5249      * {@code a} is {@code null}.
5250      *
5251      * @param a the array whose string representation to return
5252      * @return a string representation of {@code a}
5253      * @since 1.5
5254      */
5255     public static String toString(boolean[] a) {
5256         if (a == null)
5257             return "null";
5258         int iMax = a.length - 1;
5259         if (iMax == -1)
5260             return "[]";
5261 
5262         StringBuilder b = new StringBuilder();
5263         b.append('[');
5264         for (int i = 0; ; i++) {
5265             b.append(a[i]);
5266             if (i == iMax)
5267                 return b.append(']').toString();
5268             b.append(", ");
5269         }
5270     }
5271 
5272     /**
5273      * Returns a string representation of the contents of the specified array.
5274      * The string representation consists of a list of the array's elements,
5275      * enclosed in square brackets ({@code "[]"}).  Adjacent elements are
5276      * separated by the characters {@code ", "} (a comma followed by a
5277      * space).  Elements are converted to strings as by
5278      * {@code String.valueOf(float)}.  Returns {@code "null"} if {@code a}
5279      * is {@code null}.
5280      *
5281      * @param a the array whose string representation to return
5282      * @return a string representation of {@code a}
5283      * @since 1.5
5284      */
5285     public static String toString(float[] a) {
5286         if (a == null)
5287             return "null";
5288 
5289         int iMax = a.length - 1;
5290         if (iMax == -1)
5291             return "[]";
5292 
5293         StringBuilder b = new StringBuilder();
5294         b.append('[');
5295         for (int i = 0; ; i++) {
5296             b.append(a[i]);
5297             if (i == iMax)
5298                 return b.append(']').toString();
5299             b.append(", ");
5300         }
5301     }
5302 
5303     /**
5304      * Returns a string representation of the contents of the specified array.
5305      * The string representation consists of a list of the array's elements,
5306      * enclosed in square brackets ({@code "[]"}).  Adjacent elements are
5307      * separated by the characters {@code ", "} (a comma followed by a
5308      * space).  Elements are converted to strings as by
5309      * {@code String.valueOf(double)}.  Returns {@code "null"} if {@code a}
5310      * is {@code null}.
5311      *
5312      * @param a the array whose string representation to return
5313      * @return a string representation of {@code a}
5314      * @since 1.5
5315      */
5316     public static String toString(double[] a) {
5317         if (a == null)
5318             return "null";
5319         int iMax = a.length - 1;
5320         if (iMax == -1)
5321             return "[]";
5322 
5323         StringBuilder b = new StringBuilder();
5324         b.append('[');
5325         for (int i = 0; ; i++) {
5326             b.append(a[i]);
5327             if (i == iMax)
5328                 return b.append(']').toString();
5329             b.append(", ");
5330         }
5331     }
5332 
5333     /**
5334      * Returns a string representation of the contents of the specified array.
5335      * If the array contains other arrays as elements, they are converted to
5336      * strings by the {@link Object#toString} method inherited from
5337      * {@code Object}, which describes their <i>identities</i> rather than
5338      * their contents.
5339      *
5340      * <p>The value returned by this method is equal to the value that would
5341      * be returned by {@code Arrays.asList(a).toString()}, unless {@code a}
5342      * is {@code null}, in which case {@code "null"} is returned.
5343      *
5344      * @param a the array whose string representation to return
5345      * @return a string representation of {@code a}
5346      * @see #deepToString(Object[])
5347      * @since 1.5
5348      */
5349     public static String toString(Object[] a) {
5350         if (a == null)
5351             return "null";
5352 
5353         int iMax = a.length - 1;
5354         if (iMax == -1)
5355             return "[]";
5356 
5357         StringBuilder b = new StringBuilder();
5358         b.append('[');
5359         for (int i = 0; ; i++) {
5360             b.append(String.valueOf(a[i]));
5361             if (i == iMax)
5362                 return b.append(']').toString();
5363             b.append(", ");
5364         }
5365     }
5366 
5367     /**
5368      * Returns a string representation of the "deep contents" of the specified
5369      * array.  If the array contains other arrays as elements, the string
5370      * representation contains their contents and so on.  This method is
5371      * designed for converting multidimensional arrays to strings.
5372      *
5373      * <p>The string representation consists of a list of the array's
5374      * elements, enclosed in square brackets ({@code "[]"}).  Adjacent
5375      * elements are separated by the characters {@code ", "} (a comma
5376      * followed by a space).  Elements are converted to strings as by
5377      * {@code String.valueOf(Object)}, unless they are themselves
5378      * arrays.
5379      *
5380      * <p>If an element {@code e} is an array of a primitive type, it is
5381      * converted to a string as by invoking the appropriate overloading of
5382      * {@code Arrays.toString(e)}.  If an element {@code e} is an array of a
5383      * reference type, it is converted to a string as by invoking
5384      * this method recursively.
5385      *
5386      * <p>To avoid infinite recursion, if the specified array contains itself
5387      * as an element, or contains an indirect reference to itself through one
5388      * or more levels of arrays, the self-reference is converted to the string
5389      * {@code "[...]"}.  For example, an array containing only a reference
5390      * to itself would be rendered as {@code "[[...]]"}.
5391      *
5392      * <p>This method returns {@code "null"} if the specified array
5393      * is {@code null}.
5394      *
5395      * @param a the array whose string representation to return
5396      * @return a string representation of {@code a}
5397      * @see #toString(Object[])
5398      * @since 1.5
5399      */
5400     public static String deepToString(Object[] a) {
5401         if (a == null)
5402             return "null";
5403 
5404         int bufLen = 20 * a.length;
5405         if (a.length != 0 && bufLen <= 0)
5406             bufLen = Integer.MAX_VALUE;
5407         StringBuilder buf = new StringBuilder(bufLen);
5408         deepToString(a, buf, new HashSet<>());
5409         return buf.toString();
5410     }
5411 
5412     private static void deepToString(Object[] a, StringBuilder buf,
5413                                      Set<Object[]> dejaVu) {
5414         if (a == null) {
5415             buf.append("null");
5416             return;
5417         }
5418         int iMax = a.length - 1;
5419         if (iMax == -1) {
5420             buf.append("[]");
5421             return;
5422         }
5423 
5424         dejaVu.add(a);
5425         buf.append('[');
5426         for (int i = 0; ; i++) {
5427 
5428             Object element = a[i];
5429             if (element == null) {
5430                 buf.append("null");
5431             } else {
5432                 Class<?> eClass = element.getClass();
5433 
5434                 if (eClass.isArray()) {
5435                     if (eClass == byte[].class)
5436                         buf.append(toString((byte[]) element));
5437                     else if (eClass == short[].class)
5438                         buf.append(toString((short[]) element));
5439                     else if (eClass == int[].class)
5440                         buf.append(toString((int[]) element));
5441                     else if (eClass == long[].class)
5442                         buf.append(toString((long[]) element));
5443                     else if (eClass == char[].class)
5444                         buf.append(toString((char[]) element));
5445                     else if (eClass == float[].class)
5446                         buf.append(toString((float[]) element));
5447                     else if (eClass == double[].class)
5448                         buf.append(toString((double[]) element));
5449                     else if (eClass == boolean[].class)
5450                         buf.append(toString((boolean[]) element));
5451                     else { // element is an array of object references
5452                         if (dejaVu.contains(element))
5453                             buf.append("[...]");
5454                         else
5455                             deepToString((Object[])element, buf, dejaVu);
5456                     }
5457                 } else {  // element is non-null and not an array
5458                     buf.append(element.toString());
5459                 }
5460             }
5461             if (i == iMax)
5462                 break;
5463             buf.append(", ");
5464         }
5465         buf.append(']');
5466         dejaVu.remove(a);
5467     }
5468 
5469 
5470     /**
5471      * Set all elements of the specified array, using the provided
5472      * generator function to compute each element.
5473      *
5474      * <p>If the generator function throws an exception, it is relayed to
5475      * the caller and the array is left in an indeterminate state.
5476      *
5477      * @apiNote
5478      * Setting a subrange of an array, using a generator function to compute
5479      * each element, can be written as follows:
5480      * <pre>{@code
5481      * IntStream.range(startInclusive, endExclusive)
5482      *          .forEach(i -> array[i] = generator.apply(i));
5483      * }</pre>
5484      *
5485      * @param <T> type of elements of the array
5486      * @param array array to be initialized
5487      * @param generator a function accepting an index and producing the desired
5488      *        value for that position
5489      * @throws NullPointerException if the generator is null
5490      * @since 1.8
5491      */
5492     public static <T> void setAll(T[] array, IntFunction<? extends T> generator) {
5493         Objects.requireNonNull(generator);
5494         for (int i = 0; i < array.length; i++)
5495             array[i] = generator.apply(i);
5496     }
5497 
5498     /**
5499      * Set all elements of the specified array, in parallel, using the
5500      * provided generator function to compute each element.
5501      *
5502      * <p>If the generator function throws an exception, an unchecked exception
5503      * is thrown from {@code parallelSetAll} and the array is left in an
5504      * indeterminate state.
5505      *
5506      * @apiNote
5507      * Setting a subrange of an array, in parallel, using a generator function
5508      * to compute each element, can be written as follows:
5509      * <pre>{@code
5510      * IntStream.range(startInclusive, endExclusive)
5511      *          .parallel()
5512      *          .forEach(i -> array[i] = generator.apply(i));
5513      * }</pre>
5514      *
5515      * @param <T> type of elements of the array
5516      * @param array array to be initialized
5517      * @param generator a function accepting an index and producing the desired
5518      *        value for that position
5519      * @throws NullPointerException if the generator is null
5520      * @since 1.8
5521      */
5522     public static <T> void parallelSetAll(T[] array, IntFunction<? extends T> generator) {
5523         Objects.requireNonNull(generator);
5524         IntStream.range(0, array.length).parallel().forEach(i -> { array[i] = generator.apply(i); });
5525     }
5526 
5527     /**
5528      * Set all elements of the specified array, using the provided
5529      * generator function to compute each element.
5530      *
5531      * <p>If the generator function throws an exception, it is relayed to
5532      * the caller and the array is left in an indeterminate state.
5533      *
5534      * @apiNote
5535      * Setting a subrange of an array, using a generator function to compute
5536      * each element, can be written as follows:
5537      * <pre>{@code
5538      * IntStream.range(startInclusive, endExclusive)
5539      *          .forEach(i -> array[i] = generator.applyAsInt(i));
5540      * }</pre>
5541      *
5542      * @param array array to be initialized
5543      * @param generator a function accepting an index and producing the desired
5544      *        value for that position
5545      * @throws NullPointerException if the generator is null
5546      * @since 1.8
5547      */
5548     public static void setAll(int[] array, IntUnaryOperator generator) {
5549         Objects.requireNonNull(generator);
5550         for (int i = 0; i < array.length; i++)
5551             array[i] = generator.applyAsInt(i);
5552     }
5553 
5554     /**
5555      * Set all elements of the specified array, in parallel, using the
5556      * provided generator function to compute each element.
5557      *
5558      * <p>If the generator function throws an exception, an unchecked exception
5559      * is thrown from {@code parallelSetAll} and the array is left in an
5560      * indeterminate state.
5561      *
5562      * @apiNote
5563      * Setting a subrange of an array, in parallel, using a generator function
5564      * to compute each element, can be written as follows:
5565      * <pre>{@code
5566      * IntStream.range(startInclusive, endExclusive)
5567      *          .parallel()
5568      *          .forEach(i -> array[i] = generator.applyAsInt(i));
5569      * }</pre>
5570      *
5571      * @param array array to be initialized
5572      * @param generator a function accepting an index and producing the desired
5573      * value for that position
5574      * @throws NullPointerException if the generator is null
5575      * @since 1.8
5576      */
5577     public static void parallelSetAll(int[] array, IntUnaryOperator generator) {
5578         Objects.requireNonNull(generator);
5579         IntStream.range(0, array.length).parallel().forEach(i -> { array[i] = generator.applyAsInt(i); });
5580     }
5581 
5582     /**
5583      * Set all elements of the specified array, using the provided
5584      * generator function to compute each element.
5585      *
5586      * <p>If the generator function throws an exception, it is relayed to
5587      * the caller and the array is left in an indeterminate state.
5588      *
5589      * @apiNote
5590      * Setting a subrange of an array, using a generator function to compute
5591      * each element, can be written as follows:
5592      * <pre>{@code
5593      * IntStream.range(startInclusive, endExclusive)
5594      *          .forEach(i -> array[i] = generator.applyAsLong(i));
5595      * }</pre>
5596      *
5597      * @param array array to be initialized
5598      * @param generator a function accepting an index and producing the desired
5599      *        value for that position
5600      * @throws NullPointerException if the generator is null
5601      * @since 1.8
5602      */
5603     public static void setAll(long[] array, IntToLongFunction generator) {
5604         Objects.requireNonNull(generator);
5605         for (int i = 0; i < array.length; i++)
5606             array[i] = generator.applyAsLong(i);
5607     }
5608 
5609     /**
5610      * Set all elements of the specified array, in parallel, using the
5611      * provided generator function to compute each element.
5612      *
5613      * <p>If the generator function throws an exception, an unchecked exception
5614      * is thrown from {@code parallelSetAll} and the array is left in an
5615      * indeterminate state.
5616      *
5617      * @apiNote
5618      * Setting a subrange of an array, in parallel, using a generator function
5619      * to compute each element, can be written as follows:
5620      * <pre>{@code
5621      * IntStream.range(startInclusive, endExclusive)
5622      *          .parallel()
5623      *          .forEach(i -> array[i] = generator.applyAsLong(i));
5624      * }</pre>
5625      *
5626      * @param array array to be initialized
5627      * @param generator a function accepting an index and producing the desired
5628      *        value for that position
5629      * @throws NullPointerException if the generator is null
5630      * @since 1.8
5631      */
5632     public static void parallelSetAll(long[] array, IntToLongFunction generator) {
5633         Objects.requireNonNull(generator);
5634         IntStream.range(0, array.length).parallel().forEach(i -> { array[i] = generator.applyAsLong(i); });
5635     }
5636 
5637     /**
5638      * Set all elements of the specified array, using the provided
5639      * generator function to compute each element.
5640      *
5641      * <p>If the generator function throws an exception, it is relayed to
5642      * the caller and the array is left in an indeterminate state.
5643      *
5644      * @apiNote
5645      * Setting a subrange of an array, using a generator function to compute
5646      * each element, can be written as follows:
5647      * <pre>{@code
5648      * IntStream.range(startInclusive, endExclusive)
5649      *          .forEach(i -> array[i] = generator.applyAsDouble(i));
5650      * }</pre>
5651      *
5652      * @param array array to be initialized
5653      * @param generator a function accepting an index and producing the desired
5654      *        value for that position
5655      * @throws NullPointerException if the generator is null
5656      * @since 1.8
5657      */
5658     public static void setAll(double[] array, IntToDoubleFunction generator) {
5659         Objects.requireNonNull(generator);
5660         for (int i = 0; i < array.length; i++)
5661             array[i] = generator.applyAsDouble(i);
5662     }
5663 
5664     /**
5665      * Set all elements of the specified array, in parallel, using the
5666      * provided generator function to compute each element.
5667      *
5668      * <p>If the generator function throws an exception, an unchecked exception
5669      * is thrown from {@code parallelSetAll} and the array is left in an
5670      * indeterminate state.
5671      *
5672      * @apiNote
5673      * Setting a subrange of an array, in parallel, using a generator function
5674      * to compute each element, can be written as follows:
5675      * <pre>{@code
5676      * IntStream.range(startInclusive, endExclusive)
5677      *          .parallel()
5678      *          .forEach(i -> array[i] = generator.applyAsDouble(i));
5679      * }</pre>
5680      *
5681      * @param array array to be initialized
5682      * @param generator a function accepting an index and producing the desired
5683      *        value for that position
5684      * @throws NullPointerException if the generator is null
5685      * @since 1.8
5686      */
5687     public static void parallelSetAll(double[] array, IntToDoubleFunction generator) {
5688         Objects.requireNonNull(generator);
5689         IntStream.range(0, array.length).parallel().forEach(i -> { array[i] = generator.applyAsDouble(i); });
5690     }
5691 
5692     /**
5693      * Returns a {@link Spliterator} covering all of the specified array.
5694      *
5695      * <p>The spliterator reports {@link Spliterator#SIZED},
5696      * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
5697      * {@link Spliterator#IMMUTABLE}.
5698      *
5699      * @param <T> type of elements
5700      * @param array the array, assumed to be unmodified during use
5701      * @return a spliterator for the array elements
5702      * @since 1.8
5703      */
5704     public static <T> Spliterator<T> spliterator(T[] array) {
5705         return Spliterators.spliterator(array,
5706                                         Spliterator.ORDERED | Spliterator.IMMUTABLE);
5707     }
5708 
5709     /**
5710      * Returns a {@link Spliterator} covering the specified range of the
5711      * specified array.
5712      *
5713      * <p>The spliterator reports {@link Spliterator#SIZED},
5714      * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
5715      * {@link Spliterator#IMMUTABLE}.
5716      *
5717      * @param <T> type of elements
5718      * @param array the array, assumed to be unmodified during use
5719      * @param startInclusive the first index to cover, inclusive
5720      * @param endExclusive index immediately past the last index to cover
5721      * @return a spliterator for the array elements
5722      * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
5723      *         negative, {@code endExclusive} is less than
5724      *         {@code startInclusive}, or {@code endExclusive} is greater than
5725      *         the array size
5726      * @since 1.8
5727      */
5728     public static <T> Spliterator<T> spliterator(T[] array, int startInclusive, int endExclusive) {
5729         return Spliterators.spliterator(array, startInclusive, endExclusive,
5730                                         Spliterator.ORDERED | Spliterator.IMMUTABLE);
5731     }
5732 
5733     /**
5734      * Returns a {@link Spliterator.OfInt} covering all of the specified array.
5735      *
5736      * <p>The spliterator reports {@link Spliterator#SIZED},
5737      * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
5738      * {@link Spliterator#IMMUTABLE}.
5739      *
5740      * @param array the array, assumed to be unmodified during use
5741      * @return a spliterator for the array elements
5742      * @since 1.8
5743      */
5744     public static Spliterator.OfInt spliterator(int[] array) {
5745         return Spliterators.spliterator(array,
5746                                         Spliterator.ORDERED | Spliterator.IMMUTABLE);
5747     }
5748 
5749     /**
5750      * Returns a {@link Spliterator.OfInt} covering the specified range of the
5751      * specified array.
5752      *
5753      * <p>The spliterator reports {@link Spliterator#SIZED},
5754      * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
5755      * {@link Spliterator#IMMUTABLE}.
5756      *
5757      * @param array the array, assumed to be unmodified during use
5758      * @param startInclusive the first index to cover, inclusive
5759      * @param endExclusive index immediately past the last index to cover
5760      * @return a spliterator for the array elements
5761      * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
5762      *         negative, {@code endExclusive} is less than
5763      *         {@code startInclusive}, or {@code endExclusive} is greater than
5764      *         the array size
5765      * @since 1.8
5766      */
5767     public static Spliterator.OfInt spliterator(int[] array, int startInclusive, int endExclusive) {
5768         return Spliterators.spliterator(array, startInclusive, endExclusive,
5769                                         Spliterator.ORDERED | Spliterator.IMMUTABLE);
5770     }
5771 
5772     /**
5773      * Returns a {@link Spliterator.OfLong} covering all of the specified array.
5774      *
5775      * <p>The spliterator reports {@link Spliterator#SIZED},
5776      * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
5777      * {@link Spliterator#IMMUTABLE}.
5778      *
5779      * @param array the array, assumed to be unmodified during use
5780      * @return the spliterator for the array elements
5781      * @since 1.8
5782      */
5783     public static Spliterator.OfLong spliterator(long[] array) {
5784         return Spliterators.spliterator(array,
5785                                         Spliterator.ORDERED | Spliterator.IMMUTABLE);
5786     }
5787 
5788     /**
5789      * Returns a {@link Spliterator.OfLong} covering the specified range of the
5790      * specified array.
5791      *
5792      * <p>The spliterator reports {@link Spliterator#SIZED},
5793      * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
5794      * {@link Spliterator#IMMUTABLE}.
5795      *
5796      * @param array the array, assumed to be unmodified during use
5797      * @param startInclusive the first index to cover, inclusive
5798      * @param endExclusive index immediately past the last index to cover
5799      * @return a spliterator for the array elements
5800      * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
5801      *         negative, {@code endExclusive} is less than
5802      *         {@code startInclusive}, or {@code endExclusive} is greater than
5803      *         the array size
5804      * @since 1.8
5805      */
5806     public static Spliterator.OfLong spliterator(long[] array, int startInclusive, int endExclusive) {
5807         return Spliterators.spliterator(array, startInclusive, endExclusive,
5808                                         Spliterator.ORDERED | Spliterator.IMMUTABLE);
5809     }
5810 
5811     /**
5812      * Returns a {@link Spliterator.OfDouble} covering all of the specified
5813      * array.
5814      *
5815      * <p>The spliterator reports {@link Spliterator#SIZED},
5816      * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
5817      * {@link Spliterator#IMMUTABLE}.
5818      *
5819      * @param array the array, assumed to be unmodified during use
5820      * @return a spliterator for the array elements
5821      * @since 1.8
5822      */
5823     public static Spliterator.OfDouble spliterator(double[] array) {
5824         return Spliterators.spliterator(array,
5825                                         Spliterator.ORDERED | Spliterator.IMMUTABLE);
5826     }
5827 
5828     /**
5829      * Returns a {@link Spliterator.OfDouble} covering the specified range of
5830      * the specified array.
5831      *
5832      * <p>The spliterator reports {@link Spliterator#SIZED},
5833      * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
5834      * {@link Spliterator#IMMUTABLE}.
5835      *
5836      * @param array the array, assumed to be unmodified during use
5837      * @param startInclusive the first index to cover, inclusive
5838      * @param endExclusive index immediately past the last index to cover
5839      * @return a spliterator for the array elements
5840      * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
5841      *         negative, {@code endExclusive} is less than
5842      *         {@code startInclusive}, or {@code endExclusive} is greater than
5843      *         the array size
5844      * @since 1.8
5845      */
5846     public static Spliterator.OfDouble spliterator(double[] array, int startInclusive, int endExclusive) {
5847         return Spliterators.spliterator(array, startInclusive, endExclusive,
5848                                         Spliterator.ORDERED | Spliterator.IMMUTABLE);
5849     }
5850 
5851     /**
5852      * Returns a sequential {@link Stream} with the specified array as its
5853      * source.
5854      *
5855      * @param <T> The type of the array elements
5856      * @param array The array, assumed to be unmodified during use
5857      * @return a {@code Stream} for the array
5858      * @since 1.8
5859      */
5860     public static <T> Stream<T> stream(T[] array) {
5861         return stream(array, 0, array.length);
5862     }
5863 
5864     /**
5865      * Returns a sequential {@link Stream} with the specified range of the
5866      * specified array as its source.
5867      *
5868      * @param <T> the type of the array elements
5869      * @param array the array, assumed to be unmodified during use
5870      * @param startInclusive the first index to cover, inclusive
5871      * @param endExclusive index immediately past the last index to cover
5872      * @return a {@code Stream} for the array range
5873      * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
5874      *         negative, {@code endExclusive} is less than
5875      *         {@code startInclusive}, or {@code endExclusive} is greater than
5876      *         the array size
5877      * @since 1.8
5878      */
5879     public static <T> Stream<T> stream(T[] array, int startInclusive, int endExclusive) {
5880         return StreamSupport.stream(spliterator(array, startInclusive, endExclusive), false);
5881     }
5882 
5883     /**
5884      * Returns a sequential {@link IntStream} with the specified array as its
5885      * source.
5886      *
5887      * @param array the array, assumed to be unmodified during use
5888      * @return an {@code IntStream} for the array
5889      * @since 1.8
5890      */
5891     public static IntStream stream(int[] array) {
5892         return stream(array, 0, array.length);
5893     }
5894 
5895     /**
5896      * Returns a sequential {@link IntStream} with the specified range of the
5897      * specified array as its source.
5898      *
5899      * @param array the array, assumed to be unmodified during use
5900      * @param startInclusive the first index to cover, inclusive
5901      * @param endExclusive index immediately past the last index to cover
5902      * @return an {@code IntStream} for the array range
5903      * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
5904      *         negative, {@code endExclusive} is less than
5905      *         {@code startInclusive}, or {@code endExclusive} is greater than
5906      *         the array size
5907      * @since 1.8
5908      */
5909     public static IntStream stream(int[] array, int startInclusive, int endExclusive) {
5910         return StreamSupport.intStream(spliterator(array, startInclusive, endExclusive), false);
5911     }
5912 
5913     /**
5914      * Returns a sequential {@link LongStream} with the specified array as its
5915      * source.
5916      *
5917      * @param array the array, assumed to be unmodified during use
5918      * @return a {@code LongStream} for the array
5919      * @since 1.8
5920      */
5921     public static LongStream stream(long[] array) {
5922         return stream(array, 0, array.length);
5923     }
5924 
5925     /**
5926      * Returns a sequential {@link LongStream} with the specified range of the
5927      * specified array as its source.
5928      *
5929      * @param array the array, assumed to be unmodified during use
5930      * @param startInclusive the first index to cover, inclusive
5931      * @param endExclusive index immediately past the last index to cover
5932      * @return a {@code LongStream} for the array range
5933      * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
5934      *         negative, {@code endExclusive} is less than
5935      *         {@code startInclusive}, or {@code endExclusive} is greater than
5936      *         the array size
5937      * @since 1.8
5938      */
5939     public static LongStream stream(long[] array, int startInclusive, int endExclusive) {
5940         return StreamSupport.longStream(spliterator(array, startInclusive, endExclusive), false);
5941     }
5942 
5943     /**
5944      * Returns a sequential {@link DoubleStream} with the specified array as its
5945      * source.
5946      *
5947      * @param array the array, assumed to be unmodified during use
5948      * @return a {@code DoubleStream} for the array
5949      * @since 1.8
5950      */
5951     public static DoubleStream stream(double[] array) {
5952         return stream(array, 0, array.length);
5953     }
5954 
5955     /**
5956      * Returns a sequential {@link DoubleStream} with the specified range of the
5957      * specified array as its source.
5958      *
5959      * @param array the array, assumed to be unmodified during use
5960      * @param startInclusive the first index to cover, inclusive
5961      * @param endExclusive index immediately past the last index to cover
5962      * @return a {@code DoubleStream} for the array range
5963      * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
5964      *         negative, {@code endExclusive} is less than
5965      *         {@code startInclusive}, or {@code endExclusive} is greater than
5966      *         the array size
5967      * @since 1.8
5968      */
5969     public static DoubleStream stream(double[] array, int startInclusive, int endExclusive) {
5970         return StreamSupport.doubleStream(spliterator(array, startInclusive, endExclusive), false);
5971     }
5972 
5973 
5974     // Comparison methods
5975 
5976     // Compare boolean
5977 
5978     /**
5979      * Compares two {@code boolean} arrays lexicographically.
5980      *
5981      * <p>If the two arrays share a common prefix then the lexicographic
5982      * comparison is the result of comparing two elements, as if by
5983      * {@link Boolean#compare(boolean, boolean)}, at an index within the
5984      * respective arrays that is the prefix length.
5985      * Otherwise, one array is a proper prefix of the other and, lexicographic
5986      * comparison is the result of comparing the two array lengths.
5987      * (See {@link #mismatch(boolean[], boolean[])} for the definition of a
5988      * common and proper prefix.)
5989      *
5990      * <p>A {@code null} array reference is considered lexicographically less
5991      * than a non-{@code null} array reference.  Two {@code null} array
5992      * references are considered equal.
5993      *
5994      * <p>The comparison is consistent with {@link #equals(boolean[], boolean[]) equals},
5995      * more specifically the following holds for arrays {@code a} and {@code b}:
5996      * <pre>{@code
5997      *     Arrays.equals(a, b) == (Arrays.compare(a, b) == 0)
5998      * }</pre>
5999      *
6000      * @apiNote
6001      * <p>This method behaves as if (for non-{@code null} array references):
6002      * <pre>{@code
6003      *     int i = Arrays.mismatch(a, b);
6004      *     if (i >= 0 && i < Math.min(a.length, b.length))
6005      *         return Boolean.compare(a[i], b[i]);
6006      *     return a.length - b.length;
6007      * }</pre>
6008      *
6009      * @param a the first array to compare
6010      * @param b the second array to compare
6011      * @return the value {@code 0} if the first and second array are equal and
6012      *         contain the same elements in the same order;
6013      *         a value less than {@code 0} if the first array is
6014      *         lexicographically less than the second array; and
6015      *         a value greater than {@code 0} if the first array is
6016      *         lexicographically greater than the second array
6017      * @since 9
6018      */
6019     public static int compare(boolean[] a, boolean[] b) {
6020         if (a == b)
6021             return 0;
6022         if (a == null || b == null)
6023             return a == null ? -1 : 1;
6024 
6025         int i = ArraysSupport.mismatch(a, b,
6026                                        Math.min(a.length, b.length));
6027         if (i >= 0) {
6028             return Boolean.compare(a[i], b[i]);
6029         }
6030 
6031         return a.length - b.length;
6032     }
6033 
6034     /**
6035      * Compares two {@code boolean} arrays lexicographically over the specified
6036      * ranges.
6037      *
6038      * <p>If the two arrays, over the specified ranges, share a common prefix
6039      * then the lexicographic comparison is the result of comparing two
6040      * elements, as if by {@link Boolean#compare(boolean, boolean)}, at a
6041      * relative index within the respective arrays that is the length of the
6042      * prefix.
6043      * Otherwise, one array is a proper prefix of the other and, lexicographic
6044      * comparison is the result of comparing the two range lengths.
6045      * (See {@link #mismatch(boolean[], int, int, boolean[], int, int)} for the
6046      * definition of a common and proper prefix.)
6047      *
6048      * <p>The comparison is consistent with
6049      * {@link #equals(boolean[], int, int, boolean[], int, int) equals}, more
6050      * specifically the following holds for arrays {@code a} and {@code b} with
6051      * specified ranges [{@code aFromIndex}, {@code aToIndex}) and
6052      * [{@code bFromIndex}, {@code bToIndex}) respectively:
6053      * <pre>{@code
6054      *     Arrays.equals(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) ==
6055      *         (Arrays.compare(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) == 0)
6056      * }</pre>
6057      *
6058      * @apiNote
6059      * <p>This method behaves as if:
6060      * <pre>{@code
6061      *     int i = Arrays.mismatch(a, aFromIndex, aToIndex,
6062      *                             b, bFromIndex, bToIndex);
6063      *     if (i >= 0 && i < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
6064      *         return Boolean.compare(a[aFromIndex + i], b[bFromIndex + i]);
6065      *     return (aToIndex - aFromIndex) - (bToIndex - bFromIndex);
6066      * }</pre>
6067      *
6068      * @param a the first array to compare
6069      * @param aFromIndex the index (inclusive) of the first element in the
6070      *                   first array to be compared
6071      * @param aToIndex the index (exclusive) of the last element in the
6072      *                 first array to be compared
6073      * @param b the second array to compare
6074      * @param bFromIndex the index (inclusive) of the first element in the
6075      *                   second array to be compared
6076      * @param bToIndex the index (exclusive) of the last element in the
6077      *                 second array to be compared
6078      * @return the value {@code 0} if, over the specified ranges, the first and
6079      *         second array are equal and contain the same elements in the same
6080      *         order;
6081      *         a value less than {@code 0} if, over the specified ranges, the
6082      *         first array is lexicographically less than the second array; and
6083      *         a value greater than {@code 0} if, over the specified ranges, the
6084      *         first array is lexicographically greater than the second array
6085      * @throws IllegalArgumentException
6086      *         if {@code aFromIndex > aToIndex} or
6087      *         if {@code bFromIndex > bToIndex}
6088      * @throws ArrayIndexOutOfBoundsException
6089      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
6090      *         if {@code bFromIndex < 0 or bToIndex > b.length}
6091      * @throws NullPointerException
6092      *         if either array is {@code null}
6093      * @since 9
6094      */
6095     public static int compare(boolean[] a, int aFromIndex, int aToIndex,
6096                               boolean[] b, int bFromIndex, int bToIndex) {
6097         rangeCheck(a.length, aFromIndex, aToIndex);
6098         rangeCheck(b.length, bFromIndex, bToIndex);
6099 
6100         int aLength = aToIndex - aFromIndex;
6101         int bLength = bToIndex - bFromIndex;
6102         int i = ArraysSupport.mismatch(a, aFromIndex,
6103                                        b, bFromIndex,
6104                                        Math.min(aLength, bLength));
6105         if (i >= 0) {
6106             return Boolean.compare(a[aFromIndex + i], b[bFromIndex + i]);
6107         }
6108 
6109         return aLength - bLength;
6110     }
6111 
6112     // Compare byte
6113 
6114     /**
6115      * Compares two {@code byte} arrays lexicographically.
6116      *
6117      * <p>If the two arrays share a common prefix then the lexicographic
6118      * comparison is the result of comparing two elements, as if by
6119      * {@link Byte#compare(byte, byte)}, at an index within the respective
6120      * arrays that is the prefix length.
6121      * Otherwise, one array is a proper prefix of the other and, lexicographic
6122      * comparison is the result of comparing the two array lengths.
6123      * (See {@link #mismatch(byte[], byte[])} for the definition of a common and
6124      * proper prefix.)
6125      *
6126      * <p>A {@code null} array reference is considered lexicographically less
6127      * than a non-{@code null} array reference.  Two {@code null} array
6128      * references are considered equal.
6129      *
6130      * <p>The comparison is consistent with {@link #equals(byte[], byte[]) equals},
6131      * more specifically the following holds for arrays {@code a} and {@code b}:
6132      * <pre>{@code
6133      *     Arrays.equals(a, b) == (Arrays.compare(a, b) == 0)
6134      * }</pre>
6135      *
6136      * @apiNote
6137      * <p>This method behaves as if (for non-{@code null} array references):
6138      * <pre>{@code
6139      *     int i = Arrays.mismatch(a, b);
6140      *     if (i >= 0 && i < Math.min(a.length, b.length))
6141      *         return Byte.compare(a[i], b[i]);
6142      *     return a.length - b.length;
6143      * }</pre>
6144      *
6145      * @param a the first array to compare
6146      * @param b the second array to compare
6147      * @return the value {@code 0} if the first and second array are equal and
6148      *         contain the same elements in the same order;
6149      *         a value less than {@code 0} if the first array is
6150      *         lexicographically less than the second array; and
6151      *         a value greater than {@code 0} if the first array is
6152      *         lexicographically greater than the second array
6153      * @since 9
6154      */
6155     public static int compare(byte[] a, byte[] b) {
6156         if (a == b)
6157             return 0;
6158         if (a == null || b == null)
6159             return a == null ? -1 : 1;
6160 
6161         int i = ArraysSupport.mismatch(a, b,
6162                                        Math.min(a.length, b.length));
6163         if (i >= 0) {
6164             return Byte.compare(a[i], b[i]);
6165         }
6166 
6167         return a.length - b.length;
6168     }
6169 
6170     /**
6171      * Compares two {@code byte} arrays lexicographically over the specified
6172      * ranges.
6173      *
6174      * <p>If the two arrays, over the specified ranges, share a common prefix
6175      * then the lexicographic comparison is the result of comparing two
6176      * elements, as if by {@link Byte#compare(byte, byte)}, at a relative index
6177      * within the respective arrays that is the length of the prefix.
6178      * Otherwise, one array is a proper prefix of the other and, lexicographic
6179      * comparison is the result of comparing the two range lengths.
6180      * (See {@link #mismatch(byte[], int, int, byte[], int, int)} for the
6181      * definition of a common and proper prefix.)
6182      *
6183      * <p>The comparison is consistent with
6184      * {@link #equals(byte[], int, int, byte[], int, int) equals}, more
6185      * specifically the following holds for arrays {@code a} and {@code b} with
6186      * specified ranges [{@code aFromIndex}, {@code aToIndex}) and
6187      * [{@code bFromIndex}, {@code bToIndex}) respectively:
6188      * <pre>{@code
6189      *     Arrays.equals(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) ==
6190      *         (Arrays.compare(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) == 0)
6191      * }</pre>
6192      *
6193      * @apiNote
6194      * <p>This method behaves as if:
6195      * <pre>{@code
6196      *     int i = Arrays.mismatch(a, aFromIndex, aToIndex,
6197      *                             b, bFromIndex, bToIndex);
6198      *     if (i >= 0 && i < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
6199      *         return Byte.compare(a[aFromIndex + i], b[bFromIndex + i]);
6200      *     return (aToIndex - aFromIndex) - (bToIndex - bFromIndex);
6201      * }</pre>
6202      *
6203      * @param a the first array to compare
6204      * @param aFromIndex the index (inclusive) of the first element in the
6205      *                   first array to be compared
6206      * @param aToIndex the index (exclusive) of the last element in the
6207      *                 first array to be compared
6208      * @param b the second array to compare
6209      * @param bFromIndex the index (inclusive) of the first element in the
6210      *                   second array to be compared
6211      * @param bToIndex the index (exclusive) of the last element in the
6212      *                 second array to be compared
6213      * @return the value {@code 0} if, over the specified ranges, the first and
6214      *         second array are equal and contain the same elements in the same
6215      *         order;
6216      *         a value less than {@code 0} if, over the specified ranges, the
6217      *         first array is lexicographically less than the second array; and
6218      *         a value greater than {@code 0} if, over the specified ranges, the
6219      *         first array is lexicographically greater than the second array
6220      * @throws IllegalArgumentException
6221      *         if {@code aFromIndex > aToIndex} or
6222      *         if {@code bFromIndex > bToIndex}
6223      * @throws ArrayIndexOutOfBoundsException
6224      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
6225      *         if {@code bFromIndex < 0 or bToIndex > b.length}
6226      * @throws NullPointerException
6227      *         if either array is {@code null}
6228      * @since 9
6229      */
6230     public static int compare(byte[] a, int aFromIndex, int aToIndex,
6231                               byte[] b, int bFromIndex, int bToIndex) {
6232         rangeCheck(a.length, aFromIndex, aToIndex);
6233         rangeCheck(b.length, bFromIndex, bToIndex);
6234 
6235         int aLength = aToIndex - aFromIndex;
6236         int bLength = bToIndex - bFromIndex;
6237         int i = ArraysSupport.mismatch(a, aFromIndex,
6238                                        b, bFromIndex,
6239                                        Math.min(aLength, bLength));
6240         if (i >= 0) {
6241             return Byte.compare(a[aFromIndex + i], b[bFromIndex + i]);
6242         }
6243 
6244         return aLength - bLength;
6245     }
6246 
6247     /**
6248      * Compares two {@code byte} arrays lexicographically, numerically treating
6249      * elements as unsigned.
6250      *
6251      * <p>If the two arrays share a common prefix then the lexicographic
6252      * comparison is the result of comparing two elements, as if by
6253      * {@link Byte#compareUnsigned(byte, byte)}, at an index within the
6254      * respective arrays that is the prefix length.
6255      * Otherwise, one array is a proper prefix of the other and, lexicographic
6256      * comparison is the result of comparing the two array lengths.
6257      * (See {@link #mismatch(byte[], byte[])} for the definition of a common
6258      * and proper prefix.)
6259      *
6260      * <p>A {@code null} array reference is considered lexicographically less
6261      * than a non-{@code null} array reference.  Two {@code null} array
6262      * references are considered equal.
6263      *
6264      * @apiNote
6265      * <p>This method behaves as if (for non-{@code null} array references):
6266      * <pre>{@code
6267      *     int i = Arrays.mismatch(a, b);
6268      *     if (i >= 0 && i < Math.min(a.length, b.length))
6269      *         return Byte.compareUnsigned(a[i], b[i]);
6270      *     return a.length - b.length;
6271      * }</pre>
6272      *
6273      * @param a the first array to compare
6274      * @param b the second array to compare
6275      * @return the value {@code 0} if the first and second array are
6276      *         equal and contain the same elements in the same order;
6277      *         a value less than {@code 0} if the first array is
6278      *         lexicographically less than the second array; and
6279      *         a value greater than {@code 0} if the first array is
6280      *         lexicographically greater than the second array
6281      * @since 9
6282      */
6283     public static int compareUnsigned(byte[] a, byte[] b) {
6284         if (a == b)
6285             return 0;
6286         if (a == null || b == null)
6287             return a == null ? -1 : 1;
6288 
6289         int i = ArraysSupport.mismatch(a, b,
6290                                        Math.min(a.length, b.length));
6291         if (i >= 0) {
6292             return Byte.compareUnsigned(a[i], b[i]);
6293         }
6294 
6295         return a.length - b.length;
6296     }
6297 
6298 
6299     /**
6300      * Compares two {@code byte} arrays lexicographically over the specified
6301      * ranges, numerically treating elements as unsigned.
6302      *
6303      * <p>If the two arrays, over the specified ranges, share a common prefix
6304      * then the lexicographic comparison is the result of comparing two
6305      * elements, as if by {@link Byte#compareUnsigned(byte, byte)}, at a
6306      * relative index within the respective arrays that is the length of the
6307      * prefix.
6308      * Otherwise, one array is a proper prefix of the other and, lexicographic
6309      * comparison is the result of comparing the two range lengths.
6310      * (See {@link #mismatch(byte[], int, int, byte[], int, int)} for the
6311      * definition of a common and proper prefix.)
6312      *
6313      * @apiNote
6314      * <p>This method behaves as if:
6315      * <pre>{@code
6316      *     int i = Arrays.mismatch(a, aFromIndex, aToIndex,
6317      *                             b, bFromIndex, bToIndex);
6318      *     if (i >= 0 && i < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
6319      *         return Byte.compareUnsigned(a[aFromIndex + i], b[bFromIndex + i]);
6320      *     return (aToIndex - aFromIndex) - (bToIndex - bFromIndex);
6321      * }</pre>
6322      *
6323      * @param a the first array to compare
6324      * @param aFromIndex the index (inclusive) of the first element in the
6325      *                   first array to be compared
6326      * @param aToIndex the index (exclusive) of the last element in the
6327      *                 first array to be compared
6328      * @param b the second array to compare
6329      * @param bFromIndex the index (inclusive) of the first element in the
6330      *                   second array to be compared
6331      * @param bToIndex the index (exclusive) of the last element in the
6332      *                 second array to be compared
6333      * @return the value {@code 0} if, over the specified ranges, the first and
6334      *         second array are equal and contain the same elements in the same
6335      *         order;
6336      *         a value less than {@code 0} if, over the specified ranges, the
6337      *         first array is lexicographically less than the second array; and
6338      *         a value greater than {@code 0} if, over the specified ranges, the
6339      *         first array is lexicographically greater than the second array
6340      * @throws IllegalArgumentException
6341      *         if {@code aFromIndex > aToIndex} or
6342      *         if {@code bFromIndex > bToIndex}
6343      * @throws ArrayIndexOutOfBoundsException
6344      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
6345      *         if {@code bFromIndex < 0 or bToIndex > b.length}
6346      * @throws NullPointerException
6347      *         if either array is null
6348      * @since 9
6349      */
6350     public static int compareUnsigned(byte[] a, int aFromIndex, int aToIndex,
6351                                       byte[] b, int bFromIndex, int bToIndex) {
6352         rangeCheck(a.length, aFromIndex, aToIndex);
6353         rangeCheck(b.length, bFromIndex, bToIndex);
6354 
6355         int aLength = aToIndex - aFromIndex;
6356         int bLength = bToIndex - bFromIndex;
6357         int i = ArraysSupport.mismatch(a, aFromIndex,
6358                                        b, bFromIndex,
6359                                        Math.min(aLength, bLength));
6360         if (i >= 0) {
6361             return Byte.compareUnsigned(a[aFromIndex + i], b[bFromIndex + i]);
6362         }
6363 
6364         return aLength - bLength;
6365     }
6366 
6367     // Compare short
6368 
6369     /**
6370      * Compares two {@code short} arrays lexicographically.
6371      *
6372      * <p>If the two arrays share a common prefix then the lexicographic
6373      * comparison is the result of comparing two elements, as if by
6374      * {@link Short#compare(short, short)}, at an index within the respective
6375      * arrays that is the prefix length.
6376      * Otherwise, one array is a proper prefix of the other and, lexicographic
6377      * comparison is the result of comparing the two array lengths.
6378      * (See {@link #mismatch(short[], short[])} for the definition of a common
6379      * and proper prefix.)
6380      *
6381      * <p>A {@code null} array reference is considered lexicographically less
6382      * than a non-{@code null} array reference.  Two {@code null} array
6383      * references are considered equal.
6384      *
6385      * <p>The comparison is consistent with {@link #equals(short[], short[]) equals},
6386      * more specifically the following holds for arrays {@code a} and {@code b}:
6387      * <pre>{@code
6388      *     Arrays.equals(a, b) == (Arrays.compare(a, b) == 0)
6389      * }</pre>
6390      *
6391      * @apiNote
6392      * <p>This method behaves as if (for non-{@code null} array references):
6393      * <pre>{@code
6394      *     int i = Arrays.mismatch(a, b);
6395      *     if (i >= 0 && i < Math.min(a.length, b.length))
6396      *         return Short.compare(a[i], b[i]);
6397      *     return a.length - b.length;
6398      * }</pre>
6399      *
6400      * @param a the first array to compare
6401      * @param b the second array to compare
6402      * @return the value {@code 0} if the first and second array are equal and
6403      *         contain the same elements in the same order;
6404      *         a value less than {@code 0} if the first array is
6405      *         lexicographically less than the second array; and
6406      *         a value greater than {@code 0} if the first array is
6407      *         lexicographically greater than the second array
6408      * @since 9
6409      */
6410     public static int compare(short[] a, short[] b) {
6411         if (a == b)
6412             return 0;
6413         if (a == null || b == null)
6414             return a == null ? -1 : 1;
6415 
6416         int i = ArraysSupport.mismatch(a, b,
6417                                        Math.min(a.length, b.length));
6418         if (i >= 0) {
6419             return Short.compare(a[i], b[i]);
6420         }
6421 
6422         return a.length - b.length;
6423     }
6424 
6425     /**
6426      * Compares two {@code short} arrays lexicographically over the specified
6427      * ranges.
6428      *
6429      * <p>If the two arrays, over the specified ranges, share a common prefix
6430      * then the lexicographic comparison is the result of comparing two
6431      * elements, as if by {@link Short#compare(short, short)}, at a relative
6432      * index within the respective arrays that is the length of the prefix.
6433      * Otherwise, one array is a proper prefix of the other and, lexicographic
6434      * comparison is the result of comparing the two range lengths.
6435      * (See {@link #mismatch(short[], int, int, short[], int, int)} for the
6436      * definition of a common and proper prefix.)
6437      *
6438      * <p>The comparison is consistent with
6439      * {@link #equals(short[], int, int, short[], int, int) equals}, more
6440      * specifically the following holds for arrays {@code a} and {@code b} with
6441      * specified ranges [{@code aFromIndex}, {@code aToIndex}) and
6442      * [{@code bFromIndex}, {@code bToIndex}) respectively:
6443      * <pre>{@code
6444      *     Arrays.equals(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) ==
6445      *         (Arrays.compare(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) == 0)
6446      * }</pre>
6447      *
6448      * @apiNote
6449      * <p>This method behaves as if:
6450      * <pre>{@code
6451      *     int i = Arrays.mismatch(a, aFromIndex, aToIndex,
6452      *                             b, bFromIndex, bToIndex);
6453      *     if (i >= 0 && i < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
6454      *         return Short.compare(a[aFromIndex + i], b[bFromIndex + i]);
6455      *     return (aToIndex - aFromIndex) - (bToIndex - bFromIndex);
6456      * }</pre>
6457      *
6458      * @param a the first array to compare
6459      * @param aFromIndex the index (inclusive) of the first element in the
6460      *                   first array to be compared
6461      * @param aToIndex the index (exclusive) of the last element in the
6462      *                 first array to be compared
6463      * @param b the second array to compare
6464      * @param bFromIndex the index (inclusive) of the first element in the
6465      *                   second array to be compared
6466      * @param bToIndex the index (exclusive) of the last element in the
6467      *                 second array to be compared
6468      * @return the value {@code 0} if, over the specified ranges, the first and
6469      *         second array are equal and contain the same elements in the same
6470      *         order;
6471      *         a value less than {@code 0} if, over the specified ranges, the
6472      *         first array is lexicographically less than the second array; and
6473      *         a value greater than {@code 0} if, over the specified ranges, the
6474      *         first array is lexicographically greater than the second array
6475      * @throws IllegalArgumentException
6476      *         if {@code aFromIndex > aToIndex} or
6477      *         if {@code bFromIndex > bToIndex}
6478      * @throws ArrayIndexOutOfBoundsException
6479      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
6480      *         if {@code bFromIndex < 0 or bToIndex > b.length}
6481      * @throws NullPointerException
6482      *         if either array is {@code null}
6483      * @since 9
6484      */
6485     public static int compare(short[] a, int aFromIndex, int aToIndex,
6486                               short[] b, int bFromIndex, int bToIndex) {
6487         rangeCheck(a.length, aFromIndex, aToIndex);
6488         rangeCheck(b.length, bFromIndex, bToIndex);
6489 
6490         int aLength = aToIndex - aFromIndex;
6491         int bLength = bToIndex - bFromIndex;
6492         int i = ArraysSupport.mismatch(a, aFromIndex,
6493                                        b, bFromIndex,
6494                                        Math.min(aLength, bLength));
6495         if (i >= 0) {
6496             return Short.compare(a[aFromIndex + i], b[bFromIndex + i]);
6497         }
6498 
6499         return aLength - bLength;
6500     }
6501 
6502     /**
6503      * Compares two {@code short} arrays lexicographically, numerically treating
6504      * elements as unsigned.
6505      *
6506      * <p>If the two arrays share a common prefix then the lexicographic
6507      * comparison is the result of comparing two elements, as if by
6508      * {@link Short#compareUnsigned(short, short)}, at an index within the
6509      * respective arrays that is the prefix length.
6510      * Otherwise, one array is a proper prefix of the other and, lexicographic
6511      * comparison is the result of comparing the two array lengths.
6512      * (See {@link #mismatch(short[], short[])} for the definition of a common
6513      * and proper prefix.)
6514      *
6515      * <p>A {@code null} array reference is considered lexicographically less
6516      * than a non-{@code null} array reference.  Two {@code null} array
6517      * references are considered equal.
6518      *
6519      * @apiNote
6520      * <p>This method behaves as if (for non-{@code null} array references):
6521      * <pre>{@code
6522      *     int i = Arrays.mismatch(a, b);
6523      *     if (i >= 0 && i < Math.min(a.length, b.length))
6524      *         return Short.compareUnsigned(a[i], b[i]);
6525      *     return a.length - b.length;
6526      * }</pre>
6527      *
6528      * @param a the first array to compare
6529      * @param b the second array to compare
6530      * @return the value {@code 0} if the first and second array are
6531      *         equal and contain the same elements in the same order;
6532      *         a value less than {@code 0} if the first array is
6533      *         lexicographically less than the second array; and
6534      *         a value greater than {@code 0} if the first array is
6535      *         lexicographically greater than the second array
6536      * @since 9
6537      */
6538     public static int compareUnsigned(short[] a, short[] b) {
6539         if (a == b)
6540             return 0;
6541         if (a == null || b == null)
6542             return a == null ? -1 : 1;
6543 
6544         int i = ArraysSupport.mismatch(a, b,
6545                                        Math.min(a.length, b.length));
6546         if (i >= 0) {
6547             return Short.compareUnsigned(a[i], b[i]);
6548         }
6549 
6550         return a.length - b.length;
6551     }
6552 
6553     /**
6554      * Compares two {@code short} arrays lexicographically over the specified
6555      * ranges, numerically treating elements as unsigned.
6556      *
6557      * <p>If the two arrays, over the specified ranges, share a common prefix
6558      * then the lexicographic comparison is the result of comparing two
6559      * elements, as if by {@link Short#compareUnsigned(short, short)}, at a
6560      * relative index within the respective arrays that is the length of the
6561      * prefix.
6562      * Otherwise, one array is a proper prefix of the other and, lexicographic
6563      * comparison is the result of comparing the two range lengths.
6564      * (See {@link #mismatch(short[], int, int, short[], int, int)} for the
6565      * definition of a common and proper prefix.)
6566      *
6567      * @apiNote
6568      * <p>This method behaves as if:
6569      * <pre>{@code
6570      *     int i = Arrays.mismatch(a, aFromIndex, aToIndex,
6571      *                             b, bFromIndex, bToIndex);
6572      *     if (i >= 0 && i < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
6573      *         return Short.compareUnsigned(a[aFromIndex + i], b[bFromIndex + i]);
6574      *     return (aToIndex - aFromIndex) - (bToIndex - bFromIndex);
6575      * }</pre>
6576      *
6577      * @param a the first array to compare
6578      * @param aFromIndex the index (inclusive) of the first element in the
6579      *                   first array to be compared
6580      * @param aToIndex the index (exclusive) of the last element in the
6581      *                 first array to be compared
6582      * @param b the second array to compare
6583      * @param bFromIndex the index (inclusive) of the first element in the
6584      *                   second array to be compared
6585      * @param bToIndex the index (exclusive) of the last element in the
6586      *                 second array to be compared
6587      * @return the value {@code 0} if, over the specified ranges, the first and
6588      *         second array are equal and contain the same elements in the same
6589      *         order;
6590      *         a value less than {@code 0} if, over the specified ranges, the
6591      *         first array is lexicographically less than the second array; and
6592      *         a value greater than {@code 0} if, over the specified ranges, the
6593      *         first array is lexicographically greater than the second array
6594      * @throws IllegalArgumentException
6595      *         if {@code aFromIndex > aToIndex} or
6596      *         if {@code bFromIndex > bToIndex}
6597      * @throws ArrayIndexOutOfBoundsException
6598      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
6599      *         if {@code bFromIndex < 0 or bToIndex > b.length}
6600      * @throws NullPointerException
6601      *         if either array is null
6602      * @since 9
6603      */
6604     public static int compareUnsigned(short[] a, int aFromIndex, int aToIndex,
6605                                       short[] b, int bFromIndex, int bToIndex) {
6606         rangeCheck(a.length, aFromIndex, aToIndex);
6607         rangeCheck(b.length, bFromIndex, bToIndex);
6608 
6609         int aLength = aToIndex - aFromIndex;
6610         int bLength = bToIndex - bFromIndex;
6611         int i = ArraysSupport.mismatch(a, aFromIndex,
6612                                        b, bFromIndex,
6613                                        Math.min(aLength, bLength));
6614         if (i >= 0) {
6615             return Short.compareUnsigned(a[aFromIndex + i], b[bFromIndex + i]);
6616         }
6617 
6618         return aLength - bLength;
6619     }
6620 
6621     // Compare char
6622 
6623     /**
6624      * Compares two {@code char} arrays lexicographically.
6625      *
6626      * <p>If the two arrays share a common prefix then the lexicographic
6627      * comparison is the result of comparing two elements, as if by
6628      * {@link Character#compare(char, char)}, at an index within the respective
6629      * arrays that is the prefix length.
6630      * Otherwise, one array is a proper prefix of the other and, lexicographic
6631      * comparison is the result of comparing the two array lengths.
6632      * (See {@link #mismatch(char[], char[])} for the definition of a common and
6633      * proper prefix.)
6634      *
6635      * <p>A {@code null} array reference is considered lexicographically less
6636      * than a non-{@code null} array reference.  Two {@code null} array
6637      * references are considered equal.
6638      *
6639      * <p>The comparison is consistent with {@link #equals(char[], char[]) equals},
6640      * more specifically the following holds for arrays {@code a} and {@code b}:
6641      * <pre>{@code
6642      *     Arrays.equals(a, b) == (Arrays.compare(a, b) == 0)
6643      * }</pre>
6644      *
6645      * @apiNote
6646      * <p>This method behaves as if (for non-{@code null} array references):
6647      * <pre>{@code
6648      *     int i = Arrays.mismatch(a, b);
6649      *     if (i >= 0 && i < Math.min(a.length, b.length))
6650      *         return Character.compare(a[i], b[i]);
6651      *     return a.length - b.length;
6652      * }</pre>
6653      *
6654      * @param a the first array to compare
6655      * @param b the second array to compare
6656      * @return the value {@code 0} if the first and second array are equal and
6657      *         contain the same elements in the same order;
6658      *         a value less than {@code 0} if the first array is
6659      *         lexicographically less than the second array; and
6660      *         a value greater than {@code 0} if the first array is
6661      *         lexicographically greater than the second array
6662      * @since 9
6663      */
6664     public static int compare(char[] a, char[] b) {
6665         if (a == b)
6666             return 0;
6667         if (a == null || b == null)
6668             return a == null ? -1 : 1;
6669 
6670         int i = ArraysSupport.mismatch(a, b,
6671                                        Math.min(a.length, b.length));
6672         if (i >= 0) {
6673             return Character.compare(a[i], b[i]);
6674         }
6675 
6676         return a.length - b.length;
6677     }
6678 
6679     /**
6680      * Compares two {@code char} arrays lexicographically over the specified
6681      * ranges.
6682      *
6683      * <p>If the two arrays, over the specified ranges, share a common prefix
6684      * then the lexicographic comparison is the result of comparing two
6685      * elements, as if by {@link Character#compare(char, char)}, at a relative
6686      * index within the respective arrays that is the length of the prefix.
6687      * Otherwise, one array is a proper prefix of the other and, lexicographic
6688      * comparison is the result of comparing the two range lengths.
6689      * (See {@link #mismatch(char[], int, int, char[], int, int)} for the
6690      * definition of a common and proper prefix.)
6691      *
6692      * <p>The comparison is consistent with
6693      * {@link #equals(char[], int, int, char[], int, int) equals}, more
6694      * specifically the following holds for arrays {@code a} and {@code b} with
6695      * specified ranges [{@code aFromIndex}, {@code aToIndex}) and
6696      * [{@code bFromIndex}, {@code bToIndex}) respectively:
6697      * <pre>{@code
6698      *     Arrays.equals(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) ==
6699      *         (Arrays.compare(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) == 0)
6700      * }</pre>
6701      *
6702      * @apiNote
6703      * <p>This method behaves as if:
6704      * <pre>{@code
6705      *     int i = Arrays.mismatch(a, aFromIndex, aToIndex,
6706      *                             b, bFromIndex, bToIndex);
6707      *     if (i >= 0 && i < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
6708      *         return Character.compare(a[aFromIndex + i], b[bFromIndex + i]);
6709      *     return (aToIndex - aFromIndex) - (bToIndex - bFromIndex);
6710      * }</pre>
6711      *
6712      * @param a the first array to compare
6713      * @param aFromIndex the index (inclusive) of the first element in the
6714      *                   first array to be compared
6715      * @param aToIndex the index (exclusive) of the last element in the
6716      *                 first array to be compared
6717      * @param b the second array to compare
6718      * @param bFromIndex the index (inclusive) of the first element in the
6719      *                   second array to be compared
6720      * @param bToIndex the index (exclusive) of the last element in the
6721      *                 second array to be compared
6722      * @return the value {@code 0} if, over the specified ranges, the first and
6723      *         second array are equal and contain the same elements in the same
6724      *         order;
6725      *         a value less than {@code 0} if, over the specified ranges, the
6726      *         first array is lexicographically less than the second array; and
6727      *         a value greater than {@code 0} if, over the specified ranges, the
6728      *         first array is lexicographically greater than the second array
6729      * @throws IllegalArgumentException
6730      *         if {@code aFromIndex > aToIndex} or
6731      *         if {@code bFromIndex > bToIndex}
6732      * @throws ArrayIndexOutOfBoundsException
6733      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
6734      *         if {@code bFromIndex < 0 or bToIndex > b.length}
6735      * @throws NullPointerException
6736      *         if either array is {@code null}
6737      * @since 9
6738      */
6739     public static int compare(char[] a, int aFromIndex, int aToIndex,
6740                               char[] b, int bFromIndex, int bToIndex) {
6741         rangeCheck(a.length, aFromIndex, aToIndex);
6742         rangeCheck(b.length, bFromIndex, bToIndex);
6743 
6744         int aLength = aToIndex - aFromIndex;
6745         int bLength = bToIndex - bFromIndex;
6746         int i = ArraysSupport.mismatch(a, aFromIndex,
6747                                        b, bFromIndex,
6748                                        Math.min(aLength, bLength));
6749         if (i >= 0) {
6750             return Character.compare(a[aFromIndex + i], b[bFromIndex + i]);
6751         }
6752 
6753         return aLength - bLength;
6754     }
6755 
6756     // Compare int
6757 
6758     /**
6759      * Compares two {@code int} arrays lexicographically.
6760      *
6761      * <p>If the two arrays share a common prefix then the lexicographic
6762      * comparison is the result of comparing two elements, as if by
6763      * {@link Integer#compare(int, int)}, at an index within the respective
6764      * arrays that is the prefix length.
6765      * Otherwise, one array is a proper prefix of the other and, lexicographic
6766      * comparison is the result of comparing the two array lengths.
6767      * (See {@link #mismatch(int[], int[])} for the definition of a common and
6768      * proper prefix.)
6769      *
6770      * <p>A {@code null} array reference is considered lexicographically less
6771      * than a non-{@code null} array reference.  Two {@code null} array
6772      * references are considered equal.
6773      *
6774      * <p>The comparison is consistent with {@link #equals(int[], int[]) equals},
6775      * more specifically the following holds for arrays {@code a} and {@code b}:
6776      * <pre>{@code
6777      *     Arrays.equals(a, b) == (Arrays.compare(a, b) == 0)
6778      * }</pre>
6779      *
6780      * @apiNote
6781      * <p>This method behaves as if (for non-{@code null} array references):
6782      * <pre>{@code
6783      *     int i = Arrays.mismatch(a, b);
6784      *     if (i >= 0 && i < Math.min(a.length, b.length))
6785      *         return Integer.compare(a[i], b[i]);
6786      *     return a.length - b.length;
6787      * }</pre>
6788      *
6789      * @param a the first array to compare
6790      * @param b the second array to compare
6791      * @return the value {@code 0} if the first and second array are equal and
6792      *         contain the same elements in the same order;
6793      *         a value less than {@code 0} if the first array is
6794      *         lexicographically less than the second array; and
6795      *         a value greater than {@code 0} if the first array is
6796      *         lexicographically greater than the second array
6797      * @since 9
6798      */
6799     public static int compare(int[] a, int[] b) {
6800         if (a == b)
6801             return 0;
6802         if (a == null || b == null)
6803             return a == null ? -1 : 1;
6804 
6805         int i = ArraysSupport.mismatch(a, b,
6806                                        Math.min(a.length, b.length));
6807         if (i >= 0) {
6808             return Integer.compare(a[i], b[i]);
6809         }
6810 
6811         return a.length - b.length;
6812     }
6813 
6814     /**
6815      * Compares two {@code int} arrays lexicographically over the specified
6816      * ranges.
6817      *
6818      * <p>If the two arrays, over the specified ranges, share a common prefix
6819      * then the lexicographic comparison is the result of comparing two
6820      * elements, as if by {@link Integer#compare(int, int)}, at a relative index
6821      * within the respective arrays that is the length of the prefix.
6822      * Otherwise, one array is a proper prefix of the other and, lexicographic
6823      * comparison is the result of comparing the two range lengths.
6824      * (See {@link #mismatch(int[], int, int, int[], int, int)} for the
6825      * definition of a common and proper prefix.)
6826      *
6827      * <p>The comparison is consistent with
6828      * {@link #equals(int[], int, int, int[], int, int) equals}, more
6829      * specifically the following holds for arrays {@code a} and {@code b} with
6830      * specified ranges [{@code aFromIndex}, {@code aToIndex}) and
6831      * [{@code bFromIndex}, {@code bToIndex}) respectively:
6832      * <pre>{@code
6833      *     Arrays.equals(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) ==
6834      *         (Arrays.compare(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) == 0)
6835      * }</pre>
6836      *
6837      * @apiNote
6838      * <p>This method behaves as if:
6839      * <pre>{@code
6840      *     int i = Arrays.mismatch(a, aFromIndex, aToIndex,
6841      *                             b, bFromIndex, bToIndex);
6842      *     if (i >= 0 && i < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
6843      *         return Integer.compare(a[aFromIndex + i], b[bFromIndex + i]);
6844      *     return (aToIndex - aFromIndex) - (bToIndex - bFromIndex);
6845      * }</pre>
6846      *
6847      * @param a the first array to compare
6848      * @param aFromIndex the index (inclusive) of the first element in the
6849      *                   first array to be compared
6850      * @param aToIndex the index (exclusive) of the last element in the
6851      *                 first array to be compared
6852      * @param b the second array to compare
6853      * @param bFromIndex the index (inclusive) of the first element in the
6854      *                   second array to be compared
6855      * @param bToIndex the index (exclusive) of the last element in the
6856      *                 second array to be compared
6857      * @return the value {@code 0} if, over the specified ranges, the first and
6858      *         second array are equal and contain the same elements in the same
6859      *         order;
6860      *         a value less than {@code 0} if, over the specified ranges, the
6861      *         first array is lexicographically less than the second array; and
6862      *         a value greater than {@code 0} if, over the specified ranges, the
6863      *         first array is lexicographically greater than the second array
6864      * @throws IllegalArgumentException
6865      *         if {@code aFromIndex > aToIndex} or
6866      *         if {@code bFromIndex > bToIndex}
6867      * @throws ArrayIndexOutOfBoundsException
6868      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
6869      *         if {@code bFromIndex < 0 or bToIndex > b.length}
6870      * @throws NullPointerException
6871      *         if either array is {@code null}
6872      * @since 9
6873      */
6874     public static int compare(int[] a, int aFromIndex, int aToIndex,
6875                               int[] b, int bFromIndex, int bToIndex) {
6876         rangeCheck(a.length, aFromIndex, aToIndex);
6877         rangeCheck(b.length, bFromIndex, bToIndex);
6878 
6879         int aLength = aToIndex - aFromIndex;
6880         int bLength = bToIndex - bFromIndex;
6881         int i = ArraysSupport.mismatch(a, aFromIndex,
6882                                        b, bFromIndex,
6883                                        Math.min(aLength, bLength));
6884         if (i >= 0) {
6885             return Integer.compare(a[aFromIndex + i], b[bFromIndex + i]);
6886         }
6887 
6888         return aLength - bLength;
6889     }
6890 
6891     /**
6892      * Compares two {@code int} arrays lexicographically, numerically treating
6893      * elements as unsigned.
6894      *
6895      * <p>If the two arrays share a common prefix then the lexicographic
6896      * comparison is the result of comparing two elements, as if by
6897      * {@link Integer#compareUnsigned(int, int)}, at an index within the
6898      * respective arrays that is the prefix length.
6899      * Otherwise, one array is a proper prefix of the other and, lexicographic
6900      * comparison is the result of comparing the two array lengths.
6901      * (See {@link #mismatch(int[], int[])} for the definition of a common
6902      * and proper prefix.)
6903      *
6904      * <p>A {@code null} array reference is considered lexicographically less
6905      * than a non-{@code null} array reference.  Two {@code null} array
6906      * references are considered equal.
6907      *
6908      * @apiNote
6909      * <p>This method behaves as if (for non-{@code null} array references):
6910      * <pre>{@code
6911      *     int i = Arrays.mismatch(a, b);
6912      *     if (i >= 0 && i < Math.min(a.length, b.length))
6913      *         return Integer.compareUnsigned(a[i], b[i]);
6914      *     return a.length - b.length;
6915      * }</pre>
6916      *
6917      * @param a the first array to compare
6918      * @param b the second array to compare
6919      * @return the value {@code 0} if the first and second array are
6920      *         equal and contain the same elements in the same order;
6921      *         a value less than {@code 0} if the first array is
6922      *         lexicographically less than the second array; and
6923      *         a value greater than {@code 0} if the first array is
6924      *         lexicographically greater than the second array
6925      * @since 9
6926      */
6927     public static int compareUnsigned(int[] a, int[] b) {
6928         if (a == b)
6929             return 0;
6930         if (a == null || b == null)
6931             return a == null ? -1 : 1;
6932 
6933         int i = ArraysSupport.mismatch(a, b,
6934                                        Math.min(a.length, b.length));
6935         if (i >= 0) {
6936             return Integer.compareUnsigned(a[i], b[i]);
6937         }
6938 
6939         return a.length - b.length;
6940     }
6941 
6942     /**
6943      * Compares two {@code int} arrays lexicographically over the specified
6944      * ranges, numerically treating elements as unsigned.
6945      *
6946      * <p>If the two arrays, over the specified ranges, share a common prefix
6947      * then the lexicographic comparison is the result of comparing two
6948      * elements, as if by {@link Integer#compareUnsigned(int, int)}, at a
6949      * relative index within the respective arrays that is the length of the
6950      * prefix.
6951      * Otherwise, one array is a proper prefix of the other and, lexicographic
6952      * comparison is the result of comparing the two range lengths.
6953      * (See {@link #mismatch(int[], int, int, int[], int, int)} for the
6954      * definition of a common and proper prefix.)
6955      *
6956      * @apiNote
6957      * <p>This method behaves as if:
6958      * <pre>{@code
6959      *     int i = Arrays.mismatch(a, aFromIndex, aToIndex,
6960      *                             b, bFromIndex, bToIndex);
6961      *     if (i >= 0 && i < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
6962      *         return Integer.compareUnsigned(a[aFromIndex + i], b[bFromIndex + i]);
6963      *     return (aToIndex - aFromIndex) - (bToIndex - bFromIndex);
6964      * }</pre>
6965      *
6966      * @param a the first array to compare
6967      * @param aFromIndex the index (inclusive) of the first element in the
6968      *                   first array to be compared
6969      * @param aToIndex the index (exclusive) of the last element in the
6970      *                 first array to be compared
6971      * @param b the second array to compare
6972      * @param bFromIndex the index (inclusive) of the first element in the
6973      *                   second array to be compared
6974      * @param bToIndex the index (exclusive) of the last element in the
6975      *                 second array to be compared
6976      * @return the value {@code 0} if, over the specified ranges, the first and
6977      *         second array are equal and contain the same elements in the same
6978      *         order;
6979      *         a value less than {@code 0} if, over the specified ranges, the
6980      *         first array is lexicographically less than the second array; and
6981      *         a value greater than {@code 0} if, over the specified ranges, the
6982      *         first array is lexicographically greater than the second array
6983      * @throws IllegalArgumentException
6984      *         if {@code aFromIndex > aToIndex} or
6985      *         if {@code bFromIndex > bToIndex}
6986      * @throws ArrayIndexOutOfBoundsException
6987      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
6988      *         if {@code bFromIndex < 0 or bToIndex > b.length}
6989      * @throws NullPointerException
6990      *         if either array is null
6991      * @since 9
6992      */
6993     public static int compareUnsigned(int[] a, int aFromIndex, int aToIndex,
6994                                       int[] b, int bFromIndex, int bToIndex) {
6995         rangeCheck(a.length, aFromIndex, aToIndex);
6996         rangeCheck(b.length, bFromIndex, bToIndex);
6997 
6998         int aLength = aToIndex - aFromIndex;
6999         int bLength = bToIndex - bFromIndex;
7000         int i = ArraysSupport.mismatch(a, aFromIndex,
7001                                        b, bFromIndex,
7002                                        Math.min(aLength, bLength));
7003         if (i >= 0) {
7004             return Integer.compareUnsigned(a[aFromIndex + i], b[bFromIndex + i]);
7005         }
7006 
7007         return aLength - bLength;
7008     }
7009 
7010     // Compare long
7011 
7012     /**
7013      * Compares two {@code long} arrays lexicographically.
7014      *
7015      * <p>If the two arrays share a common prefix then the lexicographic
7016      * comparison is the result of comparing two elements, as if by
7017      * {@link Long#compare(long, long)}, at an index within the respective
7018      * arrays that is the prefix length.
7019      * Otherwise, one array is a proper prefix of the other and, lexicographic
7020      * comparison is the result of comparing the two array lengths.
7021      * (See {@link #mismatch(long[], long[])} for the definition of a common and
7022      * proper prefix.)
7023      *
7024      * <p>A {@code null} array reference is considered lexicographically less
7025      * than a non-{@code null} array reference.  Two {@code null} array
7026      * references are considered equal.
7027      *
7028      * <p>The comparison is consistent with {@link #equals(long[], long[]) equals},
7029      * more specifically the following holds for arrays {@code a} and {@code b}:
7030      * <pre>{@code
7031      *     Arrays.equals(a, b) == (Arrays.compare(a, b) == 0)
7032      * }</pre>
7033      *
7034      * @apiNote
7035      * <p>This method behaves as if (for non-{@code null} array references):
7036      * <pre>{@code
7037      *     int i = Arrays.mismatch(a, b);
7038      *     if (i >= 0 && i < Math.min(a.length, b.length))
7039      *         return Long.compare(a[i], b[i]);
7040      *     return a.length - b.length;
7041      * }</pre>
7042      *
7043      * @param a the first array to compare
7044      * @param b the second array to compare
7045      * @return the value {@code 0} if the first and second array are equal and
7046      *         contain the same elements in the same order;
7047      *         a value less than {@code 0} if the first array is
7048      *         lexicographically less than the second array; and
7049      *         a value greater than {@code 0} if the first array is
7050      *         lexicographically greater than the second array
7051      * @since 9
7052      */
7053     public static int compare(long[] a, long[] b) {
7054         if (a == b)
7055             return 0;
7056         if (a == null || b == null)
7057             return a == null ? -1 : 1;
7058 
7059         int i = ArraysSupport.mismatch(a, b,
7060                                        Math.min(a.length, b.length));
7061         if (i >= 0) {
7062             return Long.compare(a[i], b[i]);
7063         }
7064 
7065         return a.length - b.length;
7066     }
7067 
7068     /**
7069      * Compares two {@code long} arrays lexicographically over the specified
7070      * ranges.
7071      *
7072      * <p>If the two arrays, over the specified ranges, share a common prefix
7073      * then the lexicographic comparison is the result of comparing two
7074      * elements, as if by {@link Long#compare(long, long)}, at a relative index
7075      * within the respective arrays that is the length of the prefix.
7076      * Otherwise, one array is a proper prefix of the other and, lexicographic
7077      * comparison is the result of comparing the two range lengths.
7078      * (See {@link #mismatch(long[], int, int, long[], int, int)} for the
7079      * definition of a common and proper prefix.)
7080      *
7081      * <p>The comparison is consistent with
7082      * {@link #equals(long[], int, int, long[], int, int) equals}, more
7083      * specifically the following holds for arrays {@code a} and {@code b} with
7084      * specified ranges [{@code aFromIndex}, {@code aToIndex}) and
7085      * [{@code bFromIndex}, {@code bToIndex}) respectively:
7086      * <pre>{@code
7087      *     Arrays.equals(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) ==
7088      *         (Arrays.compare(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) == 0)
7089      * }</pre>
7090      *
7091      * @apiNote
7092      * <p>This method behaves as if:
7093      * <pre>{@code
7094      *     int i = Arrays.mismatch(a, aFromIndex, aToIndex,
7095      *                             b, bFromIndex, bToIndex);
7096      *     if (i >= 0 && i < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
7097      *         return Long.compare(a[aFromIndex + i], b[bFromIndex + i]);
7098      *     return (aToIndex - aFromIndex) - (bToIndex - bFromIndex);
7099      * }</pre>
7100      *
7101      * @param a the first array to compare
7102      * @param aFromIndex the index (inclusive) of the first element in the
7103      *                   first array to be compared
7104      * @param aToIndex the index (exclusive) of the last element in the
7105      *                 first array to be compared
7106      * @param b the second array to compare
7107      * @param bFromIndex the index (inclusive) of the first element in the
7108      *                   second array to be compared
7109      * @param bToIndex the index (exclusive) of the last element in the
7110      *                 second array to be compared
7111      * @return the value {@code 0} if, over the specified ranges, the first and
7112      *         second array are equal and contain the same elements in the same
7113      *         order;
7114      *         a value less than {@code 0} if, over the specified ranges, the
7115      *         first array is lexicographically less than the second array; and
7116      *         a value greater than {@code 0} if, over the specified ranges, the
7117      *         first array is lexicographically greater than the second array
7118      * @throws IllegalArgumentException
7119      *         if {@code aFromIndex > aToIndex} or
7120      *         if {@code bFromIndex > bToIndex}
7121      * @throws ArrayIndexOutOfBoundsException
7122      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
7123      *         if {@code bFromIndex < 0 or bToIndex > b.length}
7124      * @throws NullPointerException
7125      *         if either array is {@code null}
7126      * @since 9
7127      */
7128     public static int compare(long[] a, int aFromIndex, int aToIndex,
7129                               long[] b, int bFromIndex, int bToIndex) {
7130         rangeCheck(a.length, aFromIndex, aToIndex);
7131         rangeCheck(b.length, bFromIndex, bToIndex);
7132 
7133         int aLength = aToIndex - aFromIndex;
7134         int bLength = bToIndex - bFromIndex;
7135         int i = ArraysSupport.mismatch(a, aFromIndex,
7136                                        b, bFromIndex,
7137                                        Math.min(aLength, bLength));
7138         if (i >= 0) {
7139             return Long.compare(a[aFromIndex + i], b[bFromIndex + i]);
7140         }
7141 
7142         return aLength - bLength;
7143     }
7144 
7145     /**
7146      * Compares two {@code long} arrays lexicographically, numerically treating
7147      * elements as unsigned.
7148      *
7149      * <p>If the two arrays share a common prefix then the lexicographic
7150      * comparison is the result of comparing two elements, as if by
7151      * {@link Long#compareUnsigned(long, long)}, at an index within the
7152      * respective arrays that is the prefix length.
7153      * Otherwise, one array is a proper prefix of the other and, lexicographic
7154      * comparison is the result of comparing the two array lengths.
7155      * (See {@link #mismatch(long[], long[])} for the definition of a common
7156      * and proper prefix.)
7157      *
7158      * <p>A {@code null} array reference is considered lexicographically less
7159      * than a non-{@code null} array reference.  Two {@code null} array
7160      * references are considered equal.
7161      *
7162      * @apiNote
7163      * <p>This method behaves as if (for non-{@code null} array references):
7164      * <pre>{@code
7165      *     int i = Arrays.mismatch(a, b);
7166      *     if (i >= 0 && i < Math.min(a.length, b.length))
7167      *         return Long.compareUnsigned(a[i], b[i]);
7168      *     return a.length - b.length;
7169      * }</pre>
7170      *
7171      * @param a the first array to compare
7172      * @param b the second array to compare
7173      * @return the value {@code 0} if the first and second array are
7174      *         equal and contain the same elements in the same order;
7175      *         a value less than {@code 0} if the first array is
7176      *         lexicographically less than the second array; and
7177      *         a value greater than {@code 0} if the first array is
7178      *         lexicographically greater than the second array
7179      * @since 9
7180      */
7181     public static int compareUnsigned(long[] a, long[] b) {
7182         if (a == b)
7183             return 0;
7184         if (a == null || b == null)
7185             return a == null ? -1 : 1;
7186 
7187         int i = ArraysSupport.mismatch(a, b,
7188                                        Math.min(a.length, b.length));
7189         if (i >= 0) {
7190             return Long.compareUnsigned(a[i], b[i]);
7191         }
7192 
7193         return a.length - b.length;
7194     }
7195 
7196     /**
7197      * Compares two {@code long} arrays lexicographically over the specified
7198      * ranges, numerically treating elements as unsigned.
7199      *
7200      * <p>If the two arrays, over the specified ranges, share a common prefix
7201      * then the lexicographic comparison is the result of comparing two
7202      * elements, as if by {@link Long#compareUnsigned(long, long)}, at a
7203      * relative index within the respective arrays that is the length of the
7204      * prefix.
7205      * Otherwise, one array is a proper prefix of the other and, lexicographic
7206      * comparison is the result of comparing the two range lengths.
7207      * (See {@link #mismatch(long[], int, int, long[], int, int)} for the
7208      * definition of a common and proper prefix.)
7209      *
7210      * @apiNote
7211      * <p>This method behaves as if:
7212      * <pre>{@code
7213      *     int i = Arrays.mismatch(a, aFromIndex, aToIndex,
7214      *                             b, bFromIndex, bToIndex);
7215      *     if (i >= 0 && i < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
7216      *         return Long.compareUnsigned(a[aFromIndex + i], b[bFromIndex + i]);
7217      *     return (aToIndex - aFromIndex) - (bToIndex - bFromIndex);
7218      * }</pre>
7219      *
7220      * @param a the first array to compare
7221      * @param aFromIndex the index (inclusive) of the first element in the
7222      *                   first array to be compared
7223      * @param aToIndex the index (exclusive) of the last element in the
7224      *                 first array to be compared
7225      * @param b the second array to compare
7226      * @param bFromIndex the index (inclusive) of the first element in the
7227      *                   second array to be compared
7228      * @param bToIndex the index (exclusive) of the last element in the
7229      *                 second array to be compared
7230      * @return the value {@code 0} if, over the specified ranges, the first and
7231      *         second array are equal and contain the same elements in the same
7232      *         order;
7233      *         a value less than {@code 0} if, over the specified ranges, the
7234      *         first array is lexicographically less than the second array; and
7235      *         a value greater than {@code 0} if, over the specified ranges, the
7236      *         first array is lexicographically greater than the second array
7237      * @throws IllegalArgumentException
7238      *         if {@code aFromIndex > aToIndex} or
7239      *         if {@code bFromIndex > bToIndex}
7240      * @throws ArrayIndexOutOfBoundsException
7241      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
7242      *         if {@code bFromIndex < 0 or bToIndex > b.length}
7243      * @throws NullPointerException
7244      *         if either array is null
7245      * @since 9
7246      */
7247     public static int compareUnsigned(long[] a, int aFromIndex, int aToIndex,
7248                                       long[] b, int bFromIndex, int bToIndex) {
7249         rangeCheck(a.length, aFromIndex, aToIndex);
7250         rangeCheck(b.length, bFromIndex, bToIndex);
7251 
7252         int aLength = aToIndex - aFromIndex;
7253         int bLength = bToIndex - bFromIndex;
7254         int i = ArraysSupport.mismatch(a, aFromIndex,
7255                                        b, bFromIndex,
7256                                        Math.min(aLength, bLength));
7257         if (i >= 0) {
7258             return Long.compareUnsigned(a[aFromIndex + i], b[bFromIndex + i]);
7259         }
7260 
7261         return aLength - bLength;
7262     }
7263 
7264     // Compare float
7265 
7266     /**
7267      * Compares two {@code float} arrays lexicographically.
7268      *
7269      * <p>If the two arrays share a common prefix then the lexicographic
7270      * comparison is the result of comparing two elements, as if by
7271      * {@link Float#compare(float, float)}, at an index within the respective
7272      * arrays that is the prefix length.
7273      * Otherwise, one array is a proper prefix of the other and, lexicographic
7274      * comparison is the result of comparing the two array lengths.
7275      * (See {@link #mismatch(float[], float[])} for the definition of a common
7276      * and proper prefix.)
7277      *
7278      * <p>A {@code null} array reference is considered lexicographically less
7279      * than a non-{@code null} array reference.  Two {@code null} array
7280      * references are considered equal.
7281      *
7282      * <p>The comparison is consistent with {@link #equals(float[], float[]) equals},
7283      * more specifically the following holds for arrays {@code a} and {@code b}:
7284      * <pre>{@code
7285      *     Arrays.equals(a, b) == (Arrays.compare(a, b) == 0)
7286      * }</pre>
7287      *
7288      * @apiNote
7289      * <p>This method behaves as if (for non-{@code null} array references):
7290      * <pre>{@code
7291      *     int i = Arrays.mismatch(a, b);
7292      *     if (i >= 0 && i < Math.min(a.length, b.length))
7293      *         return Float.compare(a[i], b[i]);
7294      *     return a.length - b.length;
7295      * }</pre>
7296      *
7297      * @param a the first array to compare
7298      * @param b the second array to compare
7299      * @return the value {@code 0} if the first and second array are equal and
7300      *         contain the same elements in the same order;
7301      *         a value less than {@code 0} if the first array is
7302      *         lexicographically less than the second array; and
7303      *         a value greater than {@code 0} if the first array is
7304      *         lexicographically greater than the second array
7305      * @since 9
7306      */
7307     public static int compare(float[] a, float[] b) {
7308         if (a == b)
7309             return 0;
7310         if (a == null || b == null)
7311             return a == null ? -1 : 1;
7312 
7313         int i = ArraysSupport.mismatch(a, b,
7314                                        Math.min(a.length, b.length));
7315         if (i >= 0) {
7316             return Float.compare(a[i], b[i]);
7317         }
7318 
7319         return a.length - b.length;
7320     }
7321 
7322     /**
7323      * Compares two {@code float} arrays lexicographically over the specified
7324      * ranges.
7325      *
7326      * <p>If the two arrays, over the specified ranges, share a common prefix
7327      * then the lexicographic comparison is the result of comparing two
7328      * elements, as if by {@link Float#compare(float, float)}, at a relative
7329      * index within the respective arrays that is the length of the prefix.
7330      * Otherwise, one array is a proper prefix of the other and, lexicographic
7331      * comparison is the result of comparing the two range lengths.
7332      * (See {@link #mismatch(float[], int, int, float[], int, int)} for the
7333      * definition of a common and proper prefix.)
7334      *
7335      * <p>The comparison is consistent with
7336      * {@link #equals(float[], int, int, float[], int, int) equals}, more
7337      * specifically the following holds for arrays {@code a} and {@code b} with
7338      * specified ranges [{@code aFromIndex}, {@code aToIndex}) and
7339      * [{@code bFromIndex}, {@code bToIndex}) respectively:
7340      * <pre>{@code
7341      *     Arrays.equals(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) ==
7342      *         (Arrays.compare(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) == 0)
7343      * }</pre>
7344      *
7345      * @apiNote
7346      * <p>This method behaves as if:
7347      * <pre>{@code
7348      *     int i = Arrays.mismatch(a, aFromIndex, aToIndex,
7349      *                             b, bFromIndex, bToIndex);
7350      *     if (i >= 0 && i < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
7351      *         return Float.compare(a[aFromIndex + i], b[bFromIndex + i]);
7352      *     return (aToIndex - aFromIndex) - (bToIndex - bFromIndex);
7353      * }</pre>
7354      *
7355      * @param a the first array to compare
7356      * @param aFromIndex the index (inclusive) of the first element in the
7357      *                   first array to be compared
7358      * @param aToIndex the index (exclusive) of the last element in the
7359      *                 first array to be compared
7360      * @param b the second array to compare
7361      * @param bFromIndex the index (inclusive) of the first element in the
7362      *                   second array to be compared
7363      * @param bToIndex the index (exclusive) of the last element in the
7364      *                 second array to be compared
7365      * @return the value {@code 0} if, over the specified ranges, the first and
7366      *         second array are equal and contain the same elements in the same
7367      *         order;
7368      *         a value less than {@code 0} if, over the specified ranges, the
7369      *         first array is lexicographically less than the second array; and
7370      *         a value greater than {@code 0} if, over the specified ranges, the
7371      *         first array is lexicographically greater than the second array
7372      * @throws IllegalArgumentException
7373      *         if {@code aFromIndex > aToIndex} or
7374      *         if {@code bFromIndex > bToIndex}
7375      * @throws ArrayIndexOutOfBoundsException
7376      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
7377      *         if {@code bFromIndex < 0 or bToIndex > b.length}
7378      * @throws NullPointerException
7379      *         if either array is {@code null}
7380      * @since 9
7381      */
7382     public static int compare(float[] a, int aFromIndex, int aToIndex,
7383                               float[] b, int bFromIndex, int bToIndex) {
7384         rangeCheck(a.length, aFromIndex, aToIndex);
7385         rangeCheck(b.length, bFromIndex, bToIndex);
7386 
7387         int aLength = aToIndex - aFromIndex;
7388         int bLength = bToIndex - bFromIndex;
7389         int i = ArraysSupport.mismatch(a, aFromIndex,
7390                                        b, bFromIndex,
7391                                        Math.min(aLength, bLength));
7392         if (i >= 0) {
7393             return Float.compare(a[aFromIndex + i], b[bFromIndex + i]);
7394         }
7395 
7396         return aLength - bLength;
7397     }
7398 
7399     // Compare double
7400 
7401     /**
7402      * Compares two {@code double} arrays lexicographically.
7403      *
7404      * <p>If the two arrays share a common prefix then the lexicographic
7405      * comparison is the result of comparing two elements, as if by
7406      * {@link Double#compare(double, double)}, at an index within the respective
7407      * arrays that is the prefix length.
7408      * Otherwise, one array is a proper prefix of the other and, lexicographic
7409      * comparison is the result of comparing the two array lengths.
7410      * (See {@link #mismatch(double[], double[])} for the definition of a common
7411      * and proper prefix.)
7412      *
7413      * <p>A {@code null} array reference is considered lexicographically less
7414      * than a non-{@code null} array reference.  Two {@code null} array
7415      * references are considered equal.
7416      *
7417      * <p>The comparison is consistent with {@link #equals(double[], double[]) equals},
7418      * more specifically the following holds for arrays {@code a} and {@code b}:
7419      * <pre>{@code
7420      *     Arrays.equals(a, b) == (Arrays.compare(a, b) == 0)
7421      * }</pre>
7422      *
7423      * @apiNote
7424      * <p>This method behaves as if (for non-{@code null} array references):
7425      * <pre>{@code
7426      *     int i = Arrays.mismatch(a, b);
7427      *     if (i >= 0 && i < Math.min(a.length, b.length))
7428      *         return Double.compare(a[i], b[i]);
7429      *     return a.length - b.length;
7430      * }</pre>
7431      *
7432      * @param a the first array to compare
7433      * @param b the second array to compare
7434      * @return the value {@code 0} if the first and second array are equal and
7435      *         contain the same elements in the same order;
7436      *         a value less than {@code 0} if the first array is
7437      *         lexicographically less than the second array; and
7438      *         a value greater than {@code 0} if the first array is
7439      *         lexicographically greater than the second array
7440      * @since 9
7441      */
7442     public static int compare(double[] a, double[] b) {
7443         if (a == b)
7444             return 0;
7445         if (a == null || b == null)
7446             return a == null ? -1 : 1;
7447 
7448         int i = ArraysSupport.mismatch(a, b,
7449                                        Math.min(a.length, b.length));
7450         if (i >= 0) {
7451             return Double.compare(a[i], b[i]);
7452         }
7453 
7454         return a.length - b.length;
7455     }
7456 
7457     /**
7458      * Compares two {@code double} arrays lexicographically over the specified
7459      * ranges.
7460      *
7461      * <p>If the two arrays, over the specified ranges, share a common prefix
7462      * then the lexicographic comparison is the result of comparing two
7463      * elements, as if by {@link Double#compare(double, double)}, at a relative
7464      * index within the respective arrays that is the length of the prefix.
7465      * Otherwise, one array is a proper prefix of the other and, lexicographic
7466      * comparison is the result of comparing the two range lengths.
7467      * (See {@link #mismatch(double[], int, int, double[], int, int)} for the
7468      * definition of a common and proper prefix.)
7469      *
7470      * <p>The comparison is consistent with
7471      * {@link #equals(double[], int, int, double[], int, int) equals}, more
7472      * specifically the following holds for arrays {@code a} and {@code b} with
7473      * specified ranges [{@code aFromIndex}, {@code aToIndex}) and
7474      * [{@code bFromIndex}, {@code bToIndex}) respectively:
7475      * <pre>{@code
7476      *     Arrays.equals(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) ==
7477      *         (Arrays.compare(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) == 0)
7478      * }</pre>
7479      *
7480      * @apiNote
7481      * <p>This method behaves as if:
7482      * <pre>{@code
7483      *     int i = Arrays.mismatch(a, aFromIndex, aToIndex,
7484      *                             b, bFromIndex, bToIndex);
7485      *     if (i >= 0 && i < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
7486      *         return Double.compare(a[aFromIndex + i], b[bFromIndex + i]);
7487      *     return (aToIndex - aFromIndex) - (bToIndex - bFromIndex);
7488      * }</pre>
7489      *
7490      * @param a the first array to compare
7491      * @param aFromIndex the index (inclusive) of the first element in the
7492      *                   first array to be compared
7493      * @param aToIndex the index (exclusive) of the last element in the
7494      *                 first array to be compared
7495      * @param b the second array to compare
7496      * @param bFromIndex the index (inclusive) of the first element in the
7497      *                   second array to be compared
7498      * @param bToIndex the index (exclusive) of the last element in the
7499      *                 second array to be compared
7500      * @return the value {@code 0} if, over the specified ranges, the first and
7501      *         second array are equal and contain the same elements in the same
7502      *         order;
7503      *         a value less than {@code 0} if, over the specified ranges, the
7504      *         first array is lexicographically less than the second array; and
7505      *         a value greater than {@code 0} if, over the specified ranges, the
7506      *         first array is lexicographically greater than the second array
7507      * @throws IllegalArgumentException
7508      *         if {@code aFromIndex > aToIndex} or
7509      *         if {@code bFromIndex > bToIndex}
7510      * @throws ArrayIndexOutOfBoundsException
7511      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
7512      *         if {@code bFromIndex < 0 or bToIndex > b.length}
7513      * @throws NullPointerException
7514      *         if either array is {@code null}
7515      * @since 9
7516      */
7517     public static int compare(double[] a, int aFromIndex, int aToIndex,
7518                               double[] b, int bFromIndex, int bToIndex) {
7519         rangeCheck(a.length, aFromIndex, aToIndex);
7520         rangeCheck(b.length, bFromIndex, bToIndex);
7521 
7522         int aLength = aToIndex - aFromIndex;
7523         int bLength = bToIndex - bFromIndex;
7524         int i = ArraysSupport.mismatch(a, aFromIndex,
7525                                        b, bFromIndex,
7526                                        Math.min(aLength, bLength));
7527         if (i >= 0) {
7528             return Double.compare(a[aFromIndex + i], b[bFromIndex + i]);
7529         }
7530 
7531         return aLength - bLength;
7532     }
7533 
7534     // Compare objects
7535 
7536     /**
7537      * Compares two {@code Object} arrays, within comparable elements,
7538      * lexicographically.
7539      *
7540      * <p>If the two arrays share a common prefix then the lexicographic
7541      * comparison is the result of comparing two elements of type {@code T} at
7542      * an index {@code i} within the respective arrays that is the prefix
7543      * length, as if by:
7544      * <pre>{@code
7545      *     Comparator.nullsFirst(Comparator.<T>naturalOrder()).
7546      *         compare(a[i], b[i])
7547      * }</pre>
7548      * Otherwise, one array is a proper prefix of the other and, lexicographic
7549      * comparison is the result of comparing the two array lengths.
7550      * (See {@link #mismatch(Object[], Object[])} for the definition of a common
7551      * and proper prefix.)
7552      *
7553      * <p>A {@code null} array reference is considered lexicographically less
7554      * than a non-{@code null} array reference. Two {@code null} array
7555      * references are considered equal.
7556      * A {@code null} array element is considered lexicographically less than a
7557      * non-{@code null} array element. Two {@code null} array elements are
7558      * considered equal.
7559      *
7560      * <p>The comparison is consistent with {@link #equals(Object[], Object[]) equals},
7561      * more specifically the following holds for arrays {@code a} and {@code b}:
7562      * <pre>{@code
7563      *     Arrays.equals(a, b) == (Arrays.compare(a, b) == 0)
7564      * }</pre>
7565      *
7566      * @apiNote
7567      * <p>This method behaves as if (for non-{@code null} array references
7568      * and elements):
7569      * <pre>{@code
7570      *     int i = Arrays.mismatch(a, b);
7571      *     if (i >= 0 && i < Math.min(a.length, b.length))
7572      *         return a[i].compareTo(b[i]);
7573      *     return a.length - b.length;
7574      * }</pre>
7575      *
7576      * @param a the first array to compare
7577      * @param b the second array to compare
7578      * @param <T> the type of comparable array elements
7579      * @return the value {@code 0} if the first and second array are equal and
7580      *         contain the same elements in the same order;
7581      *         a value less than {@code 0} if the first array is
7582      *         lexicographically less than the second array; and
7583      *         a value greater than {@code 0} if the first array is
7584      *         lexicographically greater than the second array
7585      * @since 9
7586      */
7587     public static <T extends Comparable<? super T>> int compare(T[] a, T[] b) {
7588         if (a == b)
7589             return 0;
7590         // A null array is less than a non-null array
7591         if (a == null || b == null)
7592             return a == null ? -1 : 1;
7593 
7594         int length = Math.min(a.length, b.length);
7595         for (int i = 0; i < length; i++) {
7596             T oa = a[i];
7597             T ob = b[i];
7598             if (oa != ob) {
7599                 // A null element is less than a non-null element
7600                 if (oa == null || ob == null)
7601                     return oa == null ? -1 : 1;
7602                 int v = oa.compareTo(ob);
7603                 if (v != 0) {
7604                     return v;
7605                 }
7606             }
7607         }
7608 
7609         return a.length - b.length;
7610     }
7611 
7612     /**
7613      * Compares two {@code Object} arrays lexicographically over the specified
7614      * ranges.
7615      *
7616      * <p>If the two arrays, over the specified ranges, share a common prefix
7617      * then the lexicographic comparison is the result of comparing two
7618      * elements of type {@code T} at a relative index {@code i} within the
7619      * respective arrays that is the prefix length, as if by:
7620      * <pre>{@code
7621      *     Comparator.nullsFirst(Comparator.<T>naturalOrder()).
7622      *         compare(a[aFromIndex + i, b[bFromIndex + i])
7623      * }</pre>
7624      * Otherwise, one array is a proper prefix of the other and, lexicographic
7625      * comparison is the result of comparing the two range lengths.
7626      * (See {@link #mismatch(Object[], int, int, Object[], int, int)} for the
7627      * definition of a common and proper prefix.)
7628      *
7629      * <p>The comparison is consistent with
7630      * {@link #equals(Object[], int, int, Object[], int, int) equals}, more
7631      * specifically the following holds for arrays {@code a} and {@code b} with
7632      * specified ranges [{@code aFromIndex}, {@code aToIndex}) and
7633      * [{@code bFromIndex}, {@code bToIndex}) respectively:
7634      * <pre>{@code
7635      *     Arrays.equals(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) ==
7636      *         (Arrays.compare(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex) == 0)
7637      * }</pre>
7638      *
7639      * @apiNote
7640      * <p>This method behaves as if (for non-{@code null} array elements):
7641      * <pre>{@code
7642      *     int i = Arrays.mismatch(a, aFromIndex, aToIndex,
7643      *                             b, bFromIndex, bToIndex);
7644      *     if (i >= 0 && i < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
7645      *         return a[aFromIndex + i].compareTo(b[bFromIndex + i]);
7646      *     return (aToIndex - aFromIndex) - (bToIndex - bFromIndex);
7647      * }</pre>
7648      *
7649      * @param a the first array to compare
7650      * @param aFromIndex the index (inclusive) of the first element in the
7651      *                   first array to be compared
7652      * @param aToIndex the index (exclusive) of the last element in the
7653      *                 first array to be compared
7654      * @param b the second array to compare
7655      * @param bFromIndex the index (inclusive) of the first element in the
7656      *                   second array to be compared
7657      * @param bToIndex the index (exclusive) of the last element in the
7658      *                 second array to be compared
7659      * @param <T> the type of comparable array elements
7660      * @return the value {@code 0} if, over the specified ranges, the first and
7661      *         second array are equal and contain the same elements in the same
7662      *         order;
7663      *         a value less than {@code 0} if, over the specified ranges, the
7664      *         first array is lexicographically less than the second array; and
7665      *         a value greater than {@code 0} if, over the specified ranges, the
7666      *         first array is lexicographically greater than the second array
7667      * @throws IllegalArgumentException
7668      *         if {@code aFromIndex > aToIndex} or
7669      *         if {@code bFromIndex > bToIndex}
7670      * @throws ArrayIndexOutOfBoundsException
7671      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
7672      *         if {@code bFromIndex < 0 or bToIndex > b.length}
7673      * @throws NullPointerException
7674      *         if either array is {@code null}
7675      * @since 9
7676      */
7677     public static <T extends Comparable<? super T>> int compare(
7678             T[] a, int aFromIndex, int aToIndex,
7679             T[] b, int bFromIndex, int bToIndex) {
7680         rangeCheck(a.length, aFromIndex, aToIndex);
7681         rangeCheck(b.length, bFromIndex, bToIndex);
7682 
7683         int aLength = aToIndex - aFromIndex;
7684         int bLength = bToIndex - bFromIndex;
7685         int length = Math.min(aLength, bLength);
7686         for (int i = 0; i < length; i++) {
7687             T oa = a[aFromIndex++];
7688             T ob = b[bFromIndex++];
7689             if (oa != ob) {
7690                 if (oa == null || ob == null)
7691                     return oa == null ? -1 : 1;
7692                 int v = oa.compareTo(ob);
7693                 if (v != 0) {
7694                     return v;
7695                 }
7696             }
7697         }
7698 
7699         return aLength - bLength;
7700     }
7701 
7702     /**
7703      * Compares two {@code Object} arrays lexicographically using a specified
7704      * comparator.
7705      *
7706      * <p>If the two arrays share a common prefix then the lexicographic
7707      * comparison is the result of comparing with the specified comparator two
7708      * elements at an index within the respective arrays that is the prefix
7709      * length.
7710      * Otherwise, one array is a proper prefix of the other and, lexicographic
7711      * comparison is the result of comparing the two array lengths.
7712      * (See {@link #mismatch(Object[], Object[])} for the definition of a common
7713      * and proper prefix.)
7714      *
7715      * <p>A {@code null} array reference is considered lexicographically less
7716      * than a non-{@code null} array reference.  Two {@code null} array
7717      * references are considered equal.
7718      *
7719      * @apiNote
7720      * <p>This method behaves as if (for non-{@code null} array references):
7721      * <pre>{@code
7722      *     int i = Arrays.mismatch(a, b, cmp);
7723      *     if (i >= 0 && i < Math.min(a.length, b.length))
7724      *         return cmp.compare(a[i], b[i]);
7725      *     return a.length - b.length;
7726      * }</pre>
7727      *
7728      * @param a the first array to compare
7729      * @param b the second array to compare
7730      * @param cmp the comparator to compare array elements
7731      * @param <T> the type of array elements
7732      * @return the value {@code 0} if the first and second array are equal and
7733      *         contain the same elements in the same order;
7734      *         a value less than {@code 0} if the first array is
7735      *         lexicographically less than the second array; and
7736      *         a value greater than {@code 0} if the first array is
7737      *         lexicographically greater than the second array
7738      * @throws NullPointerException if the comparator is {@code null}
7739      * @since 9
7740      */
7741     public static <T> int compare(T[] a, T[] b,
7742                                   Comparator<? super T> cmp) {
7743         Objects.requireNonNull(cmp);
7744         if (a == b)
7745             return 0;
7746         if (a == null || b == null)
7747             return a == null ? -1 : 1;
7748 
7749         int length = Math.min(a.length, b.length);
7750         for (int i = 0; i < length; i++) {
7751             T oa = a[i];
7752             T ob = b[i];
7753             if (oa != ob) {
7754                 // Null-value comparison is deferred to the comparator
7755                 int v = cmp.compare(oa, ob);
7756                 if (v != 0) {
7757                     return v;
7758                 }
7759             }
7760         }
7761 
7762         return a.length - b.length;
7763     }
7764 
7765     /**
7766      * Compares two {@code Object} arrays lexicographically over the specified
7767      * ranges.
7768      *
7769      * <p>If the two arrays, over the specified ranges, share a common prefix
7770      * then the lexicographic comparison is the result of comparing with the
7771      * specified comparator two elements at a relative index within the
7772      * respective arrays that is the prefix length.
7773      * Otherwise, one array is a proper prefix of the other and, lexicographic
7774      * comparison is the result of comparing the two range lengths.
7775      * (See {@link #mismatch(Object[], int, int, Object[], int, int)} for the
7776      * definition of a common and proper prefix.)
7777      *
7778      * @apiNote
7779      * <p>This method behaves as if (for non-{@code null} array elements):
7780      * <pre>{@code
7781      *     int i = Arrays.mismatch(a, aFromIndex, aToIndex,
7782      *                             b, bFromIndex, bToIndex, cmp);
7783      *     if (i >= 0 && i < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
7784      *         return cmp.compare(a[aFromIndex + i], b[bFromIndex + i]);
7785      *     return (aToIndex - aFromIndex) - (bToIndex - bFromIndex);
7786      * }</pre>
7787      *
7788      * @param a the first array to compare
7789      * @param aFromIndex the index (inclusive) of the first element in the
7790      *                   first array to be compared
7791      * @param aToIndex the index (exclusive) of the last element in the
7792      *                 first array to be compared
7793      * @param b the second array to compare
7794      * @param bFromIndex the index (inclusive) of the first element in the
7795      *                   second array to be compared
7796      * @param bToIndex the index (exclusive) of the last element in the
7797      *                 second array to be compared
7798      * @param cmp the comparator to compare array elements
7799      * @param <T> the type of array elements
7800      * @return the value {@code 0} if, over the specified ranges, the first and
7801      *         second array are equal and contain the same elements in the same
7802      *         order;
7803      *         a value less than {@code 0} if, over the specified ranges, the
7804      *         first array is lexicographically less than the second array; and
7805      *         a value greater than {@code 0} if, over the specified ranges, the
7806      *         first array is lexicographically greater than the second array
7807      * @throws IllegalArgumentException
7808      *         if {@code aFromIndex > aToIndex} or
7809      *         if {@code bFromIndex > bToIndex}
7810      * @throws ArrayIndexOutOfBoundsException
7811      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
7812      *         if {@code bFromIndex < 0 or bToIndex > b.length}
7813      * @throws NullPointerException
7814      *         if either array or the comparator is {@code null}
7815      * @since 9
7816      */
7817     public static <T> int compare(
7818             T[] a, int aFromIndex, int aToIndex,
7819             T[] b, int bFromIndex, int bToIndex,
7820             Comparator<? super T> cmp) {
7821         Objects.requireNonNull(cmp);
7822         rangeCheck(a.length, aFromIndex, aToIndex);
7823         rangeCheck(b.length, bFromIndex, bToIndex);
7824 
7825         int aLength = aToIndex - aFromIndex;
7826         int bLength = bToIndex - bFromIndex;
7827         int length = Math.min(aLength, bLength);
7828         for (int i = 0; i < length; i++) {
7829             T oa = a[aFromIndex++];
7830             T ob = b[bFromIndex++];
7831             if (oa != ob) {
7832                 // Null-value comparison is deferred to the comparator
7833                 int v = cmp.compare(oa, ob);
7834                 if (v != 0) {
7835                     return v;
7836                 }
7837             }
7838         }
7839 
7840         return aLength - bLength;
7841     }
7842 
7843 
7844     // Mismatch methods
7845 
7846     // Mismatch boolean
7847 
7848     /**
7849      * Finds and returns the index of the first mismatch between two
7850      * {@code boolean} arrays, otherwise return -1 if no mismatch is found.  The
7851      * index will be in the range of 0 (inclusive) up to the length (inclusive)
7852      * of the smaller array.
7853      *
7854      * <p>If the two arrays share a common prefix then the returned index is the
7855      * length of the common prefix and it follows that there is a mismatch
7856      * between the two elements at that index within the respective arrays.
7857      * If one array is a proper prefix of the other then the returned index is
7858      * the length of the smaller array and it follows that the index is only
7859      * valid for the larger array.
7860      * Otherwise, there is no mismatch.
7861      *
7862      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a common
7863      * prefix of length {@code pl} if the following expression is true:
7864      * <pre>{@code
7865      *     pl >= 0 &&
7866      *     pl < Math.min(a.length, b.length) &&
7867      *     Arrays.equals(a, 0, pl, b, 0, pl) &&
7868      *     a[pl] != b[pl]
7869      * }</pre>
7870      * Note that a common prefix length of {@code 0} indicates that the first
7871      * elements from each array mismatch.
7872      *
7873      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a proper
7874      * prefix if the following expression is true:
7875      * <pre>{@code
7876      *     a.length != b.length &&
7877      *     Arrays.equals(a, 0, Math.min(a.length, b.length),
7878      *                   b, 0, Math.min(a.length, b.length))
7879      * }</pre>
7880      *
7881      * @param a the first array to be tested for a mismatch
7882      * @param b the second array to be tested for a mismatch
7883      * @return the index of the first mismatch between the two arrays,
7884      *         otherwise {@code -1}.
7885      * @throws NullPointerException
7886      *         if either array is {@code null}
7887      * @since 9
7888      */
7889     public static int mismatch(boolean[] a, boolean[] b) {
7890         int length = Math.min(a.length, b.length); // Check null array refs
7891         if (a == b)
7892             return -1;
7893 
7894         int i = ArraysSupport.mismatch(a, b, length);
7895         return (i < 0 && a.length != b.length) ? length : i;
7896     }
7897 
7898     /**
7899      * Finds and returns the relative index of the first mismatch between two
7900      * {@code boolean} arrays over the specified ranges, otherwise return -1 if
7901      * no mismatch is found.  The index will be in the range of 0 (inclusive) up
7902      * to the length (inclusive) of the smaller range.
7903      *
7904      * <p>If the two arrays, over the specified ranges, share a common prefix
7905      * then the returned relative index is the length of the common prefix and
7906      * it follows that there is a mismatch between the two elements at that
7907      * relative index within the respective arrays.
7908      * If one array is a proper prefix of the other, over the specified ranges,
7909      * then the returned relative index is the length of the smaller range and
7910      * it follows that the relative index is only valid for the array with the
7911      * larger range.
7912      * Otherwise, there is no mismatch.
7913      *
7914      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
7915      * ranges [{@code aFromIndex}, {@code aToIndex}) and
7916      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a common
7917      * prefix of length {@code pl} if the following expression is true:
7918      * <pre>{@code
7919      *     pl >= 0 &&
7920      *     pl < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex) &&
7921      *     Arrays.equals(a, aFromIndex, aFromIndex + pl, b, bFromIndex, bFromIndex + pl) &&
7922      *     a[aFromIndex + pl] != b[bFromIndex + pl]
7923      * }</pre>
7924      * Note that a common prefix length of {@code 0} indicates that the first
7925      * elements from each array mismatch.
7926      *
7927      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
7928      * ranges [{@code aFromIndex}, {@code aToIndex}) and
7929      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a proper
7930      * prefix if the following expression is true:
7931      * <pre>{@code
7932      *     (aToIndex - aFromIndex) != (bToIndex - bFromIndex) &&
7933      *     Arrays.equals(a, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex),
7934      *                   b, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
7935      * }</pre>
7936      *
7937      * @param a the first array to be tested for a mismatch
7938      * @param aFromIndex the index (inclusive) of the first element in the
7939      *                   first array to be tested
7940      * @param aToIndex the index (exclusive) of the last element in the
7941      *                 first array to be tested
7942      * @param b the second array to be tested for a mismatch
7943      * @param bFromIndex the index (inclusive) of the first element in the
7944      *                   second array to be tested
7945      * @param bToIndex the index (exclusive) of the last element in the
7946      *                 second array to be tested
7947      * @return the relative index of the first mismatch between the two arrays
7948      *         over the specified ranges, otherwise {@code -1}.
7949      * @throws IllegalArgumentException
7950      *         if {@code aFromIndex > aToIndex} or
7951      *         if {@code bFromIndex > bToIndex}
7952      * @throws ArrayIndexOutOfBoundsException
7953      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
7954      *         if {@code bFromIndex < 0 or bToIndex > b.length}
7955      * @throws NullPointerException
7956      *         if either array is {@code null}
7957      * @since 9
7958      */
7959     public static int mismatch(boolean[] a, int aFromIndex, int aToIndex,
7960                                boolean[] b, int bFromIndex, int bToIndex) {
7961         rangeCheck(a.length, aFromIndex, aToIndex);
7962         rangeCheck(b.length, bFromIndex, bToIndex);
7963 
7964         int aLength = aToIndex - aFromIndex;
7965         int bLength = bToIndex - bFromIndex;
7966         int length = Math.min(aLength, bLength);
7967         int i = ArraysSupport.mismatch(a, aFromIndex,
7968                                        b, bFromIndex,
7969                                        length);
7970         return (i < 0 && aLength != bLength) ? length : i;
7971     }
7972 
7973     // Mismatch byte
7974 
7975     /**
7976      * Finds and returns the index of the first mismatch between two {@code byte}
7977      * arrays, otherwise return -1 if no mismatch is found.  The index will be
7978      * in the range of 0 (inclusive) up to the length (inclusive) of the smaller
7979      * array.
7980      *
7981      * <p>If the two arrays share a common prefix then the returned index is the
7982      * length of the common prefix and it follows that there is a mismatch
7983      * between the two elements at that index within the respective arrays.
7984      * If one array is a proper prefix of the other then the returned index is
7985      * the length of the smaller array and it follows that the index is only
7986      * valid for the larger array.
7987      * Otherwise, there is no mismatch.
7988      *
7989      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a common
7990      * prefix of length {@code pl} if the following expression is true:
7991      * <pre>{@code
7992      *     pl >= 0 &&
7993      *     pl < Math.min(a.length, b.length) &&
7994      *     Arrays.equals(a, 0, pl, b, 0, pl) &&
7995      *     a[pl] != b[pl]
7996      * }</pre>
7997      * Note that a common prefix length of {@code 0} indicates that the first
7998      * elements from each array mismatch.
7999      *
8000      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a proper
8001      * prefix if the following expression is true:
8002      * <pre>{@code
8003      *     a.length != b.length &&
8004      *     Arrays.equals(a, 0, Math.min(a.length, b.length),
8005      *                   b, 0, Math.min(a.length, b.length))
8006      * }</pre>
8007      *
8008      * @param a the first array to be tested for a mismatch
8009      * @param b the second array to be tested for a mismatch
8010      * @return the index of the first mismatch between the two arrays,
8011      *         otherwise {@code -1}.
8012      * @throws NullPointerException
8013      *         if either array is {@code null}
8014      * @since 9
8015      */
8016     public static int mismatch(byte[] a, byte[] b) {
8017         int length = Math.min(a.length, b.length); // Check null array refs
8018         if (a == b)
8019             return -1;
8020 
8021         int i = ArraysSupport.mismatch(a, b, length);
8022         return (i < 0 && a.length != b.length) ? length : i;
8023     }
8024 
8025     /**
8026      * Finds and returns the relative index of the first mismatch between two
8027      * {@code byte} arrays over the specified ranges, otherwise return -1 if no
8028      * mismatch is found.  The index will be in the range of 0 (inclusive) up to
8029      * the length (inclusive) of the smaller range.
8030      *
8031      * <p>If the two arrays, over the specified ranges, share a common prefix
8032      * then the returned relative index is the length of the common prefix and
8033      * it follows that there is a mismatch between the two elements at that
8034      * relative index within the respective arrays.
8035      * If one array is a proper prefix of the other, over the specified ranges,
8036      * then the returned relative index is the length of the smaller range and
8037      * it follows that the relative index is only valid for the array with the
8038      * larger range.
8039      * Otherwise, there is no mismatch.
8040      *
8041      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
8042      * ranges [{@code aFromIndex}, {@code aToIndex}) and
8043      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a common
8044      * prefix of length {@code pl} if the following expression is true:
8045      * <pre>{@code
8046      *     pl >= 0 &&
8047      *     pl < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex) &&
8048      *     Arrays.equals(a, aFromIndex, aFromIndex + pl, b, bFromIndex, bFromIndex + pl) &&
8049      *     a[aFromIndex + pl] != b[bFromIndex + pl]
8050      * }</pre>
8051      * Note that a common prefix length of {@code 0} indicates that the first
8052      * elements from each array mismatch.
8053      *
8054      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
8055      * ranges [{@code aFromIndex}, {@code aToIndex}) and
8056      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a proper
8057      * prefix if the following expression is true:
8058      * <pre>{@code
8059      *     (aToIndex - aFromIndex) != (bToIndex - bFromIndex) &&
8060      *     Arrays.equals(a, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex),
8061      *                   b, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
8062      * }</pre>
8063      *
8064      * @param a the first array to be tested for a mismatch
8065      * @param aFromIndex the index (inclusive) of the first element in the
8066      *                   first array to be tested
8067      * @param aToIndex the index (exclusive) of the last element in the
8068      *                 first array to be tested
8069      * @param b the second array to be tested for a mismatch
8070      * @param bFromIndex the index (inclusive) of the first element in the
8071      *                   second array to be tested
8072      * @param bToIndex the index (exclusive) of the last element in the
8073      *                 second array to be tested
8074      * @return the relative index of the first mismatch between the two arrays
8075      *         over the specified ranges, otherwise {@code -1}.
8076      * @throws IllegalArgumentException
8077      *         if {@code aFromIndex > aToIndex} or
8078      *         if {@code bFromIndex > bToIndex}
8079      * @throws ArrayIndexOutOfBoundsException
8080      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
8081      *         if {@code bFromIndex < 0 or bToIndex > b.length}
8082      * @throws NullPointerException
8083      *         if either array is {@code null}
8084      * @since 9
8085      */
8086     public static int mismatch(byte[] a, int aFromIndex, int aToIndex,
8087                                byte[] b, int bFromIndex, int bToIndex) {
8088         rangeCheck(a.length, aFromIndex, aToIndex);
8089         rangeCheck(b.length, bFromIndex, bToIndex);
8090 
8091         int aLength = aToIndex - aFromIndex;
8092         int bLength = bToIndex - bFromIndex;
8093         int length = Math.min(aLength, bLength);
8094         int i = ArraysSupport.mismatch(a, aFromIndex,
8095                                        b, bFromIndex,
8096                                        length);
8097         return (i < 0 && aLength != bLength) ? length : i;
8098     }
8099 
8100     // Mismatch char
8101 
8102     /**
8103      * Finds and returns the index of the first mismatch between two {@code char}
8104      * arrays, otherwise return -1 if no mismatch is found.  The index will be
8105      * in the range of 0 (inclusive) up to the length (inclusive) of the smaller
8106      * array.
8107      *
8108      * <p>If the two arrays share a common prefix then the returned index is the
8109      * length of the common prefix and it follows that there is a mismatch
8110      * between the two elements at that index within the respective arrays.
8111      * If one array is a proper prefix of the other then the returned index is
8112      * the length of the smaller array and it follows that the index is only
8113      * valid for the larger array.
8114      * Otherwise, there is no mismatch.
8115      *
8116      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a common
8117      * prefix of length {@code pl} if the following expression is true:
8118      * <pre>{@code
8119      *     pl >= 0 &&
8120      *     pl < Math.min(a.length, b.length) &&
8121      *     Arrays.equals(a, 0, pl, b, 0, pl) &&
8122      *     a[pl] != b[pl]
8123      * }</pre>
8124      * Note that a common prefix length of {@code 0} indicates that the first
8125      * elements from each array mismatch.
8126      *
8127      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a proper
8128      * prefix if the following expression is true:
8129      * <pre>{@code
8130      *     a.length != b.length &&
8131      *     Arrays.equals(a, 0, Math.min(a.length, b.length),
8132      *                   b, 0, Math.min(a.length, b.length))
8133      * }</pre>
8134      *
8135      * @param a the first array to be tested for a mismatch
8136      * @param b the second array to be tested for a mismatch
8137      * @return the index of the first mismatch between the two arrays,
8138      *         otherwise {@code -1}.
8139      * @throws NullPointerException
8140      *         if either array is {@code null}
8141      * @since 9
8142      */
8143     public static int mismatch(char[] a, char[] b) {
8144         int length = Math.min(a.length, b.length); // Check null array refs
8145         if (a == b)
8146             return -1;
8147 
8148         int i = ArraysSupport.mismatch(a, b, length);
8149         return (i < 0 && a.length != b.length) ? length : i;
8150     }
8151 
8152     /**
8153      * Finds and returns the relative index of the first mismatch between two
8154      * {@code char} arrays over the specified ranges, otherwise return -1 if no
8155      * mismatch is found.  The index will be in the range of 0 (inclusive) up to
8156      * the length (inclusive) of the smaller range.
8157      *
8158      * <p>If the two arrays, over the specified ranges, share a common prefix
8159      * then the returned relative index is the length of the common prefix and
8160      * it follows that there is a mismatch between the two elements at that
8161      * relative index within the respective arrays.
8162      * If one array is a proper prefix of the other, over the specified ranges,
8163      * then the returned relative index is the length of the smaller range and
8164      * it follows that the relative index is only valid for the array with the
8165      * larger range.
8166      * Otherwise, there is no mismatch.
8167      *
8168      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
8169      * ranges [{@code aFromIndex}, {@code aToIndex}) and
8170      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a common
8171      * prefix of length {@code pl} if the following expression is true:
8172      * <pre>{@code
8173      *     pl >= 0 &&
8174      *     pl < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex) &&
8175      *     Arrays.equals(a, aFromIndex, aFromIndex + pl, b, bFromIndex, bFromIndex + pl) &&
8176      *     a[aFromIndex + pl] != b[bFromIndex + pl]
8177      * }</pre>
8178      * Note that a common prefix length of {@code 0} indicates that the first
8179      * elements from each array mismatch.
8180      *
8181      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
8182      * ranges [{@code aFromIndex}, {@code aToIndex}) and
8183      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a proper
8184      * prefix if the following expression is true:
8185      * <pre>{@code
8186      *     (aToIndex - aFromIndex) != (bToIndex - bFromIndex) &&
8187      *     Arrays.equals(a, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex),
8188      *                   b, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
8189      * }</pre>
8190      *
8191      * @param a the first array to be tested for a mismatch
8192      * @param aFromIndex the index (inclusive) of the first element in the
8193      *                   first array to be tested
8194      * @param aToIndex the index (exclusive) of the last element in the
8195      *                 first array to be tested
8196      * @param b the second array to be tested for a mismatch
8197      * @param bFromIndex the index (inclusive) of the first element in the
8198      *                   second array to be tested
8199      * @param bToIndex the index (exclusive) of the last element in the
8200      *                 second array to be tested
8201      * @return the relative index of the first mismatch between the two arrays
8202      *         over the specified ranges, otherwise {@code -1}.
8203      * @throws IllegalArgumentException
8204      *         if {@code aFromIndex > aToIndex} or
8205      *         if {@code bFromIndex > bToIndex}
8206      * @throws ArrayIndexOutOfBoundsException
8207      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
8208      *         if {@code bFromIndex < 0 or bToIndex > b.length}
8209      * @throws NullPointerException
8210      *         if either array is {@code null}
8211      * @since 9
8212      */
8213     public static int mismatch(char[] a, int aFromIndex, int aToIndex,
8214                                char[] b, int bFromIndex, int bToIndex) {
8215         rangeCheck(a.length, aFromIndex, aToIndex);
8216         rangeCheck(b.length, bFromIndex, bToIndex);
8217 
8218         int aLength = aToIndex - aFromIndex;
8219         int bLength = bToIndex - bFromIndex;
8220         int length = Math.min(aLength, bLength);
8221         int i = ArraysSupport.mismatch(a, aFromIndex,
8222                                        b, bFromIndex,
8223                                        length);
8224         return (i < 0 && aLength != bLength) ? length : i;
8225     }
8226 
8227     // Mismatch short
8228 
8229     /**
8230      * Finds and returns the index of the first mismatch between two {@code short}
8231      * arrays, otherwise return -1 if no mismatch is found.  The index will be
8232      * in the range of 0 (inclusive) up to the length (inclusive) of the smaller
8233      * array.
8234      *
8235      * <p>If the two arrays share a common prefix then the returned index is the
8236      * length of the common prefix and it follows that there is a mismatch
8237      * between the two elements at that index within the respective arrays.
8238      * If one array is a proper prefix of the other then the returned index is
8239      * the length of the smaller array and it follows that the index is only
8240      * valid for the larger array.
8241      * Otherwise, there is no mismatch.
8242      *
8243      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a common
8244      * prefix of length {@code pl} if the following expression is true:
8245      * <pre>{@code
8246      *     pl >= 0 &&
8247      *     pl < Math.min(a.length, b.length) &&
8248      *     Arrays.equals(a, 0, pl, b, 0, pl) &&
8249      *     a[pl] != b[pl]
8250      * }</pre>
8251      * Note that a common prefix length of {@code 0} indicates that the first
8252      * elements from each array mismatch.
8253      *
8254      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a proper
8255      * prefix if the following expression is true:
8256      * <pre>{@code
8257      *     a.length != b.length &&
8258      *     Arrays.equals(a, 0, Math.min(a.length, b.length),
8259      *                   b, 0, Math.min(a.length, b.length))
8260      * }</pre>
8261      *
8262      * @param a the first array to be tested for a mismatch
8263      * @param b the second array to be tested for a mismatch
8264      * @return the index of the first mismatch between the two arrays,
8265      *         otherwise {@code -1}.
8266      * @throws NullPointerException
8267      *         if either array is {@code null}
8268      * @since 9
8269      */
8270     public static int mismatch(short[] a, short[] b) {
8271         int length = Math.min(a.length, b.length); // Check null array refs
8272         if (a == b)
8273             return -1;
8274 
8275         int i = ArraysSupport.mismatch(a, b, length);
8276         return (i < 0 && a.length != b.length) ? length : i;
8277     }
8278 
8279     /**
8280      * Finds and returns the relative index of the first mismatch between two
8281      * {@code short} arrays over the specified ranges, otherwise return -1 if no
8282      * mismatch is found.  The index will be in the range of 0 (inclusive) up to
8283      * the length (inclusive) of the smaller range.
8284      *
8285      * <p>If the two arrays, over the specified ranges, share a common prefix
8286      * then the returned relative index is the length of the common prefix and
8287      * it follows that there is a mismatch between the two elements at that
8288      * relative index within the respective arrays.
8289      * If one array is a proper prefix of the other, over the specified ranges,
8290      * then the returned relative index is the length of the smaller range and
8291      * it follows that the relative index is only valid for the array with the
8292      * larger range.
8293      * Otherwise, there is no mismatch.
8294      *
8295      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
8296      * ranges [{@code aFromIndex}, {@code aToIndex}) and
8297      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a common
8298      * prefix of length {@code pl} if the following expression is true:
8299      * <pre>{@code
8300      *     pl >= 0 &&
8301      *     pl < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex) &&
8302      *     Arrays.equals(a, aFromIndex, aFromIndex + pl, b, bFromIndex, bFromIndex + pl) &&
8303      *     a[aFromIndex + pl] != b[bFromIndex + pl]
8304      * }</pre>
8305      * Note that a common prefix length of {@code 0} indicates that the first
8306      * elements from each array mismatch.
8307      *
8308      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
8309      * ranges [{@code aFromIndex}, {@code aToIndex}) and
8310      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a proper
8311      * prefix if the following expression is true:
8312      * <pre>{@code
8313      *     (aToIndex - aFromIndex) != (bToIndex - bFromIndex) &&
8314      *     Arrays.equals(a, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex),
8315      *                   b, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
8316      * }</pre>
8317      *
8318      * @param a the first array to be tested for a mismatch
8319      * @param aFromIndex the index (inclusive) of the first element in the
8320      *                   first array to be tested
8321      * @param aToIndex the index (exclusive) of the last element in the
8322      *                 first array to be tested
8323      * @param b the second array to be tested for a mismatch
8324      * @param bFromIndex the index (inclusive) of the first element in the
8325      *                   second array to be tested
8326      * @param bToIndex the index (exclusive) of the last element in the
8327      *                 second array to be tested
8328      * @return the relative index of the first mismatch between the two arrays
8329      *         over the specified ranges, otherwise {@code -1}.
8330      * @throws IllegalArgumentException
8331      *         if {@code aFromIndex > aToIndex} or
8332      *         if {@code bFromIndex > bToIndex}
8333      * @throws ArrayIndexOutOfBoundsException
8334      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
8335      *         if {@code bFromIndex < 0 or bToIndex > b.length}
8336      * @throws NullPointerException
8337      *         if either array is {@code null}
8338      * @since 9
8339      */
8340     public static int mismatch(short[] a, int aFromIndex, int aToIndex,
8341                                short[] b, int bFromIndex, int bToIndex) {
8342         rangeCheck(a.length, aFromIndex, aToIndex);
8343         rangeCheck(b.length, bFromIndex, bToIndex);
8344 
8345         int aLength = aToIndex - aFromIndex;
8346         int bLength = bToIndex - bFromIndex;
8347         int length = Math.min(aLength, bLength);
8348         int i = ArraysSupport.mismatch(a, aFromIndex,
8349                                        b, bFromIndex,
8350                                        length);
8351         return (i < 0 && aLength != bLength) ? length : i;
8352     }
8353 
8354     // Mismatch int
8355 
8356     /**
8357      * Finds and returns the index of the first mismatch between two {@code int}
8358      * arrays, otherwise return -1 if no mismatch is found.  The index will be
8359      * in the range of 0 (inclusive) up to the length (inclusive) of the smaller
8360      * array.
8361      *
8362      * <p>If the two arrays share a common prefix then the returned index is the
8363      * length of the common prefix and it follows that there is a mismatch
8364      * between the two elements at that index within the respective arrays.
8365      * If one array is a proper prefix of the other then the returned index is
8366      * the length of the smaller array and it follows that the index is only
8367      * valid for the larger array.
8368      * Otherwise, there is no mismatch.
8369      *
8370      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a common
8371      * prefix of length {@code pl} if the following expression is true:
8372      * <pre>{@code
8373      *     pl >= 0 &&
8374      *     pl < Math.min(a.length, b.length) &&
8375      *     Arrays.equals(a, 0, pl, b, 0, pl) &&
8376      *     a[pl] != b[pl]
8377      * }</pre>
8378      * Note that a common prefix length of {@code 0} indicates that the first
8379      * elements from each array mismatch.
8380      *
8381      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a proper
8382      * prefix if the following expression is true:
8383      * <pre>{@code
8384      *     a.length != b.length &&
8385      *     Arrays.equals(a, 0, Math.min(a.length, b.length),
8386      *                   b, 0, Math.min(a.length, b.length))
8387      * }</pre>
8388      *
8389      * @param a the first array to be tested for a mismatch
8390      * @param b the second array to be tested for a mismatch
8391      * @return the index of the first mismatch between the two arrays,
8392      *         otherwise {@code -1}.
8393      * @throws NullPointerException
8394      *         if either array is {@code null}
8395      * @since 9
8396      */
8397     public static int mismatch(int[] a, int[] b) {
8398         int length = Math.min(a.length, b.length); // Check null array refs
8399         if (a == b)
8400             return -1;
8401 
8402         int i = ArraysSupport.mismatch(a, b, length);
8403         return (i < 0 && a.length != b.length) ? length : i;
8404     }
8405 
8406     /**
8407      * Finds and returns the relative index of the first mismatch between two
8408      * {@code int} arrays over the specified ranges, otherwise return -1 if no
8409      * mismatch is found.  The index will be in the range of 0 (inclusive) up to
8410      * the length (inclusive) of the smaller range.
8411      *
8412      * <p>If the two arrays, over the specified ranges, share a common prefix
8413      * then the returned relative index is the length of the common prefix and
8414      * it follows that there is a mismatch between the two elements at that
8415      * relative index within the respective arrays.
8416      * If one array is a proper prefix of the other, over the specified ranges,
8417      * then the returned relative index is the length of the smaller range and
8418      * it follows that the relative index is only valid for the array with the
8419      * larger range.
8420      * Otherwise, there is no mismatch.
8421      *
8422      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
8423      * ranges [{@code aFromIndex}, {@code aToIndex}) and
8424      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a common
8425      * prefix of length {@code pl} if the following expression is true:
8426      * <pre>{@code
8427      *     pl >= 0 &&
8428      *     pl < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex) &&
8429      *     Arrays.equals(a, aFromIndex, aFromIndex + pl, b, bFromIndex, bFromIndex + pl) &&
8430      *     a[aFromIndex + pl] != b[bFromIndex + pl]
8431      * }</pre>
8432      * Note that a common prefix length of {@code 0} indicates that the first
8433      * elements from each array mismatch.
8434      *
8435      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
8436      * ranges [{@code aFromIndex}, {@code aToIndex}) and
8437      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a proper
8438      * prefix if the following expression is true:
8439      * <pre>{@code
8440      *     (aToIndex - aFromIndex) != (bToIndex - bFromIndex) &&
8441      *     Arrays.equals(a, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex),
8442      *                   b, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
8443      * }</pre>
8444      *
8445      * @param a the first array to be tested for a mismatch
8446      * @param aFromIndex the index (inclusive) of the first element in the
8447      *                   first array to be tested
8448      * @param aToIndex the index (exclusive) of the last element in the
8449      *                 first array to be tested
8450      * @param b the second array to be tested for a mismatch
8451      * @param bFromIndex the index (inclusive) of the first element in the
8452      *                   second array to be tested
8453      * @param bToIndex the index (exclusive) of the last element in the
8454      *                 second array to be tested
8455      * @return the relative index of the first mismatch between the two arrays
8456      *         over the specified ranges, otherwise {@code -1}.
8457      * @throws IllegalArgumentException
8458      *         if {@code aFromIndex > aToIndex} or
8459      *         if {@code bFromIndex > bToIndex}
8460      * @throws ArrayIndexOutOfBoundsException
8461      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
8462      *         if {@code bFromIndex < 0 or bToIndex > b.length}
8463      * @throws NullPointerException
8464      *         if either array is {@code null}
8465      * @since 9
8466      */
8467     public static int mismatch(int[] a, int aFromIndex, int aToIndex,
8468                                int[] b, int bFromIndex, int bToIndex) {
8469         rangeCheck(a.length, aFromIndex, aToIndex);
8470         rangeCheck(b.length, bFromIndex, bToIndex);
8471 
8472         int aLength = aToIndex - aFromIndex;
8473         int bLength = bToIndex - bFromIndex;
8474         int length = Math.min(aLength, bLength);
8475         int i = ArraysSupport.mismatch(a, aFromIndex,
8476                                        b, bFromIndex,
8477                                        length);
8478         return (i < 0 && aLength != bLength) ? length : i;
8479     }
8480 
8481     // Mismatch long
8482 
8483     /**
8484      * Finds and returns the index of the first mismatch between two {@code long}
8485      * arrays, otherwise return -1 if no mismatch is found.  The index will be
8486      * in the range of 0 (inclusive) up to the length (inclusive) of the smaller
8487      * array.
8488      *
8489      * <p>If the two arrays share a common prefix then the returned index is the
8490      * length of the common prefix and it follows that there is a mismatch
8491      * between the two elements at that index within the respective arrays.
8492      * If one array is a proper prefix of the other then the returned index is
8493      * the length of the smaller array and it follows that the index is only
8494      * valid for the larger array.
8495      * Otherwise, there is no mismatch.
8496      *
8497      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a common
8498      * prefix of length {@code pl} if the following expression is true:
8499      * <pre>{@code
8500      *     pl >= 0 &&
8501      *     pl < Math.min(a.length, b.length) &&
8502      *     Arrays.equals(a, 0, pl, b, 0, pl) &&
8503      *     a[pl] != b[pl]
8504      * }</pre>
8505      * Note that a common prefix length of {@code 0} indicates that the first
8506      * elements from each array mismatch.
8507      *
8508      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a proper
8509      * prefix if the following expression is true:
8510      * <pre>{@code
8511      *     a.length != b.length &&
8512      *     Arrays.equals(a, 0, Math.min(a.length, b.length),
8513      *                   b, 0, Math.min(a.length, b.length))
8514      * }</pre>
8515      *
8516      * @param a the first array to be tested for a mismatch
8517      * @param b the second array to be tested for a mismatch
8518      * @return the index of the first mismatch between the two arrays,
8519      *         otherwise {@code -1}.
8520      * @throws NullPointerException
8521      *         if either array is {@code null}
8522      * @since 9
8523      */
8524     public static int mismatch(long[] a, long[] b) {
8525         int length = Math.min(a.length, b.length); // Check null array refs
8526         if (a == b)
8527             return -1;
8528 
8529         int i = ArraysSupport.mismatch(a, b, length);
8530         return (i < 0 && a.length != b.length) ? length : i;
8531     }
8532 
8533     /**
8534      * Finds and returns the relative index of the first mismatch between two
8535      * {@code long} arrays over the specified ranges, otherwise return -1 if no
8536      * mismatch is found.  The index will be in the range of 0 (inclusive) up to
8537      * the length (inclusive) of the smaller range.
8538      *
8539      * <p>If the two arrays, over the specified ranges, share a common prefix
8540      * then the returned relative index is the length of the common prefix and
8541      * it follows that there is a mismatch between the two elements at that
8542      * relative index within the respective arrays.
8543      * If one array is a proper prefix of the other, over the specified ranges,
8544      * then the returned relative index is the length of the smaller range and
8545      * it follows that the relative index is only valid for the array with the
8546      * larger range.
8547      * Otherwise, there is no mismatch.
8548      *
8549      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
8550      * ranges [{@code aFromIndex}, {@code aToIndex}) and
8551      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a common
8552      * prefix of length {@code pl} if the following expression is true:
8553      * <pre>{@code
8554      *     pl >= 0 &&
8555      *     pl < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex) &&
8556      *     Arrays.equals(a, aFromIndex, aFromIndex + pl, b, bFromIndex, bFromIndex + pl) &&
8557      *     a[aFromIndex + pl] != b[bFromIndex + pl]
8558      * }</pre>
8559      * Note that a common prefix length of {@code 0} indicates that the first
8560      * elements from each array mismatch.
8561      *
8562      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
8563      * ranges [{@code aFromIndex}, {@code aToIndex}) and
8564      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a proper
8565      * prefix if the following expression is true:
8566      * <pre>{@code
8567      *     (aToIndex - aFromIndex) != (bToIndex - bFromIndex) &&
8568      *     Arrays.equals(a, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex),
8569      *                   b, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
8570      * }</pre>
8571      *
8572      * @param a the first array to be tested for a mismatch
8573      * @param aFromIndex the index (inclusive) of the first element in the
8574      *                   first array to be tested
8575      * @param aToIndex the index (exclusive) of the last element in the
8576      *                 first array to be tested
8577      * @param b the second array to be tested for a mismatch
8578      * @param bFromIndex the index (inclusive) of the first element in the
8579      *                   second array to be tested
8580      * @param bToIndex the index (exclusive) of the last element in the
8581      *                 second array to be tested
8582      * @return the relative index of the first mismatch between the two arrays
8583      *         over the specified ranges, otherwise {@code -1}.
8584      * @throws IllegalArgumentException
8585      *         if {@code aFromIndex > aToIndex} or
8586      *         if {@code bFromIndex > bToIndex}
8587      * @throws ArrayIndexOutOfBoundsException
8588      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
8589      *         if {@code bFromIndex < 0 or bToIndex > b.length}
8590      * @throws NullPointerException
8591      *         if either array is {@code null}
8592      * @since 9
8593      */
8594     public static int mismatch(long[] a, int aFromIndex, int aToIndex,
8595                                long[] b, int bFromIndex, int bToIndex) {
8596         rangeCheck(a.length, aFromIndex, aToIndex);
8597         rangeCheck(b.length, bFromIndex, bToIndex);
8598 
8599         int aLength = aToIndex - aFromIndex;
8600         int bLength = bToIndex - bFromIndex;
8601         int length = Math.min(aLength, bLength);
8602         int i = ArraysSupport.mismatch(a, aFromIndex,
8603                                        b, bFromIndex,
8604                                        length);
8605         return (i < 0 && aLength != bLength) ? length : i;
8606     }
8607 
8608     // Mismatch float
8609 
8610     /**
8611      * Finds and returns the index of the first mismatch between two {@code float}
8612      * arrays, otherwise return -1 if no mismatch is found.  The index will be
8613      * in the range of 0 (inclusive) up to the length (inclusive) of the smaller
8614      * array.
8615      *
8616      * <p>If the two arrays share a common prefix then the returned index is the
8617      * length of the common prefix and it follows that there is a mismatch
8618      * between the two elements at that index within the respective arrays.
8619      * If one array is a proper prefix of the other then the returned index is
8620      * the length of the smaller array and it follows that the index is only
8621      * valid for the larger array.
8622      * Otherwise, there is no mismatch.
8623      *
8624      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a common
8625      * prefix of length {@code pl} if the following expression is true:
8626      * <pre>{@code
8627      *     pl >= 0 &&
8628      *     pl < Math.min(a.length, b.length) &&
8629      *     Arrays.equals(a, 0, pl, b, 0, pl) &&
8630      *     Float.compare(a[pl], b[pl]) != 0
8631      * }</pre>
8632      * Note that a common prefix length of {@code 0} indicates that the first
8633      * elements from each array mismatch.
8634      *
8635      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a proper
8636      * prefix if the following expression is true:
8637      * <pre>{@code
8638      *     a.length != b.length &&
8639      *     Arrays.equals(a, 0, Math.min(a.length, b.length),
8640      *                   b, 0, Math.min(a.length, b.length))
8641      * }</pre>
8642      *
8643      * @param a the first array to be tested for a mismatch
8644      * @param b the second array to be tested for a mismatch
8645      * @return the index of the first mismatch between the two arrays,
8646      *         otherwise {@code -1}.
8647      * @throws NullPointerException
8648      *         if either array is {@code null}
8649      * @since 9
8650      */
8651     public static int mismatch(float[] a, float[] b) {
8652         int length = Math.min(a.length, b.length); // Check null array refs
8653         if (a == b)
8654             return -1;
8655 
8656         int i = ArraysSupport.mismatch(a, b, length);
8657         return (i < 0 && a.length != b.length) ? length : i;
8658     }
8659 
8660     /**
8661      * Finds and returns the relative index of the first mismatch between two
8662      * {@code float} arrays over the specified ranges, otherwise return -1 if no
8663      * mismatch is found.  The index will be in the range of 0 (inclusive) up to
8664      * the length (inclusive) of the smaller range.
8665      *
8666      * <p>If the two arrays, over the specified ranges, share a common prefix
8667      * then the returned relative index is the length of the common prefix and
8668      * it follows that there is a mismatch between the two elements at that
8669      * relative index within the respective arrays.
8670      * If one array is a proper prefix of the other, over the specified ranges,
8671      * then the returned relative index is the length of the smaller range and
8672      * it follows that the relative index is only valid for the array with the
8673      * larger range.
8674      * Otherwise, there is no mismatch.
8675      *
8676      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
8677      * ranges [{@code aFromIndex}, {@code aToIndex}) and
8678      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a common
8679      * prefix of length {@code pl} if the following expression is true:
8680      * <pre>{@code
8681      *     pl >= 0 &&
8682      *     pl < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex) &&
8683      *     Arrays.equals(a, aFromIndex, aFromIndex + pl, b, bFromIndex, bFromIndex + pl) &&
8684      *     Float.compare(a[aFromIndex + pl], b[bFromIndex + pl]) != 0
8685      * }</pre>
8686      * Note that a common prefix length of {@code 0} indicates that the first
8687      * elements from each array mismatch.
8688      *
8689      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
8690      * ranges [{@code aFromIndex}, {@code aToIndex}) and
8691      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a proper
8692      * prefix if the following expression is true:
8693      * <pre>{@code
8694      *     (aToIndex - aFromIndex) != (bToIndex - bFromIndex) &&
8695      *     Arrays.equals(a, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex),
8696      *                   b, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
8697      * }</pre>
8698      *
8699      * @param a the first array to be tested for a mismatch
8700      * @param aFromIndex the index (inclusive) of the first element in the
8701      *                   first array to be tested
8702      * @param aToIndex the index (exclusive) of the last element in the
8703      *                 first array to be tested
8704      * @param b the second array to be tested for a mismatch
8705      * @param bFromIndex the index (inclusive) of the first element in the
8706      *                   second array to be tested
8707      * @param bToIndex the index (exclusive) of the last element in the
8708      *                 second array to be tested
8709      * @return the relative index of the first mismatch between the two arrays
8710      *         over the specified ranges, otherwise {@code -1}.
8711      * @throws IllegalArgumentException
8712      *         if {@code aFromIndex > aToIndex} or
8713      *         if {@code bFromIndex > bToIndex}
8714      * @throws ArrayIndexOutOfBoundsException
8715      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
8716      *         if {@code bFromIndex < 0 or bToIndex > b.length}
8717      * @throws NullPointerException
8718      *         if either array is {@code null}
8719      * @since 9
8720      */
8721     public static int mismatch(float[] a, int aFromIndex, int aToIndex,
8722                                float[] b, int bFromIndex, int bToIndex) {
8723         rangeCheck(a.length, aFromIndex, aToIndex);
8724         rangeCheck(b.length, bFromIndex, bToIndex);
8725 
8726         int aLength = aToIndex - aFromIndex;
8727         int bLength = bToIndex - bFromIndex;
8728         int length = Math.min(aLength, bLength);
8729         int i = ArraysSupport.mismatch(a, aFromIndex,
8730                                        b, bFromIndex,
8731                                        length);
8732         return (i < 0 && aLength != bLength) ? length : i;
8733     }
8734 
8735     // Mismatch double
8736 
8737     /**
8738      * Finds and returns the index of the first mismatch between two
8739      * {@code double} arrays, otherwise return -1 if no mismatch is found.  The
8740      * index will be in the range of 0 (inclusive) up to the length (inclusive)
8741      * of the smaller array.
8742      *
8743      * <p>If the two arrays share a common prefix then the returned index is the
8744      * length of the common prefix and it follows that there is a mismatch
8745      * between the two elements at that index within the respective arrays.
8746      * If one array is a proper prefix of the other then the returned index is
8747      * the length of the smaller array and it follows that the index is only
8748      * valid for the larger array.
8749      * Otherwise, there is no mismatch.
8750      *
8751      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a common
8752      * prefix of length {@code pl} if the following expression is true:
8753      * <pre>{@code
8754      *     pl >= 0 &&
8755      *     pl < Math.min(a.length, b.length) &&
8756      *     Arrays.equals(a, 0, pl, b, 0, pl) &&
8757      *     Double.compare(a[pl], b[pl]) != 0
8758      * }</pre>
8759      * Note that a common prefix length of {@code 0} indicates that the first
8760      * elements from each array mismatch.
8761      *
8762      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a proper
8763      * prefix if the following expression is true:
8764      * <pre>{@code
8765      *     a.length != b.length &&
8766      *     Arrays.equals(a, 0, Math.min(a.length, b.length),
8767      *                   b, 0, Math.min(a.length, b.length))
8768      * }</pre>
8769      *
8770      * @param a the first array to be tested for a mismatch
8771      * @param b the second array to be tested for a mismatch
8772      * @return the index of the first mismatch between the two arrays,
8773      *         otherwise {@code -1}.
8774      * @throws NullPointerException
8775      *         if either array is {@code null}
8776      * @since 9
8777      */
8778     public static int mismatch(double[] a, double[] b) {
8779         int length = Math.min(a.length, b.length); // Check null array refs
8780         if (a == b)
8781             return -1;
8782 
8783         int i = ArraysSupport.mismatch(a, b, length);
8784         return (i < 0 && a.length != b.length) ? length : i;
8785     }
8786 
8787     /**
8788      * Finds and returns the relative index of the first mismatch between two
8789      * {@code double} arrays over the specified ranges, otherwise return -1 if
8790      * no mismatch is found.  The index will be in the range of 0 (inclusive) up
8791      * to the length (inclusive) of the smaller range.
8792      *
8793      * <p>If the two arrays, over the specified ranges, share a common prefix
8794      * then the returned relative index is the length of the common prefix and
8795      * it follows that there is a mismatch between the two elements at that
8796      * relative index within the respective arrays.
8797      * If one array is a proper prefix of the other, over the specified ranges,
8798      * then the returned relative index is the length of the smaller range and
8799      * it follows that the relative index is only valid for the array with the
8800      * larger range.
8801      * Otherwise, there is no mismatch.
8802      *
8803      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
8804      * ranges [{@code aFromIndex}, {@code aToIndex}) and
8805      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a common
8806      * prefix of length {@code pl} if the following expression is true:
8807      * <pre>{@code
8808      *     pl >= 0 &&
8809      *     pl < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex) &&
8810      *     Arrays.equals(a, aFromIndex, aFromIndex + pl, b, bFromIndex, bFromIndex + pl) &&
8811      *     Double.compare(a[aFromIndex + pl], b[bFromIndex + pl]) != 0
8812      * }</pre>
8813      * Note that a common prefix length of {@code 0} indicates that the first
8814      * elements from each array mismatch.
8815      *
8816      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
8817      * ranges [{@code aFromIndex}, {@code aToIndex}) and
8818      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a proper
8819      * prefix if the following expression is true:
8820      * <pre>{@code
8821      *     (aToIndex - aFromIndex) != (bToIndex - bFromIndex) &&
8822      *     Arrays.equals(a, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex),
8823      *                   b, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
8824      * }</pre>
8825      *
8826      * @param a the first array to be tested for a mismatch
8827      * @param aFromIndex the index (inclusive) of the first element in the
8828      *                   first array to be tested
8829      * @param aToIndex the index (exclusive) of the last element in the
8830      *                 first array to be tested
8831      * @param b the second array to be tested for a mismatch
8832      * @param bFromIndex the index (inclusive) of the first element in the
8833      *                   second array to be tested
8834      * @param bToIndex the index (exclusive) of the last element in the
8835      *                 second array to be tested
8836      * @return the relative index of the first mismatch between the two arrays
8837      *         over the specified ranges, otherwise {@code -1}.
8838      * @throws IllegalArgumentException
8839      *         if {@code aFromIndex > aToIndex} or
8840      *         if {@code bFromIndex > bToIndex}
8841      * @throws ArrayIndexOutOfBoundsException
8842      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
8843      *         if {@code bFromIndex < 0 or bToIndex > b.length}
8844      * @throws NullPointerException
8845      *         if either array is {@code null}
8846      * @since 9
8847      */
8848     public static int mismatch(double[] a, int aFromIndex, int aToIndex,
8849                                double[] b, int bFromIndex, int bToIndex) {
8850         rangeCheck(a.length, aFromIndex, aToIndex);
8851         rangeCheck(b.length, bFromIndex, bToIndex);
8852 
8853         int aLength = aToIndex - aFromIndex;
8854         int bLength = bToIndex - bFromIndex;
8855         int length = Math.min(aLength, bLength);
8856         int i = ArraysSupport.mismatch(a, aFromIndex,
8857                                        b, bFromIndex,
8858                                        length);
8859         return (i < 0 && aLength != bLength) ? length : i;
8860     }
8861 
8862     // Mismatch objects
8863 
8864     /**
8865      * Finds and returns the index of the first mismatch between two
8866      * {@code Object} arrays, otherwise return -1 if no mismatch is found.  The
8867      * index will be in the range of 0 (inclusive) up to the length (inclusive)
8868      * of the smaller array.
8869      *
8870      * <p>If the two arrays share a common prefix then the returned index is the
8871      * length of the common prefix and it follows that there is a mismatch
8872      * between the two elements at that index within the respective arrays.
8873      * If one array is a proper prefix of the other then the returned index is
8874      * the length of the smaller array and it follows that the index is only
8875      * valid for the larger array.
8876      * Otherwise, there is no mismatch.
8877      *
8878      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a common
8879      * prefix of length {@code pl} if the following expression is true:
8880      * <pre>{@code
8881      *     pl >= 0 &&
8882      *     pl < Math.min(a.length, b.length) &&
8883      *     Arrays.equals(a, 0, pl, b, 0, pl) &&
8884      *     !Objects.equals(a[pl], b[pl])
8885      * }</pre>
8886      * Note that a common prefix length of {@code 0} indicates that the first
8887      * elements from each array mismatch.
8888      *
8889      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a proper
8890      * prefix if the following expression is true:
8891      * <pre>{@code
8892      *     a.length != b.length &&
8893      *     Arrays.equals(a, 0, Math.min(a.length, b.length),
8894      *                   b, 0, Math.min(a.length, b.length))
8895      * }</pre>
8896      *
8897      * @param a the first array to be tested for a mismatch
8898      * @param b the second array to be tested for a mismatch
8899      * @return the index of the first mismatch between the two arrays,
8900      *         otherwise {@code -1}.
8901      * @throws NullPointerException
8902      *         if either array is {@code null}
8903      * @since 9
8904      */
8905     public static int mismatch(Object[] a, Object[] b) {
8906         int length = Math.min(a.length, b.length); // Check null array refs
8907         if (a == b)
8908             return -1;
8909 
8910         for (int i = 0; i < length; i++) {
8911             if (!Objects.equals(a[i], b[i]))
8912                 return i;
8913         }
8914 
8915         return a.length != b.length ? length : -1;
8916     }
8917 
8918     /**
8919      * Finds and returns the relative index of the first mismatch between two
8920      * {@code Object} arrays over the specified ranges, otherwise return -1 if
8921      * no mismatch is found.  The index will be in the range of 0 (inclusive) up
8922      * to the length (inclusive) of the smaller range.
8923      *
8924      * <p>If the two arrays, over the specified ranges, share a common prefix
8925      * then the returned relative index is the length of the common prefix and
8926      * it follows that there is a mismatch between the two elements at that
8927      * relative index within the respective arrays.
8928      * If one array is a proper prefix of the other, over the specified ranges,
8929      * then the returned relative index is the length of the smaller range and
8930      * it follows that the relative index is only valid for the array with the
8931      * larger range.
8932      * Otherwise, there is no mismatch.
8933      *
8934      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
8935      * ranges [{@code aFromIndex}, {@code aToIndex}) and
8936      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a common
8937      * prefix of length {@code pl} if the following expression is true:
8938      * <pre>{@code
8939      *     pl >= 0 &&
8940      *     pl < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex) &&
8941      *     Arrays.equals(a, aFromIndex, aFromIndex + pl, b, bFromIndex, bFromIndex + pl) &&
8942      *     !Objects.equals(a[aFromIndex + pl], b[bFromIndex + pl])
8943      * }</pre>
8944      * Note that a common prefix length of {@code 0} indicates that the first
8945      * elements from each array mismatch.
8946      *
8947      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
8948      * ranges [{@code aFromIndex}, {@code aToIndex}) and
8949      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a proper
8950      * prefix if the following expression is true:
8951      * <pre>{@code
8952      *     (aToIndex - aFromIndex) != (bToIndex - bFromIndex) &&
8953      *     Arrays.equals(a, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex),
8954      *                   b, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex))
8955      * }</pre>
8956      *
8957      * @param a the first array to be tested for a mismatch
8958      * @param aFromIndex the index (inclusive) of the first element in the
8959      *                   first array to be tested
8960      * @param aToIndex the index (exclusive) of the last element in the
8961      *                 first array to be tested
8962      * @param b the second array to be tested for a mismatch
8963      * @param bFromIndex the index (inclusive) of the first element in the
8964      *                   second array to be tested
8965      * @param bToIndex the index (exclusive) of the last element in the
8966      *                 second array to be tested
8967      * @return the relative index of the first mismatch between the two arrays
8968      *         over the specified ranges, otherwise {@code -1}.
8969      * @throws IllegalArgumentException
8970      *         if {@code aFromIndex > aToIndex} or
8971      *         if {@code bFromIndex > bToIndex}
8972      * @throws ArrayIndexOutOfBoundsException
8973      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
8974      *         if {@code bFromIndex < 0 or bToIndex > b.length}
8975      * @throws NullPointerException
8976      *         if either array is {@code null}
8977      * @since 9
8978      */
8979     public static int mismatch(
8980             Object[] a, int aFromIndex, int aToIndex,
8981             Object[] b, int bFromIndex, int bToIndex) {
8982         rangeCheck(a.length, aFromIndex, aToIndex);
8983         rangeCheck(b.length, bFromIndex, bToIndex);
8984 
8985         int aLength = aToIndex - aFromIndex;
8986         int bLength = bToIndex - bFromIndex;
8987         int length = Math.min(aLength, bLength);
8988         for (int i = 0; i < length; i++) {
8989             if (!Objects.equals(a[aFromIndex++], b[bFromIndex++]))
8990                 return i;
8991         }
8992 
8993         return aLength != bLength ? length : -1;
8994     }
8995 
8996     /**
8997      * Finds and returns the index of the first mismatch between two
8998      * {@code Object} arrays, otherwise return -1 if no mismatch is found.
8999      * The index will be in the range of 0 (inclusive) up to the length
9000      * (inclusive) of the smaller array.
9001      *
9002      * <p>The specified comparator is used to determine if two array elements
9003      * from the each array are not equal.
9004      *
9005      * <p>If the two arrays share a common prefix then the returned index is the
9006      * length of the common prefix and it follows that there is a mismatch
9007      * between the two elements at that index within the respective arrays.
9008      * If one array is a proper prefix of the other then the returned index is
9009      * the length of the smaller array and it follows that the index is only
9010      * valid for the larger array.
9011      * Otherwise, there is no mismatch.
9012      *
9013      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a common
9014      * prefix of length {@code pl} if the following expression is true:
9015      * <pre>{@code
9016      *     pl >= 0 &&
9017      *     pl < Math.min(a.length, b.length) &&
9018      *     Arrays.equals(a, 0, pl, b, 0, pl, cmp)
9019      *     cmp.compare(a[pl], b[pl]) != 0
9020      * }</pre>
9021      * Note that a common prefix length of {@code 0} indicates that the first
9022      * elements from each array mismatch.
9023      *
9024      * <p>Two non-{@code null} arrays, {@code a} and {@code b}, share a proper
9025      * prefix if the following expression is true:
9026      * <pre>{@code
9027      *     a.length != b.length &&
9028      *     Arrays.equals(a, 0, Math.min(a.length, b.length),
9029      *                   b, 0, Math.min(a.length, b.length),
9030      *                   cmp)
9031      * }</pre>
9032      *
9033      * @param a the first array to be tested for a mismatch
9034      * @param b the second array to be tested for a mismatch
9035      * @param cmp the comparator to compare array elements
9036      * @param <T> the type of array elements
9037      * @return the index of the first mismatch between the two arrays,
9038      *         otherwise {@code -1}.
9039      * @throws NullPointerException
9040      *         if either array or the comparator is {@code null}
9041      * @since 9
9042      */
9043     public static <T> int mismatch(T[] a, T[] b, Comparator<? super T> cmp) {
9044         Objects.requireNonNull(cmp);
9045         int length = Math.min(a.length, b.length); // Check null array refs
9046         if (a == b)
9047             return -1;
9048 
9049         for (int i = 0; i < length; i++) {
9050             T oa = a[i];
9051             T ob = b[i];
9052             if (oa != ob) {
9053                 // Null-value comparison is deferred to the comparator
9054                 int v = cmp.compare(oa, ob);
9055                 if (v != 0) {
9056                     return i;
9057                 }
9058             }
9059         }
9060 
9061         return a.length != b.length ? length : -1;
9062     }
9063 
9064     /**
9065      * Finds and returns the relative index of the first mismatch between two
9066      * {@code Object} arrays over the specified ranges, otherwise return -1 if
9067      * no mismatch is found.  The index will be in the range of 0 (inclusive) up
9068      * to the length (inclusive) of the smaller range.
9069      *
9070      * <p>If the two arrays, over the specified ranges, share a common prefix
9071      * then the returned relative index is the length of the common prefix and
9072      * it follows that there is a mismatch between the two elements at that
9073      * relative index within the respective arrays.
9074      * If one array is a proper prefix of the other, over the specified ranges,
9075      * then the returned relative index is the length of the smaller range and
9076      * it follows that the relative index is only valid for the array with the
9077      * larger range.
9078      * Otherwise, there is no mismatch.
9079      *
9080      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
9081      * ranges [{@code aFromIndex}, {@code aToIndex}) and
9082      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a common
9083      * prefix of length {@code pl} if the following expression is true:
9084      * <pre>{@code
9085      *     pl >= 0 &&
9086      *     pl < Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex) &&
9087      *     Arrays.equals(a, aFromIndex, aFromIndex + pl, b, bFromIndex, bFromIndex + pl, cmp) &&
9088      *     cmp.compare(a[aFromIndex + pl], b[bFromIndex + pl]) != 0
9089      * }</pre>
9090      * Note that a common prefix length of {@code 0} indicates that the first
9091      * elements from each array mismatch.
9092      *
9093      * <p>Two non-{@code null} arrays, {@code a} and {@code b} with specified
9094      * ranges [{@code aFromIndex}, {@code aToIndex}) and
9095      * [{@code bFromIndex}, {@code bToIndex}) respectively, share a proper
9096      * prefix if the following expression is true:
9097      * <pre>{@code
9098      *     (aToIndex - aFromIndex) != (bToIndex - bFromIndex) &&
9099      *     Arrays.equals(a, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex),
9100      *                   b, 0, Math.min(aToIndex - aFromIndex, bToIndex - bFromIndex),
9101      *                   cmp)
9102      * }</pre>
9103      *
9104      * @param a the first array to be tested for a mismatch
9105      * @param aFromIndex the index (inclusive) of the first element in the
9106      *                   first array to be tested
9107      * @param aToIndex the index (exclusive) of the last element in the
9108      *                 first array to be tested
9109      * @param b the second array to be tested for a mismatch
9110      * @param bFromIndex the index (inclusive) of the first element in the
9111      *                   second array to be tested
9112      * @param bToIndex the index (exclusive) of the last element in the
9113      *                 second array to be tested
9114      * @param cmp the comparator to compare array elements
9115      * @param <T> the type of array elements
9116      * @return the relative index of the first mismatch between the two arrays
9117      *         over the specified ranges, otherwise {@code -1}.
9118      * @throws IllegalArgumentException
9119      *         if {@code aFromIndex > aToIndex} or
9120      *         if {@code bFromIndex > bToIndex}
9121      * @throws ArrayIndexOutOfBoundsException
9122      *         if {@code aFromIndex < 0 or aToIndex > a.length} or
9123      *         if {@code bFromIndex < 0 or bToIndex > b.length}
9124      * @throws NullPointerException
9125      *         if either array or the comparator is {@code null}
9126      * @since 9
9127      */
9128     public static <T> int mismatch(
9129             T[] a, int aFromIndex, int aToIndex,
9130             T[] b, int bFromIndex, int bToIndex,
9131             Comparator<? super T> cmp) {
9132         Objects.requireNonNull(cmp);
9133         rangeCheck(a.length, aFromIndex, aToIndex);
9134         rangeCheck(b.length, bFromIndex, bToIndex);
9135 
9136         int aLength = aToIndex - aFromIndex;
9137         int bLength = bToIndex - bFromIndex;
9138         int length = Math.min(aLength, bLength);
9139         for (int i = 0; i < length; i++) {
9140             T oa = a[aFromIndex++];
9141             T ob = b[bFromIndex++];
9142             if (oa != ob) {
9143                 // Null-value comparison is deferred to the comparator
9144                 int v = cmp.compare(oa, ob);
9145                 if (v != 0) {
9146                     return i;
9147                 }
9148             }
9149         }
9150 
9151         return aLength != bLength ? length : -1;
9152     }
9153 }
9154