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