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