Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/util/Arrays.java
38829 views
/*1* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.util;2627import java.lang.reflect.Array;28import java.util.concurrent.ForkJoinPool;29import java.util.function.BinaryOperator;30import java.util.function.Consumer;31import java.util.function.DoubleBinaryOperator;32import java.util.function.IntBinaryOperator;33import java.util.function.IntFunction;34import java.util.function.IntToDoubleFunction;35import java.util.function.IntToLongFunction;36import java.util.function.IntUnaryOperator;37import java.util.function.LongBinaryOperator;38import java.util.function.UnaryOperator;39import java.util.stream.DoubleStream;40import java.util.stream.IntStream;41import java.util.stream.LongStream;42import java.util.stream.Stream;43import java.util.stream.StreamSupport;4445/**46* This class contains various methods for manipulating arrays (such as47* sorting and searching). This class also contains a static factory48* that allows arrays to be viewed as lists.49*50* <p>The methods in this class all throw a {@code NullPointerException},51* if the specified array reference is null, except where noted.52*53* <p>The documentation for the methods contained in this class includes54* briefs description of the <i>implementations</i>. Such descriptions should55* be regarded as <i>implementation notes</i>, rather than parts of the56* <i>specification</i>. Implementors should feel free to substitute other57* algorithms, so long as the specification itself is adhered to. (For58* example, the algorithm used by {@code sort(Object[])} does not have to be59* a MergeSort, but it does have to be <i>stable</i>.)60*61* <p>This class is a member of the62* <a href="{@docRoot}/../technotes/guides/collections/index.html">63* Java Collections Framework</a>.64*65* @author Josh Bloch66* @author Neal Gafter67* @author John Rose68* @since 1.269*/70public class Arrays {7172/**73* The minimum array length below which a parallel sorting74* algorithm will not further partition the sorting task. Using75* smaller sizes typically results in memory contention across76* tasks that makes parallel speedups unlikely.77*/78private static final int MIN_ARRAY_SORT_GRAN = 1 << 13;7980// Suppresses default constructor, ensuring non-instantiability.81private Arrays() {}8283/**84* A comparator that implements the natural ordering of a group of85* mutually comparable elements. May be used when a supplied86* comparator is null. To simplify code-sharing within underlying87* implementations, the compare method only declares type Object88* for its second argument.89*90* Arrays class implementor's note: It is an empirical matter91* whether ComparableTimSort offers any performance benefit over92* TimSort used with this comparator. If not, you are better off93* deleting or bypassing ComparableTimSort. There is currently no94* empirical case for separating them for parallel sorting, so all95* public Object parallelSort methods use the same comparator96* based implementation.97*/98static final class NaturalOrder implements Comparator<Object> {99@SuppressWarnings("unchecked")100public int compare(Object first, Object second) {101return ((Comparable<Object>)first).compareTo(second);102}103static final NaturalOrder INSTANCE = new NaturalOrder();104}105106/**107* Checks that {@code fromIndex} and {@code toIndex} are in108* the range and throws an exception if they aren't.109*/110private static void rangeCheck(int arrayLength, int fromIndex, int toIndex) {111if (fromIndex > toIndex) {112throw new IllegalArgumentException(113"fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");114}115if (fromIndex < 0) {116throw new ArrayIndexOutOfBoundsException(fromIndex);117}118if (toIndex > arrayLength) {119throw new ArrayIndexOutOfBoundsException(toIndex);120}121}122123/*124* Sorting methods. Note that all public "sort" methods take the125* same form: Performing argument checks if necessary, and then126* expanding arguments into those required for the internal127* implementation methods residing in other package-private128* classes (except for legacyMergeSort, included in this class).129*/130131/**132* Sorts the specified array into ascending numerical order.133*134* <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort135* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm136* offers O(n log(n)) performance on many data sets that cause other137* quicksorts to degrade to quadratic performance, and is typically138* faster than traditional (one-pivot) Quicksort implementations.139*140* @param a the array to be sorted141*/142public static void sort(int[] a) {143DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);144}145146/**147* Sorts the specified range of the array into ascending order. The range148* to be sorted extends from the index {@code fromIndex}, inclusive, to149* the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},150* the range to be sorted is empty.151*152* <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort153* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm154* offers O(n log(n)) performance on many data sets that cause other155* quicksorts to degrade to quadratic performance, and is typically156* faster than traditional (one-pivot) Quicksort implementations.157*158* @param a the array to be sorted159* @param fromIndex the index of the first element, inclusive, to be sorted160* @param toIndex the index of the last element, exclusive, to be sorted161*162* @throws IllegalArgumentException if {@code fromIndex > toIndex}163* @throws ArrayIndexOutOfBoundsException164* if {@code fromIndex < 0} or {@code toIndex > a.length}165*/166public static void sort(int[] a, int fromIndex, int toIndex) {167rangeCheck(a.length, fromIndex, toIndex);168DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);169}170171/**172* Sorts the specified array into ascending numerical order.173*174* <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort175* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm176* offers O(n log(n)) performance on many data sets that cause other177* quicksorts to degrade to quadratic performance, and is typically178* faster than traditional (one-pivot) Quicksort implementations.179*180* @param a the array to be sorted181*/182public static void sort(long[] a) {183DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);184}185186/**187* Sorts the specified range of the array into ascending order. The range188* to be sorted extends from the index {@code fromIndex}, inclusive, to189* the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},190* the range to be sorted is empty.191*192* <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort193* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm194* offers O(n log(n)) performance on many data sets that cause other195* quicksorts to degrade to quadratic performance, and is typically196* faster than traditional (one-pivot) Quicksort implementations.197*198* @param a the array to be sorted199* @param fromIndex the index of the first element, inclusive, to be sorted200* @param toIndex the index of the last element, exclusive, to be sorted201*202* @throws IllegalArgumentException if {@code fromIndex > toIndex}203* @throws ArrayIndexOutOfBoundsException204* if {@code fromIndex < 0} or {@code toIndex > a.length}205*/206public static void sort(long[] a, int fromIndex, int toIndex) {207rangeCheck(a.length, fromIndex, toIndex);208DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);209}210211/**212* Sorts the specified array into ascending numerical order.213*214* <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort215* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm216* offers O(n log(n)) performance on many data sets that cause other217* quicksorts to degrade to quadratic performance, and is typically218* faster than traditional (one-pivot) Quicksort implementations.219*220* @param a the array to be sorted221*/222public static void sort(short[] a) {223DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);224}225226/**227* Sorts the specified range of the array into ascending order. The range228* to be sorted extends from the index {@code fromIndex}, inclusive, to229* the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},230* the range to be sorted is empty.231*232* <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort233* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm234* offers O(n log(n)) performance on many data sets that cause other235* quicksorts to degrade to quadratic performance, and is typically236* faster than traditional (one-pivot) Quicksort implementations.237*238* @param a the array to be sorted239* @param fromIndex the index of the first element, inclusive, to be sorted240* @param toIndex the index of the last element, exclusive, to be sorted241*242* @throws IllegalArgumentException if {@code fromIndex > toIndex}243* @throws ArrayIndexOutOfBoundsException244* if {@code fromIndex < 0} or {@code toIndex > a.length}245*/246public static void sort(short[] a, int fromIndex, int toIndex) {247rangeCheck(a.length, fromIndex, toIndex);248DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);249}250251/**252* Sorts the specified array into ascending numerical order.253*254* <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort255* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm256* offers O(n log(n)) performance on many data sets that cause other257* quicksorts to degrade to quadratic performance, and is typically258* faster than traditional (one-pivot) Quicksort implementations.259*260* @param a the array to be sorted261*/262public static void sort(char[] a) {263DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);264}265266/**267* Sorts the specified range of the array into ascending order. The range268* to be sorted extends from the index {@code fromIndex}, inclusive, to269* the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},270* the range to be sorted is empty.271*272* <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort273* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm274* offers O(n log(n)) performance on many data sets that cause other275* quicksorts to degrade to quadratic performance, and is typically276* faster than traditional (one-pivot) Quicksort implementations.277*278* @param a the array to be sorted279* @param fromIndex the index of the first element, inclusive, to be sorted280* @param toIndex the index of the last element, exclusive, to be sorted281*282* @throws IllegalArgumentException if {@code fromIndex > toIndex}283* @throws ArrayIndexOutOfBoundsException284* if {@code fromIndex < 0} or {@code toIndex > a.length}285*/286public static void sort(char[] a, int fromIndex, int toIndex) {287rangeCheck(a.length, fromIndex, toIndex);288DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);289}290291/**292* Sorts the specified array into ascending numerical order.293*294* <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort295* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm296* offers O(n log(n)) performance on many data sets that cause other297* quicksorts to degrade to quadratic performance, and is typically298* faster than traditional (one-pivot) Quicksort implementations.299*300* @param a the array to be sorted301*/302public static void sort(byte[] a) {303DualPivotQuicksort.sort(a, 0, a.length - 1);304}305306/**307* Sorts the specified range of the array into ascending order. The range308* to be sorted extends from the index {@code fromIndex}, inclusive, to309* the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},310* the range to be sorted is empty.311*312* <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort313* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm314* offers O(n log(n)) performance on many data sets that cause other315* quicksorts to degrade to quadratic performance, and is typically316* faster than traditional (one-pivot) Quicksort implementations.317*318* @param a the array to be sorted319* @param fromIndex the index of the first element, inclusive, to be sorted320* @param toIndex the index of the last element, exclusive, to be sorted321*322* @throws IllegalArgumentException if {@code fromIndex > toIndex}323* @throws ArrayIndexOutOfBoundsException324* if {@code fromIndex < 0} or {@code toIndex > a.length}325*/326public static void sort(byte[] a, int fromIndex, int toIndex) {327rangeCheck(a.length, fromIndex, toIndex);328DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);329}330331/**332* Sorts the specified array into ascending numerical order.333*334* <p>The {@code <} relation does not provide a total order on all float335* values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}336* value compares neither less than, greater than, nor equal to any value,337* even itself. This method uses the total order imposed by the method338* {@link Float#compareTo}: {@code -0.0f} is treated as less than value339* {@code 0.0f} and {@code Float.NaN} is considered greater than any340* other value and all {@code Float.NaN} values are considered equal.341*342* <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort343* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm344* offers O(n log(n)) performance on many data sets that cause other345* quicksorts to degrade to quadratic performance, and is typically346* faster than traditional (one-pivot) Quicksort implementations.347*348* @param a the array to be sorted349*/350public static void sort(float[] a) {351DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);352}353354/**355* Sorts the specified range of the array into ascending order. The range356* to be sorted extends from the index {@code fromIndex}, inclusive, to357* 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 float361* values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.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 method364* {@link Float#compareTo}: {@code -0.0f} is treated as less than value365* {@code 0.0f} and {@code Float.NaN} is considered greater than any366* other value and all {@code Float.NaN} values are considered equal.367*368* <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort369* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm370* offers O(n log(n)) performance on many data sets that cause other371* quicksorts to degrade to quadratic performance, and is typically372* faster than traditional (one-pivot) Quicksort implementations.373*374* @param a the array to be sorted375* @param fromIndex the index of the first element, inclusive, to be sorted376* @param toIndex the index of the last element, exclusive, to be sorted377*378* @throws IllegalArgumentException if {@code fromIndex > toIndex}379* @throws ArrayIndexOutOfBoundsException380* if {@code fromIndex < 0} or {@code toIndex > a.length}381*/382public static void sort(float[] a, int fromIndex, int toIndex) {383rangeCheck(a.length, fromIndex, toIndex);384DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);385}386387/**388* Sorts the specified array into ascending numerical order.389*390* <p>The {@code <} relation does not provide a total order on all double391* values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}392* value compares neither less than, greater than, nor equal to any value,393* even itself. This method uses the total order imposed by the method394* {@link Double#compareTo}: {@code -0.0d} is treated as less than value395* {@code 0.0d} and {@code Double.NaN} is considered greater than any396* other value and all {@code Double.NaN} values are considered equal.397*398* <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort399* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm400* offers O(n log(n)) performance on many data sets that cause other401* quicksorts to degrade to quadratic performance, and is typically402* faster than traditional (one-pivot) Quicksort implementations.403*404* @param a the array to be sorted405*/406public static void sort(double[] a) {407DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);408}409410/**411* Sorts the specified range of the array into ascending order. The range412* to be sorted extends from the index {@code fromIndex}, inclusive, to413* the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},414* the range to be sorted is empty.415*416* <p>The {@code <} relation does not provide a total order on all double417* values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}418* value compares neither less than, greater than, nor equal to any value,419* even itself. This method uses the total order imposed by the method420* {@link Double#compareTo}: {@code -0.0d} is treated as less than value421* {@code 0.0d} and {@code Double.NaN} is considered greater than any422* other value and all {@code Double.NaN} values are considered equal.423*424* <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort425* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm426* offers O(n log(n)) performance on many data sets that cause other427* quicksorts to degrade to quadratic performance, and is typically428* faster than traditional (one-pivot) Quicksort implementations.429*430* @param a the array to be sorted431* @param fromIndex the index of the first element, inclusive, to be sorted432* @param toIndex the index of the last element, exclusive, to be sorted433*434* @throws IllegalArgumentException if {@code fromIndex > toIndex}435* @throws ArrayIndexOutOfBoundsException436* if {@code fromIndex < 0} or {@code toIndex > a.length}437*/438public static void sort(double[] a, int fromIndex, int toIndex) {439rangeCheck(a.length, fromIndex, toIndex);440DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);441}442443/**444* Sorts the specified array into ascending numerical order.445*446* @implNote The sorting algorithm is a parallel sort-merge that breaks the447* array into sub-arrays that are themselves sorted and then merged. When448* the sub-array length reaches a minimum granularity, the sub-array is449* sorted using the appropriate {@link Arrays#sort(byte[]) Arrays.sort}450* method. If the length of the specified array is less than the minimum451* granularity, then it is sorted using the appropriate {@link452* Arrays#sort(byte[]) Arrays.sort} method. The algorithm requires a453* working space no greater than the size of the original array. The454* {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to455* execute any parallel tasks.456*457* @param a the array to be sorted458*459* @since 1.8460*/461public static void parallelSort(byte[] a) {462int n = a.length, p, g;463if (n <= MIN_ARRAY_SORT_GRAN ||464(p = ForkJoinPool.getCommonPoolParallelism()) == 1)465DualPivotQuicksort.sort(a, 0, n - 1);466else467new ArraysParallelSortHelpers.FJByte.Sorter468(null, a, new byte[n], 0, n, 0,469((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?470MIN_ARRAY_SORT_GRAN : g).invoke();471}472473/**474* Sorts the specified range of the array into ascending numerical order.475* The range to be sorted extends from the index {@code fromIndex},476* inclusive, to the index {@code toIndex}, exclusive. If477* {@code fromIndex == toIndex}, the range to be sorted is empty.478*479* @implNote The sorting algorithm is a parallel sort-merge that breaks the480* array into sub-arrays that are themselves sorted and then merged. When481* the sub-array length reaches a minimum granularity, the sub-array is482* sorted using the appropriate {@link Arrays#sort(byte[]) Arrays.sort}483* method. If the length of the specified array is less than the minimum484* granularity, then it is sorted using the appropriate {@link485* Arrays#sort(byte[]) Arrays.sort} method. The algorithm requires a working486* space no greater than the size of the specified range of the original487* array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is488* used to execute any parallel tasks.489*490* @param a the array to be sorted491* @param fromIndex the index of the first element, inclusive, to be sorted492* @param toIndex the index of the last element, exclusive, to be sorted493*494* @throws IllegalArgumentException if {@code fromIndex > toIndex}495* @throws ArrayIndexOutOfBoundsException496* if {@code fromIndex < 0} or {@code toIndex > a.length}497*498* @since 1.8499*/500public static void parallelSort(byte[] a, int fromIndex, int toIndex) {501rangeCheck(a.length, fromIndex, toIndex);502int n = toIndex - fromIndex, p, g;503if (n <= MIN_ARRAY_SORT_GRAN ||504(p = ForkJoinPool.getCommonPoolParallelism()) == 1)505DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);506else507new ArraysParallelSortHelpers.FJByte.Sorter508(null, a, new byte[n], fromIndex, n, 0,509((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?510MIN_ARRAY_SORT_GRAN : g).invoke();511}512513/**514* Sorts the specified array into ascending numerical order.515*516* @implNote The sorting algorithm is a parallel sort-merge that breaks the517* array into sub-arrays that are themselves sorted and then merged. When518* the sub-array length reaches a minimum granularity, the sub-array is519* sorted using the appropriate {@link Arrays#sort(char[]) Arrays.sort}520* method. If the length of the specified array is less than the minimum521* granularity, then it is sorted using the appropriate {@link522* Arrays#sort(char[]) Arrays.sort} method. The algorithm requires a523* working space no greater than the size of the original array. The524* {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to525* execute any parallel tasks.526*527* @param a the array to be sorted528*529* @since 1.8530*/531public static void parallelSort(char[] a) {532int n = a.length, p, g;533if (n <= MIN_ARRAY_SORT_GRAN ||534(p = ForkJoinPool.getCommonPoolParallelism()) == 1)535DualPivotQuicksort.sort(a, 0, n - 1, null, 0, 0);536else537new ArraysParallelSortHelpers.FJChar.Sorter538(null, a, new char[n], 0, n, 0,539((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?540MIN_ARRAY_SORT_GRAN : g).invoke();541}542543/**544* Sorts the specified range of the array into ascending numerical order.545* The range to be sorted extends from the index {@code fromIndex},546* inclusive, to the index {@code toIndex}, exclusive. If547* {@code fromIndex == toIndex}, the range to be sorted is empty.548*549@implNote The sorting algorithm is a parallel sort-merge that breaks the550* array into sub-arrays that are themselves sorted and then merged. When551* the sub-array length reaches a minimum granularity, the sub-array is552* sorted using the appropriate {@link Arrays#sort(char[]) Arrays.sort}553* method. If the length of the specified array is less than the minimum554* granularity, then it is sorted using the appropriate {@link555* Arrays#sort(char[]) Arrays.sort} method. The algorithm requires a working556* space no greater than the size of the specified range of the original557* array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is558* used to execute any parallel tasks.559*560* @param a the array to be sorted561* @param fromIndex the index of the first element, inclusive, to be sorted562* @param toIndex the index of the last element, exclusive, to be sorted563*564* @throws IllegalArgumentException if {@code fromIndex > toIndex}565* @throws ArrayIndexOutOfBoundsException566* if {@code fromIndex < 0} or {@code toIndex > a.length}567*568* @since 1.8569*/570public static void parallelSort(char[] a, int fromIndex, int toIndex) {571rangeCheck(a.length, fromIndex, toIndex);572int n = toIndex - fromIndex, p, g;573if (n <= MIN_ARRAY_SORT_GRAN ||574(p = ForkJoinPool.getCommonPoolParallelism()) == 1)575DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);576else577new ArraysParallelSortHelpers.FJChar.Sorter578(null, a, new char[n], fromIndex, n, 0,579((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?580MIN_ARRAY_SORT_GRAN : g).invoke();581}582583/**584* Sorts the specified array into ascending numerical order.585*586* @implNote The sorting algorithm is a parallel sort-merge that breaks the587* array into sub-arrays that are themselves sorted and then merged. When588* the sub-array length reaches a minimum granularity, the sub-array is589* sorted using the appropriate {@link Arrays#sort(short[]) Arrays.sort}590* method. If the length of the specified array is less than the minimum591* granularity, then it is sorted using the appropriate {@link592* Arrays#sort(short[]) Arrays.sort} method. The algorithm requires a593* working space no greater than the size of the original array. The594* {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to595* execute any parallel tasks.596*597* @param a the array to be sorted598*599* @since 1.8600*/601public static void parallelSort(short[] a) {602int n = a.length, p, g;603if (n <= MIN_ARRAY_SORT_GRAN ||604(p = ForkJoinPool.getCommonPoolParallelism()) == 1)605DualPivotQuicksort.sort(a, 0, n - 1, null, 0, 0);606else607new ArraysParallelSortHelpers.FJShort.Sorter608(null, a, new short[n], 0, n, 0,609((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?610MIN_ARRAY_SORT_GRAN : g).invoke();611}612613/**614* Sorts the specified range of the array into ascending numerical order.615* The range to be sorted extends from the index {@code fromIndex},616* inclusive, to the index {@code toIndex}, exclusive. If617* {@code fromIndex == toIndex}, the range to be sorted is empty.618*619* @implNote The sorting algorithm is a parallel sort-merge that breaks the620* array into sub-arrays that are themselves sorted and then merged. When621* the sub-array length reaches a minimum granularity, the sub-array is622* sorted using the appropriate {@link Arrays#sort(short[]) Arrays.sort}623* method. If the length of the specified array is less than the minimum624* granularity, then it is sorted using the appropriate {@link625* Arrays#sort(short[]) Arrays.sort} method. The algorithm requires a working626* space no greater than the size of the specified range of the original627* array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is628* used to execute any parallel tasks.629*630* @param a the array to be sorted631* @param fromIndex the index of the first element, inclusive, to be sorted632* @param toIndex the index of the last element, exclusive, to be sorted633*634* @throws IllegalArgumentException if {@code fromIndex > toIndex}635* @throws ArrayIndexOutOfBoundsException636* if {@code fromIndex < 0} or {@code toIndex > a.length}637*638* @since 1.8639*/640public static void parallelSort(short[] a, int fromIndex, int toIndex) {641rangeCheck(a.length, fromIndex, toIndex);642int n = toIndex - fromIndex, p, g;643if (n <= MIN_ARRAY_SORT_GRAN ||644(p = ForkJoinPool.getCommonPoolParallelism()) == 1)645DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);646else647new ArraysParallelSortHelpers.FJShort.Sorter648(null, a, new short[n], fromIndex, n, 0,649((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?650MIN_ARRAY_SORT_GRAN : g).invoke();651}652653/**654* Sorts the specified array into ascending numerical order.655*656* @implNote The sorting algorithm is a parallel sort-merge that breaks the657* array into sub-arrays that are themselves sorted and then merged. When658* the sub-array length reaches a minimum granularity, the sub-array is659* sorted using the appropriate {@link Arrays#sort(int[]) Arrays.sort}660* method. If the length of the specified array is less than the minimum661* granularity, then it is sorted using the appropriate {@link662* Arrays#sort(int[]) Arrays.sort} method. The algorithm requires a663* working space no greater than the size of the original array. The664* {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to665* execute any parallel tasks.666*667* @param a the array to be sorted668*669* @since 1.8670*/671public static void parallelSort(int[] a) {672int n = a.length, p, g;673if (n <= MIN_ARRAY_SORT_GRAN ||674(p = ForkJoinPool.getCommonPoolParallelism()) == 1)675DualPivotQuicksort.sort(a, 0, n - 1, null, 0, 0);676else677new ArraysParallelSortHelpers.FJInt.Sorter678(null, a, new int[n], 0, n, 0,679((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?680MIN_ARRAY_SORT_GRAN : g).invoke();681}682683/**684* Sorts the specified range of the array into ascending numerical order.685* The range to be sorted extends from the index {@code fromIndex},686* inclusive, to the index {@code toIndex}, exclusive. If687* {@code fromIndex == toIndex}, the range to be sorted is empty.688*689* @implNote The sorting algorithm is a parallel sort-merge that breaks the690* array into sub-arrays that are themselves sorted and then merged. When691* the sub-array length reaches a minimum granularity, the sub-array is692* sorted using the appropriate {@link Arrays#sort(int[]) Arrays.sort}693* method. If the length of the specified array is less than the minimum694* granularity, then it is sorted using the appropriate {@link695* Arrays#sort(int[]) Arrays.sort} method. The algorithm requires a working696* space no greater than the size of the specified range of the original697* array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is698* used to execute any parallel tasks.699*700* @param a the array to be sorted701* @param fromIndex the index of the first element, inclusive, to be sorted702* @param toIndex the index of the last element, exclusive, to be sorted703*704* @throws IllegalArgumentException if {@code fromIndex > toIndex}705* @throws ArrayIndexOutOfBoundsException706* if {@code fromIndex < 0} or {@code toIndex > a.length}707*708* @since 1.8709*/710public static void parallelSort(int[] a, int fromIndex, int toIndex) {711rangeCheck(a.length, fromIndex, toIndex);712int n = toIndex - fromIndex, p, g;713if (n <= MIN_ARRAY_SORT_GRAN ||714(p = ForkJoinPool.getCommonPoolParallelism()) == 1)715DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);716else717new ArraysParallelSortHelpers.FJInt.Sorter718(null, a, new int[n], fromIndex, n, 0,719((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?720MIN_ARRAY_SORT_GRAN : g).invoke();721}722723/**724* Sorts the specified array into ascending numerical order.725*726* @implNote The sorting algorithm is a parallel sort-merge that breaks the727* array into sub-arrays that are themselves sorted and then merged. When728* the sub-array length reaches a minimum granularity, the sub-array is729* sorted using the appropriate {@link Arrays#sort(long[]) Arrays.sort}730* method. If the length of the specified array is less than the minimum731* granularity, then it is sorted using the appropriate {@link732* Arrays#sort(long[]) Arrays.sort} method. The algorithm requires a733* working space no greater than the size of the original array. The734* {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to735* execute any parallel tasks.736*737* @param a the array to be sorted738*739* @since 1.8740*/741public static void parallelSort(long[] a) {742int n = a.length, p, g;743if (n <= MIN_ARRAY_SORT_GRAN ||744(p = ForkJoinPool.getCommonPoolParallelism()) == 1)745DualPivotQuicksort.sort(a, 0, n - 1, null, 0, 0);746else747new ArraysParallelSortHelpers.FJLong.Sorter748(null, a, new long[n], 0, n, 0,749((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?750MIN_ARRAY_SORT_GRAN : g).invoke();751}752753/**754* Sorts the specified range of the array into ascending numerical order.755* The range to be sorted extends from the index {@code fromIndex},756* inclusive, to the index {@code toIndex}, exclusive. If757* {@code fromIndex == toIndex}, the range to be sorted is empty.758*759* @implNote The sorting algorithm is a parallel sort-merge that breaks the760* array into sub-arrays that are themselves sorted and then merged. When761* the sub-array length reaches a minimum granularity, the sub-array is762* sorted using the appropriate {@link Arrays#sort(long[]) Arrays.sort}763* method. If the length of the specified array is less than the minimum764* granularity, then it is sorted using the appropriate {@link765* Arrays#sort(long[]) Arrays.sort} method. The algorithm requires a working766* space no greater than the size of the specified range of the original767* array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is768* used to execute any parallel tasks.769*770* @param a the array to be sorted771* @param fromIndex the index of the first element, inclusive, to be sorted772* @param toIndex the index of the last element, exclusive, to be sorted773*774* @throws IllegalArgumentException if {@code fromIndex > toIndex}775* @throws ArrayIndexOutOfBoundsException776* if {@code fromIndex < 0} or {@code toIndex > a.length}777*778* @since 1.8779*/780public static void parallelSort(long[] a, int fromIndex, int toIndex) {781rangeCheck(a.length, fromIndex, toIndex);782int n = toIndex - fromIndex, p, g;783if (n <= MIN_ARRAY_SORT_GRAN ||784(p = ForkJoinPool.getCommonPoolParallelism()) == 1)785DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);786else787new ArraysParallelSortHelpers.FJLong.Sorter788(null, a, new long[n], fromIndex, n, 0,789((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?790MIN_ARRAY_SORT_GRAN : g).invoke();791}792793/**794* Sorts the specified array into ascending numerical order.795*796* <p>The {@code <} relation does not provide a total order on all float797* values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}798* value compares neither less than, greater than, nor equal to any value,799* even itself. This method uses the total order imposed by the method800* {@link Float#compareTo}: {@code -0.0f} is treated as less than value801* {@code 0.0f} and {@code Float.NaN} is considered greater than any802* other value and all {@code Float.NaN} values are considered equal.803*804* @implNote The sorting algorithm is a parallel sort-merge that breaks the805* array into sub-arrays that are themselves sorted and then merged. When806* the sub-array length reaches a minimum granularity, the sub-array is807* sorted using the appropriate {@link Arrays#sort(float[]) Arrays.sort}808* method. If the length of the specified array is less than the minimum809* granularity, then it is sorted using the appropriate {@link810* Arrays#sort(float[]) Arrays.sort} method. The algorithm requires a811* working space no greater than the size of the original array. The812* {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to813* execute any parallel tasks.814*815* @param a the array to be sorted816*817* @since 1.8818*/819public static void parallelSort(float[] a) {820int n = a.length, p, g;821if (n <= MIN_ARRAY_SORT_GRAN ||822(p = ForkJoinPool.getCommonPoolParallelism()) == 1)823DualPivotQuicksort.sort(a, 0, n - 1, null, 0, 0);824else825new ArraysParallelSortHelpers.FJFloat.Sorter826(null, a, new float[n], 0, n, 0,827((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?828MIN_ARRAY_SORT_GRAN : g).invoke();829}830831/**832* Sorts the specified range of the array into ascending numerical order.833* The range to be sorted extends from the index {@code fromIndex},834* inclusive, to the index {@code toIndex}, exclusive. If835* {@code fromIndex == toIndex}, the range to be sorted is empty.836*837* <p>The {@code <} relation does not provide a total order on all float838* values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}839* value compares neither less than, greater than, nor equal to any value,840* even itself. This method uses the total order imposed by the method841* {@link Float#compareTo}: {@code -0.0f} is treated as less than value842* {@code 0.0f} and {@code Float.NaN} is considered greater than any843* other value and all {@code Float.NaN} values are considered equal.844*845* @implNote The sorting algorithm is a parallel sort-merge that breaks the846* array into sub-arrays that are themselves sorted and then merged. When847* the sub-array length reaches a minimum granularity, the sub-array is848* sorted using the appropriate {@link Arrays#sort(float[]) Arrays.sort}849* method. If the length of the specified array is less than the minimum850* granularity, then it is sorted using the appropriate {@link851* Arrays#sort(float[]) Arrays.sort} method. The algorithm requires a working852* space no greater than the size of the specified range of the original853* array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is854* used to execute any parallel tasks.855*856* @param a the array to be sorted857* @param fromIndex the index of the first element, inclusive, to be sorted858* @param toIndex the index of the last element, exclusive, to be sorted859*860* @throws IllegalArgumentException if {@code fromIndex > toIndex}861* @throws ArrayIndexOutOfBoundsException862* if {@code fromIndex < 0} or {@code toIndex > a.length}863*864* @since 1.8865*/866public static void parallelSort(float[] a, int fromIndex, int toIndex) {867rangeCheck(a.length, fromIndex, toIndex);868int n = toIndex - fromIndex, p, g;869if (n <= MIN_ARRAY_SORT_GRAN ||870(p = ForkJoinPool.getCommonPoolParallelism()) == 1)871DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);872else873new ArraysParallelSortHelpers.FJFloat.Sorter874(null, a, new float[n], fromIndex, n, 0,875((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?876MIN_ARRAY_SORT_GRAN : g).invoke();877}878879/**880* Sorts the specified array into ascending numerical order.881*882* <p>The {@code <} relation does not provide a total order on all double883* values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}884* value compares neither less than, greater than, nor equal to any value,885* even itself. This method uses the total order imposed by the method886* {@link Double#compareTo}: {@code -0.0d} is treated as less than value887* {@code 0.0d} and {@code Double.NaN} is considered greater than any888* other value and all {@code Double.NaN} values are considered equal.889*890* @implNote The sorting algorithm is a parallel sort-merge that breaks the891* array into sub-arrays that are themselves sorted and then merged. When892* the sub-array length reaches a minimum granularity, the sub-array is893* sorted using the appropriate {@link Arrays#sort(double[]) Arrays.sort}894* method. If the length of the specified array is less than the minimum895* granularity, then it is sorted using the appropriate {@link896* Arrays#sort(double[]) Arrays.sort} method. The algorithm requires a897* working space no greater than the size of the original array. The898* {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to899* execute any parallel tasks.900*901* @param a the array to be sorted902*903* @since 1.8904*/905public static void parallelSort(double[] a) {906int n = a.length, p, g;907if (n <= MIN_ARRAY_SORT_GRAN ||908(p = ForkJoinPool.getCommonPoolParallelism()) == 1)909DualPivotQuicksort.sort(a, 0, n - 1, null, 0, 0);910else911new ArraysParallelSortHelpers.FJDouble.Sorter912(null, a, new double[n], 0, n, 0,913((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?914MIN_ARRAY_SORT_GRAN : g).invoke();915}916917/**918* Sorts the specified range of the array into ascending numerical order.919* The range to be sorted extends from the index {@code fromIndex},920* inclusive, to the index {@code toIndex}, exclusive. If921* {@code fromIndex == toIndex}, the range to be sorted is empty.922*923* <p>The {@code <} relation does not provide a total order on all double924* values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}925* value compares neither less than, greater than, nor equal to any value,926* even itself. This method uses the total order imposed by the method927* {@link Double#compareTo}: {@code -0.0d} is treated as less than value928* {@code 0.0d} and {@code Double.NaN} is considered greater than any929* other value and all {@code Double.NaN} values are considered equal.930*931* @implNote The sorting algorithm is a parallel sort-merge that breaks the932* array into sub-arrays that are themselves sorted and then merged. When933* the sub-array length reaches a minimum granularity, the sub-array is934* sorted using the appropriate {@link Arrays#sort(double[]) Arrays.sort}935* method. If the length of the specified array is less than the minimum936* granularity, then it is sorted using the appropriate {@link937* Arrays#sort(double[]) Arrays.sort} method. The algorithm requires a working938* space no greater than the size of the specified range of the original939* array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is940* used to execute any parallel tasks.941*942* @param a the array to be sorted943* @param fromIndex the index of the first element, inclusive, to be sorted944* @param toIndex the index of the last element, exclusive, to be sorted945*946* @throws IllegalArgumentException if {@code fromIndex > toIndex}947* @throws ArrayIndexOutOfBoundsException948* if {@code fromIndex < 0} or {@code toIndex > a.length}949*950* @since 1.8951*/952public static void parallelSort(double[] a, int fromIndex, int toIndex) {953rangeCheck(a.length, fromIndex, toIndex);954int n = toIndex - fromIndex, p, g;955if (n <= MIN_ARRAY_SORT_GRAN ||956(p = ForkJoinPool.getCommonPoolParallelism()) == 1)957DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);958else959new ArraysParallelSortHelpers.FJDouble.Sorter960(null, a, new double[n], fromIndex, n, 0,961((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?962MIN_ARRAY_SORT_GRAN : g).invoke();963}964965/**966* Sorts the specified array of objects into ascending order, according967* to the {@linkplain Comparable natural ordering} of its elements.968* All elements in the array must implement the {@link Comparable}969* interface. Furthermore, all elements in the array must be970* <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)} must971* not throw a {@code ClassCastException} for any elements {@code e1}972* and {@code e2} in the array).973*974* <p>This sort is guaranteed to be <i>stable</i>: equal elements will975* not be reordered as a result of the sort.976*977* @implNote The sorting algorithm is a parallel sort-merge that breaks the978* array into sub-arrays that are themselves sorted and then merged. When979* the sub-array length reaches a minimum granularity, the sub-array is980* sorted using the appropriate {@link Arrays#sort(Object[]) Arrays.sort}981* method. If the length of the specified array is less than the minimum982* granularity, then it is sorted using the appropriate {@link983* Arrays#sort(Object[]) Arrays.sort} method. The algorithm requires a984* working space no greater than the size of the original array. The985* {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to986* execute any parallel tasks.987*988* @param <T> the class of the objects to be sorted989* @param a the array to be sorted990*991* @throws ClassCastException if the array contains elements that are not992* <i>mutually comparable</i> (for example, strings and integers)993* @throws IllegalArgumentException (optional) if the natural994* ordering of the array elements is found to violate the995* {@link Comparable} contract996*997* @since 1.8998*/999@SuppressWarnings("unchecked")1000public static <T extends Comparable<? super T>> void parallelSort(T[] a) {1001int n = a.length, p, g;1002if (n <= MIN_ARRAY_SORT_GRAN ||1003(p = ForkJoinPool.getCommonPoolParallelism()) == 1)1004TimSort.sort(a, 0, n, NaturalOrder.INSTANCE, null, 0, 0);1005else1006new ArraysParallelSortHelpers.FJObject.Sorter<T>1007(null, a,1008(T[])Array.newInstance(a.getClass().getComponentType(), n),10090, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?1010MIN_ARRAY_SORT_GRAN : g, NaturalOrder.INSTANCE).invoke();1011}10121013/**1014* Sorts the specified range of the specified array of objects into1015* ascending order, according to the1016* {@linkplain Comparable natural ordering} of its1017* elements. The range to be sorted extends from index1018* {@code fromIndex}, inclusive, to index {@code toIndex}, exclusive.1019* (If {@code fromIndex==toIndex}, the range to be sorted is empty.) All1020* elements in this range must implement the {@link Comparable}1021* interface. Furthermore, all elements in this range must be <i>mutually1022* comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a1023* {@code ClassCastException} for any elements {@code e1} and1024* {@code e2} in the array).1025*1026* <p>This sort is guaranteed to be <i>stable</i>: equal elements will1027* not be reordered as a result of the sort.1028*1029* @implNote The sorting algorithm is a parallel sort-merge that breaks the1030* array into sub-arrays that are themselves sorted and then merged. When1031* the sub-array length reaches a minimum granularity, the sub-array is1032* sorted using the appropriate {@link Arrays#sort(Object[]) Arrays.sort}1033* method. If the length of the specified array is less than the minimum1034* granularity, then it is sorted using the appropriate {@link1035* Arrays#sort(Object[]) Arrays.sort} method. The algorithm requires a working1036* space no greater than the size of the specified range of the original1037* array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is1038* used to execute any parallel tasks.1039*1040* @param <T> the class of the objects to be sorted1041* @param a the array to be sorted1042* @param fromIndex the index of the first element (inclusive) to be1043* sorted1044* @param toIndex the index of the last element (exclusive) to be sorted1045* @throws IllegalArgumentException if {@code fromIndex > toIndex} or1046* (optional) if the natural ordering of the array elements is1047* found to violate the {@link Comparable} contract1048* @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or1049* {@code toIndex > a.length}1050* @throws ClassCastException if the array contains elements that are1051* not <i>mutually comparable</i> (for example, strings and1052* integers).1053*1054* @since 1.81055*/1056@SuppressWarnings("unchecked")1057public static <T extends Comparable<? super T>>1058void parallelSort(T[] a, int fromIndex, int toIndex) {1059rangeCheck(a.length, fromIndex, toIndex);1060int n = toIndex - fromIndex, p, g;1061if (n <= MIN_ARRAY_SORT_GRAN ||1062(p = ForkJoinPool.getCommonPoolParallelism()) == 1)1063TimSort.sort(a, fromIndex, toIndex, NaturalOrder.INSTANCE, null, 0, 0);1064else1065new ArraysParallelSortHelpers.FJObject.Sorter<T>1066(null, a,1067(T[])Array.newInstance(a.getClass().getComponentType(), n),1068fromIndex, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?1069MIN_ARRAY_SORT_GRAN : g, NaturalOrder.INSTANCE).invoke();1070}10711072/**1073* Sorts the specified array of objects according to the order induced by1074* the specified comparator. All elements in the array must be1075* <i>mutually comparable</i> by the specified comparator (that is,1076* {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}1077* for any elements {@code e1} and {@code e2} in the array).1078*1079* <p>This sort is guaranteed to be <i>stable</i>: equal elements will1080* not be reordered as a result of the sort.1081*1082* @implNote The sorting algorithm is a parallel sort-merge that breaks the1083* array into sub-arrays that are themselves sorted and then merged. When1084* the sub-array length reaches a minimum granularity, the sub-array is1085* sorted using the appropriate {@link Arrays#sort(Object[]) Arrays.sort}1086* method. If the length of the specified array is less than the minimum1087* granularity, then it is sorted using the appropriate {@link1088* Arrays#sort(Object[]) Arrays.sort} method. The algorithm requires a1089* working space no greater than the size of the original array. The1090* {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to1091* execute any parallel tasks.1092*1093* @param <T> the class of the objects to be sorted1094* @param a the array to be sorted1095* @param cmp the comparator to determine the order of the array. A1096* {@code null} value indicates that the elements'1097* {@linkplain Comparable natural ordering} should be used.1098* @throws ClassCastException if the array contains elements that are1099* not <i>mutually comparable</i> using the specified comparator1100* @throws IllegalArgumentException (optional) if the comparator is1101* found to violate the {@link java.util.Comparator} contract1102*1103* @since 1.81104*/1105@SuppressWarnings("unchecked")1106public static <T> void parallelSort(T[] a, Comparator<? super T> cmp) {1107if (cmp == null)1108cmp = NaturalOrder.INSTANCE;1109int n = a.length, p, g;1110if (n <= MIN_ARRAY_SORT_GRAN ||1111(p = ForkJoinPool.getCommonPoolParallelism()) == 1)1112TimSort.sort(a, 0, n, cmp, null, 0, 0);1113else1114new ArraysParallelSortHelpers.FJObject.Sorter<T>1115(null, a,1116(T[])Array.newInstance(a.getClass().getComponentType(), n),11170, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?1118MIN_ARRAY_SORT_GRAN : g, cmp).invoke();1119}11201121/**1122* Sorts the specified range of the specified array of objects according1123* to the order induced by the specified comparator. The range to be1124* sorted extends from index {@code fromIndex}, inclusive, to index1125* {@code toIndex}, exclusive. (If {@code fromIndex==toIndex}, the1126* range to be sorted is empty.) All elements in the range must be1127* <i>mutually comparable</i> by the specified comparator (that is,1128* {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}1129* for any elements {@code e1} and {@code e2} in the range).1130*1131* <p>This sort is guaranteed to be <i>stable</i>: equal elements will1132* not be reordered as a result of the sort.1133*1134* @implNote The sorting algorithm is a parallel sort-merge that breaks the1135* array into sub-arrays that are themselves sorted and then merged. When1136* the sub-array length reaches a minimum granularity, the sub-array is1137* sorted using the appropriate {@link Arrays#sort(Object[]) Arrays.sort}1138* method. If the length of the specified array is less than the minimum1139* granularity, then it is sorted using the appropriate {@link1140* Arrays#sort(Object[]) Arrays.sort} method. The algorithm requires a working1141* space no greater than the size of the specified range of the original1142* array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is1143* used to execute any parallel tasks.1144*1145* @param <T> the class of the objects to be sorted1146* @param a the array to be sorted1147* @param fromIndex the index of the first element (inclusive) to be1148* sorted1149* @param toIndex the index of the last element (exclusive) to be sorted1150* @param cmp the comparator to determine the order of the array. A1151* {@code null} value indicates that the elements'1152* {@linkplain Comparable natural ordering} should be used.1153* @throws IllegalArgumentException if {@code fromIndex > toIndex} or1154* (optional) if the natural ordering of the array elements is1155* found to violate the {@link Comparable} contract1156* @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or1157* {@code toIndex > a.length}1158* @throws ClassCastException if the array contains elements that are1159* not <i>mutually comparable</i> (for example, strings and1160* integers).1161*1162* @since 1.81163*/1164@SuppressWarnings("unchecked")1165public static <T> void parallelSort(T[] a, int fromIndex, int toIndex,1166Comparator<? super T> cmp) {1167rangeCheck(a.length, fromIndex, toIndex);1168if (cmp == null)1169cmp = NaturalOrder.INSTANCE;1170int n = toIndex - fromIndex, p, g;1171if (n <= MIN_ARRAY_SORT_GRAN ||1172(p = ForkJoinPool.getCommonPoolParallelism()) == 1)1173TimSort.sort(a, fromIndex, toIndex, cmp, null, 0, 0);1174else1175new ArraysParallelSortHelpers.FJObject.Sorter<T>1176(null, a,1177(T[])Array.newInstance(a.getClass().getComponentType(), n),1178fromIndex, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?1179MIN_ARRAY_SORT_GRAN : g, cmp).invoke();1180}11811182/*1183* Sorting of complex type arrays.1184*/11851186/**1187* Old merge sort implementation can be selected (for1188* compatibility with broken comparators) using a system property.1189* Cannot be a static boolean in the enclosing class due to1190* circular dependencies. To be removed in a future release.1191*/1192static final class LegacyMergeSort {1193private static final boolean userRequested =1194java.security.AccessController.doPrivileged(1195new sun.security.action.GetBooleanAction(1196"java.util.Arrays.useLegacyMergeSort")).booleanValue();1197}11981199/**1200* Sorts the specified array of objects into ascending order, according1201* to the {@linkplain Comparable natural ordering} of its elements.1202* All elements in the array must implement the {@link Comparable}1203* interface. Furthermore, all elements in the array must be1204* <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)} must1205* not throw a {@code ClassCastException} for any elements {@code e1}1206* and {@code e2} in the array).1207*1208* <p>This sort is guaranteed to be <i>stable</i>: equal elements will1209* not be reordered as a result of the sort.1210*1211* <p>Implementation note: This implementation is a stable, adaptive,1212* iterative mergesort that requires far fewer than n lg(n) comparisons1213* when the input array is partially sorted, while offering the1214* performance of a traditional mergesort when the input array is1215* randomly ordered. If the input array is nearly sorted, the1216* implementation requires approximately n comparisons. Temporary1217* storage requirements vary from a small constant for nearly sorted1218* input arrays to n/2 object references for randomly ordered input1219* arrays.1220*1221* <p>The implementation takes equal advantage of ascending and1222* descending order in its input array, and can take advantage of1223* ascending and descending order in different parts of the the same1224* input array. It is well-suited to merging two or more sorted arrays:1225* simply concatenate the arrays and sort the resulting array.1226*1227* <p>The implementation was adapted from Tim Peters's list sort for Python1228* (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">1229* TimSort</a>). It uses techniques from Peter McIlroy's "Optimistic1230* Sorting and Information Theoretic Complexity", in Proceedings of the1231* Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,1232* January 1993.1233*1234* @param a the array to be sorted1235* @throws ClassCastException if the array contains elements that are not1236* <i>mutually comparable</i> (for example, strings and integers)1237* @throws IllegalArgumentException (optional) if the natural1238* ordering of the array elements is found to violate the1239* {@link Comparable} contract1240*/1241public static void sort(Object[] a) {1242if (LegacyMergeSort.userRequested)1243legacyMergeSort(a);1244else1245ComparableTimSort.sort(a, 0, a.length, null, 0, 0);1246}12471248/** To be removed in a future release. */1249private static void legacyMergeSort(Object[] a) {1250Object[] aux = a.clone();1251mergeSort(aux, a, 0, a.length, 0);1252}12531254/**1255* Sorts the specified range of the specified array of objects into1256* ascending order, according to the1257* {@linkplain Comparable natural ordering} of its1258* elements. The range to be sorted extends from index1259* {@code fromIndex}, inclusive, to index {@code toIndex}, exclusive.1260* (If {@code fromIndex==toIndex}, the range to be sorted is empty.) All1261* elements in this range must implement the {@link Comparable}1262* interface. Furthermore, all elements in this range must be <i>mutually1263* comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a1264* {@code ClassCastException} for any elements {@code e1} and1265* {@code e2} in the array).1266*1267* <p>This sort is guaranteed to be <i>stable</i>: equal elements will1268* not be reordered as a result of the sort.1269*1270* <p>Implementation note: This implementation is a stable, adaptive,1271* iterative mergesort that requires far fewer than n lg(n) comparisons1272* when the input array is partially sorted, while offering the1273* performance of a traditional mergesort when the input array is1274* randomly ordered. If the input array is nearly sorted, the1275* implementation requires approximately n comparisons. Temporary1276* storage requirements vary from a small constant for nearly sorted1277* input arrays to n/2 object references for randomly ordered input1278* arrays.1279*1280* <p>The implementation takes equal advantage of ascending and1281* descending order in its input array, and can take advantage of1282* ascending and descending order in different parts of the the same1283* input array. It is well-suited to merging two or more sorted arrays:1284* simply concatenate the arrays and sort the resulting array.1285*1286* <p>The implementation was adapted from Tim Peters's list sort for Python1287* (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">1288* TimSort</a>). It uses techniques from Peter McIlroy's "Optimistic1289* Sorting and Information Theoretic Complexity", in Proceedings of the1290* Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,1291* January 1993.1292*1293* @param a the array to be sorted1294* @param fromIndex the index of the first element (inclusive) to be1295* sorted1296* @param toIndex the index of the last element (exclusive) to be sorted1297* @throws IllegalArgumentException if {@code fromIndex > toIndex} or1298* (optional) if the natural ordering of the array elements is1299* found to violate the {@link Comparable} contract1300* @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or1301* {@code toIndex > a.length}1302* @throws ClassCastException if the array contains elements that are1303* not <i>mutually comparable</i> (for example, strings and1304* integers).1305*/1306public static void sort(Object[] a, int fromIndex, int toIndex) {1307rangeCheck(a.length, fromIndex, toIndex);1308if (LegacyMergeSort.userRequested)1309legacyMergeSort(a, fromIndex, toIndex);1310else1311ComparableTimSort.sort(a, fromIndex, toIndex, null, 0, 0);1312}13131314/** To be removed in a future release. */1315private static void legacyMergeSort(Object[] a,1316int fromIndex, int toIndex) {1317Object[] aux = copyOfRange(a, fromIndex, toIndex);1318mergeSort(aux, a, fromIndex, toIndex, -fromIndex);1319}13201321/**1322* Tuning parameter: list size at or below which insertion sort will be1323* used in preference to mergesort.1324* To be removed in a future release.1325*/1326private static final int INSERTIONSORT_THRESHOLD = 7;13271328/**1329* Src is the source array that starts at index 01330* Dest is the (possibly larger) array destination with a possible offset1331* low is the index in dest to start sorting1332* high is the end index in dest to end sorting1333* off is the offset to generate corresponding low, high in src1334* To be removed in a future release.1335*/1336@SuppressWarnings({"unchecked", "rawtypes"})1337private static void mergeSort(Object[] src,1338Object[] dest,1339int low,1340int high,1341int off) {1342int length = high - low;13431344// Insertion sort on smallest arrays1345if (length < INSERTIONSORT_THRESHOLD) {1346for (int i=low; i<high; i++)1347for (int j=i; j>low &&1348((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)1349swap(dest, j, j-1);1350return;1351}13521353// Recursively sort halves of dest into src1354int destLow = low;1355int destHigh = high;1356low += off;1357high += off;1358int mid = (low + high) >>> 1;1359mergeSort(dest, src, low, mid, -off);1360mergeSort(dest, src, mid, high, -off);13611362// If list is already sorted, just copy from src to dest. This is an1363// optimization that results in faster sorts for nearly ordered lists.1364if (((Comparable)src[mid-1]).compareTo(src[mid]) <= 0) {1365System.arraycopy(src, low, dest, destLow, length);1366return;1367}13681369// Merge sorted halves (now in src) into dest1370for(int i = destLow, p = low, q = mid; i < destHigh; i++) {1371if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0)1372dest[i] = src[p++];1373else1374dest[i] = src[q++];1375}1376}13771378/**1379* Swaps x[a] with x[b].1380*/1381private static void swap(Object[] x, int a, int b) {1382Object t = x[a];1383x[a] = x[b];1384x[b] = t;1385}13861387/**1388* Sorts the specified array of objects according to the order induced by1389* the specified comparator. All elements in the array must be1390* <i>mutually comparable</i> by the specified comparator (that is,1391* {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}1392* for any elements {@code e1} and {@code e2} in the array).1393*1394* <p>This sort is guaranteed to be <i>stable</i>: equal elements will1395* not be reordered as a result of the sort.1396*1397* <p>Implementation note: This implementation is a stable, adaptive,1398* iterative mergesort that requires far fewer than n lg(n) comparisons1399* when the input array is partially sorted, while offering the1400* performance of a traditional mergesort when the input array is1401* randomly ordered. If the input array is nearly sorted, the1402* implementation requires approximately n comparisons. Temporary1403* storage requirements vary from a small constant for nearly sorted1404* input arrays to n/2 object references for randomly ordered input1405* arrays.1406*1407* <p>The implementation takes equal advantage of ascending and1408* descending order in its input array, and can take advantage of1409* ascending and descending order in different parts of the the same1410* input array. It is well-suited to merging two or more sorted arrays:1411* simply concatenate the arrays and sort the resulting array.1412*1413* <p>The implementation was adapted from Tim Peters's list sort for Python1414* (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">1415* TimSort</a>). It uses techniques from Peter McIlroy's "Optimistic1416* Sorting and Information Theoretic Complexity", in Proceedings of the1417* Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,1418* January 1993.1419*1420* @param <T> the class of the objects to be sorted1421* @param a the array to be sorted1422* @param c the comparator to determine the order of the array. A1423* {@code null} value indicates that the elements'1424* {@linkplain Comparable natural ordering} should be used.1425* @throws ClassCastException if the array contains elements that are1426* not <i>mutually comparable</i> using the specified comparator1427* @throws IllegalArgumentException (optional) if the comparator is1428* found to violate the {@link Comparator} contract1429*/1430public static <T> void sort(T[] a, Comparator<? super T> c) {1431if (c == null) {1432sort(a);1433} else {1434if (LegacyMergeSort.userRequested)1435legacyMergeSort(a, c);1436else1437TimSort.sort(a, 0, a.length, c, null, 0, 0);1438}1439}14401441/** To be removed in a future release. */1442private static <T> void legacyMergeSort(T[] a, Comparator<? super T> c) {1443T[] aux = a.clone();1444if (c==null)1445mergeSort(aux, a, 0, a.length, 0);1446else1447mergeSort(aux, a, 0, a.length, 0, c);1448}14491450/**1451* Sorts the specified range of the specified array of objects according1452* to the order induced by the specified comparator. The range to be1453* sorted extends from index {@code fromIndex}, inclusive, to index1454* {@code toIndex}, exclusive. (If {@code fromIndex==toIndex}, the1455* range to be sorted is empty.) All elements in the range must be1456* <i>mutually comparable</i> by the specified comparator (that is,1457* {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}1458* for any elements {@code e1} and {@code e2} in the range).1459*1460* <p>This sort is guaranteed to be <i>stable</i>: equal elements will1461* not be reordered as a result of the sort.1462*1463* <p>Implementation note: This implementation is a stable, adaptive,1464* iterative mergesort that requires far fewer than n lg(n) comparisons1465* when the input array is partially sorted, while offering the1466* performance of a traditional mergesort when the input array is1467* randomly ordered. If the input array is nearly sorted, the1468* implementation requires approximately n comparisons. Temporary1469* storage requirements vary from a small constant for nearly sorted1470* input arrays to n/2 object references for randomly ordered input1471* arrays.1472*1473* <p>The implementation takes equal advantage of ascending and1474* descending order in its input array, and can take advantage of1475* ascending and descending order in different parts of the the same1476* input array. It is well-suited to merging two or more sorted arrays:1477* simply concatenate the arrays and sort the resulting array.1478*1479* <p>The implementation was adapted from Tim Peters's list sort for Python1480* (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">1481* TimSort</a>). It uses techniques from Peter McIlroy's "Optimistic1482* Sorting and Information Theoretic Complexity", in Proceedings of the1483* Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,1484* January 1993.1485*1486* @param <T> the class of the objects to be sorted1487* @param a the array to be sorted1488* @param fromIndex the index of the first element (inclusive) to be1489* sorted1490* @param toIndex the index of the last element (exclusive) to be sorted1491* @param c the comparator to determine the order of the array. A1492* {@code null} value indicates that the elements'1493* {@linkplain Comparable natural ordering} should be used.1494* @throws ClassCastException if the array contains elements that are not1495* <i>mutually comparable</i> using the specified comparator.1496* @throws IllegalArgumentException if {@code fromIndex > toIndex} or1497* (optional) if the comparator is found to violate the1498* {@link Comparator} contract1499* @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or1500* {@code toIndex > a.length}1501*/1502public static <T> void sort(T[] a, int fromIndex, int toIndex,1503Comparator<? super T> c) {1504if (c == null) {1505sort(a, fromIndex, toIndex);1506} else {1507rangeCheck(a.length, fromIndex, toIndex);1508if (LegacyMergeSort.userRequested)1509legacyMergeSort(a, fromIndex, toIndex, c);1510else1511TimSort.sort(a, fromIndex, toIndex, c, null, 0, 0);1512}1513}15141515/** To be removed in a future release. */1516private static <T> void legacyMergeSort(T[] a, int fromIndex, int toIndex,1517Comparator<? super T> c) {1518T[] aux = copyOfRange(a, fromIndex, toIndex);1519if (c==null)1520mergeSort(aux, a, fromIndex, toIndex, -fromIndex);1521else1522mergeSort(aux, a, fromIndex, toIndex, -fromIndex, c);1523}15241525/**1526* Src is the source array that starts at index 01527* Dest is the (possibly larger) array destination with a possible offset1528* low is the index in dest to start sorting1529* high is the end index in dest to end sorting1530* off is the offset into src corresponding to low in dest1531* To be removed in a future release.1532*/1533@SuppressWarnings({"rawtypes", "unchecked"})1534private static void mergeSort(Object[] src,1535Object[] dest,1536int low, int high, int off,1537Comparator c) {1538int length = high - low;15391540// Insertion sort on smallest arrays1541if (length < INSERTIONSORT_THRESHOLD) {1542for (int i=low; i<high; i++)1543for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)1544swap(dest, j, j-1);1545return;1546}15471548// Recursively sort halves of dest into src1549int destLow = low;1550int destHigh = high;1551low += off;1552high += off;1553int mid = (low + high) >>> 1;1554mergeSort(dest, src, low, mid, -off, c);1555mergeSort(dest, src, mid, high, -off, c);15561557// If list is already sorted, just copy from src to dest. This is an1558// optimization that results in faster sorts for nearly ordered lists.1559if (c.compare(src[mid-1], src[mid]) <= 0) {1560System.arraycopy(src, low, dest, destLow, length);1561return;1562}15631564// Merge sorted halves (now in src) into dest1565for(int i = destLow, p = low, q = mid; i < destHigh; i++) {1566if (q >= high || p < mid && c.compare(src[p], src[q]) <= 0)1567dest[i] = src[p++];1568else1569dest[i] = src[q++];1570}1571}15721573// Parallel prefix15741575/**1576* Cumulates, in parallel, each element of the given array in place,1577* using the supplied function. For example if the array initially1578* holds {@code [2, 1, 0, 3]} and the operation performs addition,1579* then upon return the array holds {@code [2, 3, 3, 6]}.1580* Parallel prefix computation is usually more efficient than1581* sequential loops for large arrays.1582*1583* @param <T> the class of the objects in the array1584* @param array the array, which is modified in-place by this method1585* @param op a side-effect-free, associative function to perform the1586* cumulation1587* @throws NullPointerException if the specified array or function is null1588* @since 1.81589*/1590public static <T> void parallelPrefix(T[] array, BinaryOperator<T> op) {1591Objects.requireNonNull(op);1592if (array.length > 0)1593new ArrayPrefixHelpers.CumulateTask<>1594(null, op, array, 0, array.length).invoke();1595}15961597/**1598* Performs {@link #parallelPrefix(Object[], BinaryOperator)}1599* for the given subrange of the array.1600*1601* @param <T> the class of the objects in the array1602* @param array the array1603* @param fromIndex the index of the first element, inclusive1604* @param toIndex the index of the last element, exclusive1605* @param op a side-effect-free, associative function to perform the1606* cumulation1607* @throws IllegalArgumentException if {@code fromIndex > toIndex}1608* @throws ArrayIndexOutOfBoundsException1609* if {@code fromIndex < 0} or {@code toIndex > array.length}1610* @throws NullPointerException if the specified array or function is null1611* @since 1.81612*/1613public static <T> void parallelPrefix(T[] array, int fromIndex,1614int toIndex, BinaryOperator<T> op) {1615Objects.requireNonNull(op);1616rangeCheck(array.length, fromIndex, toIndex);1617if (fromIndex < toIndex)1618new ArrayPrefixHelpers.CumulateTask<>1619(null, op, array, fromIndex, toIndex).invoke();1620}16211622/**1623* Cumulates, in parallel, each element of the given array in place,1624* using the supplied function. For example if the array initially1625* holds {@code [2, 1, 0, 3]} and the operation performs addition,1626* then upon return the array holds {@code [2, 3, 3, 6]}.1627* Parallel prefix computation is usually more efficient than1628* sequential loops for large arrays.1629*1630* @param array the array, which is modified in-place by this method1631* @param op a side-effect-free, associative function to perform the1632* cumulation1633* @throws NullPointerException if the specified array or function is null1634* @since 1.81635*/1636public static void parallelPrefix(long[] array, LongBinaryOperator op) {1637Objects.requireNonNull(op);1638if (array.length > 0)1639new ArrayPrefixHelpers.LongCumulateTask1640(null, op, array, 0, array.length).invoke();1641}16421643/**1644* Performs {@link #parallelPrefix(long[], LongBinaryOperator)}1645* for the given subrange of the array.1646*1647* @param array the array1648* @param fromIndex the index of the first element, inclusive1649* @param toIndex the index of the last element, exclusive1650* @param op a side-effect-free, associative function to perform the1651* cumulation1652* @throws IllegalArgumentException if {@code fromIndex > toIndex}1653* @throws ArrayIndexOutOfBoundsException1654* if {@code fromIndex < 0} or {@code toIndex > array.length}1655* @throws NullPointerException if the specified array or function is null1656* @since 1.81657*/1658public static void parallelPrefix(long[] array, int fromIndex,1659int toIndex, LongBinaryOperator op) {1660Objects.requireNonNull(op);1661rangeCheck(array.length, fromIndex, toIndex);1662if (fromIndex < toIndex)1663new ArrayPrefixHelpers.LongCumulateTask1664(null, op, array, fromIndex, toIndex).invoke();1665}16661667/**1668* Cumulates, in parallel, each element of the given array in place,1669* using the supplied function. For example if the array initially1670* holds {@code [2.0, 1.0, 0.0, 3.0]} and the operation performs addition,1671* then upon return the array holds {@code [2.0, 3.0, 3.0, 6.0]}.1672* Parallel prefix computation is usually more efficient than1673* sequential loops for large arrays.1674*1675* <p> Because floating-point operations may not be strictly associative,1676* the returned result may not be identical to the value that would be1677* obtained if the operation was performed sequentially.1678*1679* @param array the array, which is modified in-place by this method1680* @param op a side-effect-free function to perform the cumulation1681* @throws NullPointerException if the specified array or function is null1682* @since 1.81683*/1684public static void parallelPrefix(double[] array, DoubleBinaryOperator op) {1685Objects.requireNonNull(op);1686if (array.length > 0)1687new ArrayPrefixHelpers.DoubleCumulateTask1688(null, op, array, 0, array.length).invoke();1689}16901691/**1692* Performs {@link #parallelPrefix(double[], DoubleBinaryOperator)}1693* for the given subrange of the array.1694*1695* @param array the array1696* @param fromIndex the index of the first element, inclusive1697* @param toIndex the index of the last element, exclusive1698* @param op a side-effect-free, associative function to perform the1699* cumulation1700* @throws IllegalArgumentException if {@code fromIndex > toIndex}1701* @throws ArrayIndexOutOfBoundsException1702* if {@code fromIndex < 0} or {@code toIndex > array.length}1703* @throws NullPointerException if the specified array or function is null1704* @since 1.81705*/1706public static void parallelPrefix(double[] array, int fromIndex,1707int toIndex, DoubleBinaryOperator op) {1708Objects.requireNonNull(op);1709rangeCheck(array.length, fromIndex, toIndex);1710if (fromIndex < toIndex)1711new ArrayPrefixHelpers.DoubleCumulateTask1712(null, op, array, fromIndex, toIndex).invoke();1713}17141715/**1716* Cumulates, in parallel, each element of the given array in place,1717* using the supplied function. For example if the array initially1718* holds {@code [2, 1, 0, 3]} and the operation performs addition,1719* then upon return the array holds {@code [2, 3, 3, 6]}.1720* Parallel prefix computation is usually more efficient than1721* sequential loops for large arrays.1722*1723* @param array the array, which is modified in-place by this method1724* @param op a side-effect-free, associative function to perform the1725* cumulation1726* @throws NullPointerException if the specified array or function is null1727* @since 1.81728*/1729public static void parallelPrefix(int[] array, IntBinaryOperator op) {1730Objects.requireNonNull(op);1731if (array.length > 0)1732new ArrayPrefixHelpers.IntCumulateTask1733(null, op, array, 0, array.length).invoke();1734}17351736/**1737* Performs {@link #parallelPrefix(int[], IntBinaryOperator)}1738* for the given subrange of the array.1739*1740* @param array the array1741* @param fromIndex the index of the first element, inclusive1742* @param toIndex the index of the last element, exclusive1743* @param op a side-effect-free, associative function to perform the1744* cumulation1745* @throws IllegalArgumentException if {@code fromIndex > toIndex}1746* @throws ArrayIndexOutOfBoundsException1747* if {@code fromIndex < 0} or {@code toIndex > array.length}1748* @throws NullPointerException if the specified array or function is null1749* @since 1.81750*/1751public static void parallelPrefix(int[] array, int fromIndex,1752int toIndex, IntBinaryOperator op) {1753Objects.requireNonNull(op);1754rangeCheck(array.length, fromIndex, toIndex);1755if (fromIndex < toIndex)1756new ArrayPrefixHelpers.IntCumulateTask1757(null, op, array, fromIndex, toIndex).invoke();1758}17591760// Searching17611762/**1763* Searches the specified array of longs for the specified value using the1764* binary search algorithm. The array must be sorted (as1765* by the {@link #sort(long[])} method) prior to making this call. If it1766* is not sorted, the results are undefined. If the array contains1767* multiple elements with the specified value, there is no guarantee which1768* one will be found.1769*1770* @param a the array to be searched1771* @param key the value to be searched for1772* @return index of the search key, if it is contained in the array;1773* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The1774* <i>insertion point</i> is defined as the point at which the1775* key would be inserted into the array: the index of the first1776* element greater than the key, or <tt>a.length</tt> if all1777* elements in the array are less than the specified key. Note1778* that this guarantees that the return value will be >= 0 if1779* and only if the key is found.1780*/1781public static int binarySearch(long[] a, long key) {1782return binarySearch0(a, 0, a.length, key);1783}17841785/**1786* Searches a range of1787* the specified array of longs for the specified value using the1788* binary search algorithm.1789* The range must be sorted (as1790* by the {@link #sort(long[], int, int)} method)1791* prior to making this call. If it1792* is not sorted, the results are undefined. If the range contains1793* multiple elements with the specified value, there is no guarantee which1794* one will be found.1795*1796* @param a the array to be searched1797* @param fromIndex the index of the first element (inclusive) to be1798* searched1799* @param toIndex the index of the last element (exclusive) to be searched1800* @param key the value to be searched for1801* @return index of the search key, if it is contained in the array1802* within the specified range;1803* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The1804* <i>insertion point</i> is defined as the point at which the1805* key would be inserted into the array: the index of the first1806* element in the range greater than the key,1807* or <tt>toIndex</tt> if all1808* elements in the range are less than the specified key. Note1809* that this guarantees that the return value will be >= 0 if1810* and only if the key is found.1811* @throws IllegalArgumentException1812* if {@code fromIndex > toIndex}1813* @throws ArrayIndexOutOfBoundsException1814* if {@code fromIndex < 0 or toIndex > a.length}1815* @since 1.61816*/1817public static int binarySearch(long[] a, int fromIndex, int toIndex,1818long key) {1819rangeCheck(a.length, fromIndex, toIndex);1820return binarySearch0(a, fromIndex, toIndex, key);1821}18221823// Like public version, but without range checks.1824private static int binarySearch0(long[] a, int fromIndex, int toIndex,1825long key) {1826int low = fromIndex;1827int high = toIndex - 1;18281829while (low <= high) {1830int mid = (low + high) >>> 1;1831long midVal = a[mid];18321833if (midVal < key)1834low = mid + 1;1835else if (midVal > key)1836high = mid - 1;1837else1838return mid; // key found1839}1840return -(low + 1); // key not found.1841}18421843/**1844* Searches the specified array of ints for the specified value using the1845* binary search algorithm. The array must be sorted (as1846* by the {@link #sort(int[])} method) prior to making this call. If it1847* is not sorted, the results are undefined. If the array contains1848* multiple elements with the specified value, there is no guarantee which1849* one will be found.1850*1851* @param a the array to be searched1852* @param key the value to be searched for1853* @return index of the search key, if it is contained in the array;1854* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The1855* <i>insertion point</i> is defined as the point at which the1856* key would be inserted into the array: the index of the first1857* element greater than the key, or <tt>a.length</tt> if all1858* elements in the array are less than the specified key. Note1859* that this guarantees that the return value will be >= 0 if1860* and only if the key is found.1861*/1862public static int binarySearch(int[] a, int key) {1863return binarySearch0(a, 0, a.length, key);1864}18651866/**1867* Searches a range of1868* the specified array of ints for the specified value using the1869* binary search algorithm.1870* The range must be sorted (as1871* by the {@link #sort(int[], int, int)} method)1872* prior to making this call. If it1873* is not sorted, the results are undefined. If the range contains1874* multiple elements with the specified value, there is no guarantee which1875* one will be found.1876*1877* @param a the array to be searched1878* @param fromIndex the index of the first element (inclusive) to be1879* searched1880* @param toIndex the index of the last element (exclusive) to be searched1881* @param key the value to be searched for1882* @return index of the search key, if it is contained in the array1883* within the specified range;1884* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The1885* <i>insertion point</i> is defined as the point at which the1886* key would be inserted into the array: the index of the first1887* element in the range greater than the key,1888* or <tt>toIndex</tt> if all1889* elements in the range are less than the specified key. Note1890* that this guarantees that the return value will be >= 0 if1891* and only if the key is found.1892* @throws IllegalArgumentException1893* if {@code fromIndex > toIndex}1894* @throws ArrayIndexOutOfBoundsException1895* if {@code fromIndex < 0 or toIndex > a.length}1896* @since 1.61897*/1898public static int binarySearch(int[] a, int fromIndex, int toIndex,1899int key) {1900rangeCheck(a.length, fromIndex, toIndex);1901return binarySearch0(a, fromIndex, toIndex, key);1902}19031904// Like public version, but without range checks.1905private static int binarySearch0(int[] a, int fromIndex, int toIndex,1906int key) {1907int low = fromIndex;1908int high = toIndex - 1;19091910while (low <= high) {1911int mid = (low + high) >>> 1;1912int midVal = a[mid];19131914if (midVal < key)1915low = mid + 1;1916else if (midVal > key)1917high = mid - 1;1918else1919return mid; // key found1920}1921return -(low + 1); // key not found.1922}19231924/**1925* Searches the specified array of shorts for the specified value using1926* the binary search algorithm. The array must be sorted1927* (as by the {@link #sort(short[])} method) prior to making this call. If1928* it is not sorted, the results are undefined. If the array contains1929* multiple elements with the specified value, there is no guarantee which1930* one will be found.1931*1932* @param a the array to be searched1933* @param key the value to be searched for1934* @return index of the search key, if it is contained in the array;1935* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The1936* <i>insertion point</i> is defined as the point at which the1937* key would be inserted into the array: the index of the first1938* element greater than the key, or <tt>a.length</tt> if all1939* elements in the array are less than the specified key. Note1940* that this guarantees that the return value will be >= 0 if1941* and only if the key is found.1942*/1943public static int binarySearch(short[] a, short key) {1944return binarySearch0(a, 0, a.length, key);1945}19461947/**1948* Searches a range of1949* the specified array of shorts for the specified value using1950* the binary search algorithm.1951* The range must be sorted1952* (as by the {@link #sort(short[], int, int)} method)1953* prior to making this call. If1954* it is not sorted, the results are undefined. If the range contains1955* multiple elements with the specified value, there is no guarantee which1956* one will be found.1957*1958* @param a the array to be searched1959* @param fromIndex the index of the first element (inclusive) to be1960* searched1961* @param toIndex the index of the last element (exclusive) to be searched1962* @param key the value to be searched for1963* @return index of the search key, if it is contained in the array1964* within the specified range;1965* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The1966* <i>insertion point</i> is defined as the point at which the1967* key would be inserted into the array: the index of the first1968* element in the range greater than the key,1969* or <tt>toIndex</tt> if all1970* elements in the range are less than the specified key. Note1971* that this guarantees that the return value will be >= 0 if1972* and only if the key is found.1973* @throws IllegalArgumentException1974* if {@code fromIndex > toIndex}1975* @throws ArrayIndexOutOfBoundsException1976* if {@code fromIndex < 0 or toIndex > a.length}1977* @since 1.61978*/1979public static int binarySearch(short[] a, int fromIndex, int toIndex,1980short key) {1981rangeCheck(a.length, fromIndex, toIndex);1982return binarySearch0(a, fromIndex, toIndex, key);1983}19841985// Like public version, but without range checks.1986private static int binarySearch0(short[] a, int fromIndex, int toIndex,1987short key) {1988int low = fromIndex;1989int high = toIndex - 1;19901991while (low <= high) {1992int mid = (low + high) >>> 1;1993short midVal = a[mid];19941995if (midVal < key)1996low = mid + 1;1997else if (midVal > key)1998high = mid - 1;1999else2000return mid; // key found2001}2002return -(low + 1); // key not found.2003}20042005/**2006* Searches the specified array of chars for the specified value using the2007* binary search algorithm. The array must be sorted (as2008* by the {@link #sort(char[])} method) prior to making this call. If it2009* is not sorted, the results are undefined. If the array contains2010* multiple elements with the specified value, there is no guarantee which2011* one will be found.2012*2013* @param a the array to be searched2014* @param key the value to be searched for2015* @return index of the search key, if it is contained in the array;2016* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The2017* <i>insertion point</i> is defined as the point at which the2018* key would be inserted into the array: the index of the first2019* element greater than the key, or <tt>a.length</tt> if all2020* elements in the array are less than the specified key. Note2021* that this guarantees that the return value will be >= 0 if2022* and only if the key is found.2023*/2024public static int binarySearch(char[] a, char key) {2025return binarySearch0(a, 0, a.length, key);2026}20272028/**2029* Searches a range of2030* the specified array of chars for the specified value using the2031* binary search algorithm.2032* The range must be sorted (as2033* by the {@link #sort(char[], int, int)} method)2034* prior to making this call. If it2035* is not sorted, the results are undefined. If the range contains2036* multiple elements with the specified value, there is no guarantee which2037* one will be found.2038*2039* @param a the array to be searched2040* @param fromIndex the index of the first element (inclusive) to be2041* searched2042* @param toIndex the index of the last element (exclusive) to be searched2043* @param key the value to be searched for2044* @return index of the search key, if it is contained in the array2045* within the specified range;2046* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The2047* <i>insertion point</i> is defined as the point at which the2048* key would be inserted into the array: the index of the first2049* element in the range greater than the key,2050* or <tt>toIndex</tt> if all2051* elements in the range are less than the specified key. Note2052* that this guarantees that the return value will be >= 0 if2053* and only if the key is found.2054* @throws IllegalArgumentException2055* if {@code fromIndex > toIndex}2056* @throws ArrayIndexOutOfBoundsException2057* if {@code fromIndex < 0 or toIndex > a.length}2058* @since 1.62059*/2060public static int binarySearch(char[] a, int fromIndex, int toIndex,2061char key) {2062rangeCheck(a.length, fromIndex, toIndex);2063return binarySearch0(a, fromIndex, toIndex, key);2064}20652066// Like public version, but without range checks.2067private static int binarySearch0(char[] a, int fromIndex, int toIndex,2068char key) {2069int low = fromIndex;2070int high = toIndex - 1;20712072while (low <= high) {2073int mid = (low + high) >>> 1;2074char midVal = a[mid];20752076if (midVal < key)2077low = mid + 1;2078else if (midVal > key)2079high = mid - 1;2080else2081return mid; // key found2082}2083return -(low + 1); // key not found.2084}20852086/**2087* Searches the specified array of bytes for the specified value using the2088* binary search algorithm. The array must be sorted (as2089* by the {@link #sort(byte[])} method) prior to making this call. If it2090* is not sorted, the results are undefined. If the array contains2091* multiple elements with the specified value, there is no guarantee which2092* one will be found.2093*2094* @param a the array to be searched2095* @param key the value to be searched for2096* @return index of the search key, if it is contained in the array;2097* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The2098* <i>insertion point</i> is defined as the point at which the2099* key would be inserted into the array: the index of the first2100* element greater than the key, or <tt>a.length</tt> if all2101* elements in the array are less than the specified key. Note2102* that this guarantees that the return value will be >= 0 if2103* and only if the key is found.2104*/2105public static int binarySearch(byte[] a, byte key) {2106return binarySearch0(a, 0, a.length, key);2107}21082109/**2110* Searches a range of2111* the specified array of bytes for the specified value using the2112* binary search algorithm.2113* The range must be sorted (as2114* by the {@link #sort(byte[], int, int)} method)2115* prior to making this call. If it2116* is not sorted, the results are undefined. If the range contains2117* multiple elements with the specified value, there is no guarantee which2118* one will be found.2119*2120* @param a the array to be searched2121* @param fromIndex the index of the first element (inclusive) to be2122* searched2123* @param toIndex the index of the last element (exclusive) to be searched2124* @param key the value to be searched for2125* @return index of the search key, if it is contained in the array2126* within the specified range;2127* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The2128* <i>insertion point</i> is defined as the point at which the2129* key would be inserted into the array: the index of the first2130* element in the range greater than the key,2131* or <tt>toIndex</tt> if all2132* elements in the range are less than the specified key. Note2133* that this guarantees that the return value will be >= 0 if2134* and only if the key is found.2135* @throws IllegalArgumentException2136* if {@code fromIndex > toIndex}2137* @throws ArrayIndexOutOfBoundsException2138* if {@code fromIndex < 0 or toIndex > a.length}2139* @since 1.62140*/2141public static int binarySearch(byte[] a, int fromIndex, int toIndex,2142byte key) {2143rangeCheck(a.length, fromIndex, toIndex);2144return binarySearch0(a, fromIndex, toIndex, key);2145}21462147// Like public version, but without range checks.2148private static int binarySearch0(byte[] a, int fromIndex, int toIndex,2149byte key) {2150int low = fromIndex;2151int high = toIndex - 1;21522153while (low <= high) {2154int mid = (low + high) >>> 1;2155byte midVal = a[mid];21562157if (midVal < key)2158low = mid + 1;2159else if (midVal > key)2160high = mid - 1;2161else2162return mid; // key found2163}2164return -(low + 1); // key not found.2165}21662167/**2168* Searches the specified array of doubles for the specified value using2169* the binary search algorithm. The array must be sorted2170* (as by the {@link #sort(double[])} method) prior to making this call.2171* If it is not sorted, the results are undefined. If the array contains2172* multiple elements with the specified value, there is no guarantee which2173* one will be found. This method considers all NaN values to be2174* equivalent and equal.2175*2176* @param a the array to be searched2177* @param key the value to be searched for2178* @return index of the search key, if it is contained in the array;2179* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The2180* <i>insertion point</i> is defined as the point at which the2181* key would be inserted into the array: the index of the first2182* element greater than the key, or <tt>a.length</tt> if all2183* elements in the array are less than the specified key. Note2184* that this guarantees that the return value will be >= 0 if2185* and only if the key is found.2186*/2187public static int binarySearch(double[] a, double key) {2188return binarySearch0(a, 0, a.length, key);2189}21902191/**2192* Searches a range of2193* the specified array of doubles for the specified value using2194* the binary search algorithm.2195* The range must be sorted2196* (as by the {@link #sort(double[], int, int)} method)2197* prior to making this call.2198* If it is not sorted, the results are undefined. If the range contains2199* multiple elements with the specified value, there is no guarantee which2200* one will be found. This method considers all NaN values to be2201* equivalent and equal.2202*2203* @param a the array to be searched2204* @param fromIndex the index of the first element (inclusive) to be2205* searched2206* @param toIndex the index of the last element (exclusive) to be searched2207* @param key the value to be searched for2208* @return index of the search key, if it is contained in the array2209* within the specified range;2210* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The2211* <i>insertion point</i> is defined as the point at which the2212* key would be inserted into the array: the index of the first2213* element in the range greater than the key,2214* or <tt>toIndex</tt> if all2215* elements in the range are less than the specified key. Note2216* that this guarantees that the return value will be >= 0 if2217* and only if the key is found.2218* @throws IllegalArgumentException2219* if {@code fromIndex > toIndex}2220* @throws ArrayIndexOutOfBoundsException2221* if {@code fromIndex < 0 or toIndex > a.length}2222* @since 1.62223*/2224public static int binarySearch(double[] a, int fromIndex, int toIndex,2225double key) {2226rangeCheck(a.length, fromIndex, toIndex);2227return binarySearch0(a, fromIndex, toIndex, key);2228}22292230// Like public version, but without range checks.2231private static int binarySearch0(double[] a, int fromIndex, int toIndex,2232double key) {2233int low = fromIndex;2234int high = toIndex - 1;22352236while (low <= high) {2237int mid = (low + high) >>> 1;2238double midVal = a[mid];22392240if (midVal < key)2241low = mid + 1; // Neither val is NaN, thisVal is smaller2242else if (midVal > key)2243high = mid - 1; // Neither val is NaN, thisVal is larger2244else {2245long midBits = Double.doubleToLongBits(midVal);2246long keyBits = Double.doubleToLongBits(key);2247if (midBits == keyBits) // Values are equal2248return mid; // Key found2249else if (midBits < keyBits) // (-0.0, 0.0) or (!NaN, NaN)2250low = mid + 1;2251else // (0.0, -0.0) or (NaN, !NaN)2252high = mid - 1;2253}2254}2255return -(low + 1); // key not found.2256}22572258/**2259* Searches the specified array of floats for the specified value using2260* the binary search algorithm. The array must be sorted2261* (as by the {@link #sort(float[])} method) prior to making this call. If2262* it is not sorted, the results are undefined. If the array contains2263* multiple elements with the specified value, there is no guarantee which2264* one will be found. This method considers all NaN values to be2265* equivalent and equal.2266*2267* @param a the array to be searched2268* @param key the value to be searched for2269* @return index of the search key, if it is contained in the array;2270* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The2271* <i>insertion point</i> is defined as the point at which the2272* key would be inserted into the array: the index of the first2273* element greater than the key, or <tt>a.length</tt> if all2274* elements in the array are less than the specified key. Note2275* that this guarantees that the return value will be >= 0 if2276* and only if the key is found.2277*/2278public static int binarySearch(float[] a, float key) {2279return binarySearch0(a, 0, a.length, key);2280}22812282/**2283* Searches a range of2284* the specified array of floats for the specified value using2285* the binary search algorithm.2286* The range must be sorted2287* (as by the {@link #sort(float[], int, int)} method)2288* prior to making this call. If2289* it is not sorted, the results are undefined. If the range contains2290* multiple elements with the specified value, there is no guarantee which2291* one will be found. This method considers all NaN values to be2292* equivalent and equal.2293*2294* @param a the array to be searched2295* @param fromIndex the index of the first element (inclusive) to be2296* searched2297* @param toIndex the index of the last element (exclusive) to be searched2298* @param key the value to be searched for2299* @return index of the search key, if it is contained in the array2300* within the specified range;2301* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The2302* <i>insertion point</i> is defined as the point at which the2303* key would be inserted into the array: the index of the first2304* element in the range greater than the key,2305* or <tt>toIndex</tt> if all2306* elements in the range are less than the specified key. Note2307* that this guarantees that the return value will be >= 0 if2308* and only if the key is found.2309* @throws IllegalArgumentException2310* if {@code fromIndex > toIndex}2311* @throws ArrayIndexOutOfBoundsException2312* if {@code fromIndex < 0 or toIndex > a.length}2313* @since 1.62314*/2315public static int binarySearch(float[] a, int fromIndex, int toIndex,2316float key) {2317rangeCheck(a.length, fromIndex, toIndex);2318return binarySearch0(a, fromIndex, toIndex, key);2319}23202321// Like public version, but without range checks.2322private static int binarySearch0(float[] a, int fromIndex, int toIndex,2323float key) {2324int low = fromIndex;2325int high = toIndex - 1;23262327while (low <= high) {2328int mid = (low + high) >>> 1;2329float midVal = a[mid];23302331if (midVal < key)2332low = mid + 1; // Neither val is NaN, thisVal is smaller2333else if (midVal > key)2334high = mid - 1; // Neither val is NaN, thisVal is larger2335else {2336int midBits = Float.floatToIntBits(midVal);2337int keyBits = Float.floatToIntBits(key);2338if (midBits == keyBits) // Values are equal2339return mid; // Key found2340else if (midBits < keyBits) // (-0.0, 0.0) or (!NaN, NaN)2341low = mid + 1;2342else // (0.0, -0.0) or (NaN, !NaN)2343high = mid - 1;2344}2345}2346return -(low + 1); // key not found.2347}23482349/**2350* Searches the specified array for the specified object using the binary2351* search algorithm. The array must be sorted into ascending order2352* according to the2353* {@linkplain Comparable natural ordering}2354* of its elements (as by the2355* {@link #sort(Object[])} method) prior to making this call.2356* If it is not sorted, the results are undefined.2357* (If the array contains elements that are not mutually comparable (for2358* example, strings and integers), it <i>cannot</i> be sorted according2359* to the natural ordering of its elements, hence results are undefined.)2360* If the array contains multiple2361* elements equal to the specified object, there is no guarantee which2362* one will be found.2363*2364* @param a the array to be searched2365* @param key the value to be searched for2366* @return index of the search key, if it is contained in the array;2367* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The2368* <i>insertion point</i> is defined as the point at which the2369* key would be inserted into the array: the index of the first2370* element greater than the key, or <tt>a.length</tt> if all2371* elements in the array are less than the specified key. Note2372* that this guarantees that the return value will be >= 0 if2373* and only if the key is found.2374* @throws ClassCastException if the search key is not comparable to the2375* elements of the array.2376*/2377public static int binarySearch(Object[] a, Object key) {2378return binarySearch0(a, 0, a.length, key);2379}23802381/**2382* Searches a range of2383* the specified array for the specified object using the binary2384* search algorithm.2385* The range must be sorted into ascending order2386* according to the2387* {@linkplain Comparable natural ordering}2388* of its elements (as by the2389* {@link #sort(Object[], int, int)} method) prior to making this2390* call. If it is not sorted, the results are undefined.2391* (If the range contains elements that are not mutually comparable (for2392* example, strings and integers), it <i>cannot</i> be sorted according2393* to the natural ordering of its elements, hence results are undefined.)2394* If the range contains multiple2395* elements equal to the specified object, there is no guarantee which2396* one will be found.2397*2398* @param a the array to be searched2399* @param fromIndex the index of the first element (inclusive) to be2400* searched2401* @param toIndex the index of the last element (exclusive) to be searched2402* @param key the value to be searched for2403* @return index of the search key, if it is contained in the array2404* within the specified range;2405* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The2406* <i>insertion point</i> is defined as the point at which the2407* key would be inserted into the array: the index of the first2408* element in the range greater than the key,2409* or <tt>toIndex</tt> if all2410* elements in the range are less than the specified key. Note2411* that this guarantees that the return value will be >= 0 if2412* and only if the key is found.2413* @throws ClassCastException if the search key is not comparable to the2414* elements of the array within the specified range.2415* @throws IllegalArgumentException2416* if {@code fromIndex > toIndex}2417* @throws ArrayIndexOutOfBoundsException2418* if {@code fromIndex < 0 or toIndex > a.length}2419* @since 1.62420*/2421public static int binarySearch(Object[] a, int fromIndex, int toIndex,2422Object key) {2423rangeCheck(a.length, fromIndex, toIndex);2424return binarySearch0(a, fromIndex, toIndex, key);2425}24262427// Like public version, but without range checks.2428private static int binarySearch0(Object[] a, int fromIndex, int toIndex,2429Object key) {2430int low = fromIndex;2431int high = toIndex - 1;24322433while (low <= high) {2434int mid = (low + high) >>> 1;2435@SuppressWarnings("rawtypes")2436Comparable midVal = (Comparable)a[mid];2437@SuppressWarnings("unchecked")2438int cmp = midVal.compareTo(key);24392440if (cmp < 0)2441low = mid + 1;2442else if (cmp > 0)2443high = mid - 1;2444else2445return mid; // key found2446}2447return -(low + 1); // key not found.2448}24492450/**2451* Searches the specified array for the specified object using the binary2452* search algorithm. The array must be sorted into ascending order2453* according to the specified comparator (as by the2454* {@link #sort(Object[], Comparator) sort(T[], Comparator)}2455* method) prior to making this call. If it is2456* not sorted, the results are undefined.2457* If the array contains multiple2458* elements equal to the specified object, there is no guarantee which one2459* will be found.2460*2461* @param <T> the class of the objects in the array2462* @param a the array to be searched2463* @param key the value to be searched for2464* @param c the comparator by which the array is ordered. A2465* <tt>null</tt> value indicates that the elements'2466* {@linkplain Comparable natural ordering} should be used.2467* @return index of the search key, if it is contained in the array;2468* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The2469* <i>insertion point</i> is defined as the point at which the2470* key would be inserted into the array: the index of the first2471* element greater than the key, or <tt>a.length</tt> if all2472* elements in the array are less than the specified key. Note2473* that this guarantees that the return value will be >= 0 if2474* and only if the key is found.2475* @throws ClassCastException if the array contains elements that are not2476* <i>mutually comparable</i> using the specified comparator,2477* or the search key is not comparable to the2478* elements of the array using this comparator.2479*/2480public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c) {2481return binarySearch0(a, 0, a.length, key, c);2482}24832484/**2485* Searches a range of2486* the specified array for the specified object using the binary2487* search algorithm.2488* The range must be sorted into ascending order2489* according to the specified comparator (as by the2490* {@link #sort(Object[], int, int, Comparator)2491* sort(T[], int, int, Comparator)}2492* method) prior to making this call.2493* If it is not sorted, the results are undefined.2494* If the range contains multiple elements equal to the specified object,2495* there is no guarantee which one will be found.2496*2497* @param <T> the class of the objects in the array2498* @param a the array to be searched2499* @param fromIndex the index of the first element (inclusive) to be2500* searched2501* @param toIndex the index of the last element (exclusive) to be searched2502* @param key the value to be searched for2503* @param c the comparator by which the array is ordered. A2504* <tt>null</tt> value indicates that the elements'2505* {@linkplain Comparable natural ordering} should be used.2506* @return index of the search key, if it is contained in the array2507* within the specified range;2508* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The2509* <i>insertion point</i> is defined as the point at which the2510* key would be inserted into the array: the index of the first2511* element in the range greater than the key,2512* or <tt>toIndex</tt> if all2513* elements in the range are less than the specified key. Note2514* that this guarantees that the return value will be >= 0 if2515* and only if the key is found.2516* @throws ClassCastException if the range contains elements that are not2517* <i>mutually comparable</i> using the specified comparator,2518* or the search key is not comparable to the2519* elements in the range using this comparator.2520* @throws IllegalArgumentException2521* if {@code fromIndex > toIndex}2522* @throws ArrayIndexOutOfBoundsException2523* if {@code fromIndex < 0 or toIndex > a.length}2524* @since 1.62525*/2526public static <T> int binarySearch(T[] a, int fromIndex, int toIndex,2527T key, Comparator<? super T> c) {2528rangeCheck(a.length, fromIndex, toIndex);2529return binarySearch0(a, fromIndex, toIndex, key, c);2530}25312532// Like public version, but without range checks.2533private static <T> int binarySearch0(T[] a, int fromIndex, int toIndex,2534T key, Comparator<? super T> c) {2535if (c == null) {2536return binarySearch0(a, fromIndex, toIndex, key);2537}2538int low = fromIndex;2539int high = toIndex - 1;25402541while (low <= high) {2542int mid = (low + high) >>> 1;2543T midVal = a[mid];2544int cmp = c.compare(midVal, key);2545if (cmp < 0)2546low = mid + 1;2547else if (cmp > 0)2548high = mid - 1;2549else2550return mid; // key found2551}2552return -(low + 1); // key not found.2553}25542555// Equality Testing25562557/**2558* Returns <tt>true</tt> if the two specified arrays of longs are2559* <i>equal</i> to one another. Two arrays are considered equal if both2560* arrays contain the same number of elements, and all corresponding pairs2561* of elements in the two arrays are equal. In other words, two arrays2562* are equal if they contain the same elements in the same order. Also,2563* two array references are considered equal if both are <tt>null</tt>.<p>2564*2565* @param a one array to be tested for equality2566* @param a2 the other array to be tested for equality2567* @return <tt>true</tt> if the two arrays are equal2568*/2569public static boolean equals(long[] a, long[] a2) {2570if (a==a2)2571return true;2572if (a==null || a2==null)2573return false;25742575int length = a.length;2576if (a2.length != length)2577return false;25782579for (int i=0; i<length; i++)2580if (a[i] != a2[i])2581return false;25822583return true;2584}25852586/**2587* Returns <tt>true</tt> if the two specified arrays of ints are2588* <i>equal</i> to one another. Two arrays are considered equal if both2589* arrays contain the same number of elements, and all corresponding pairs2590* of elements in the two arrays are equal. In other words, two arrays2591* are equal if they contain the same elements in the same order. Also,2592* two array references are considered equal if both are <tt>null</tt>.<p>2593*2594* @param a one array to be tested for equality2595* @param a2 the other array to be tested for equality2596* @return <tt>true</tt> if the two arrays are equal2597*/2598public static boolean equals(int[] a, int[] a2) {2599if (a==a2)2600return true;2601if (a==null || a2==null)2602return false;26032604int length = a.length;2605if (a2.length != length)2606return false;26072608for (int i=0; i<length; i++)2609if (a[i] != a2[i])2610return false;26112612return true;2613}26142615/**2616* Returns <tt>true</tt> if the two specified arrays of shorts are2617* <i>equal</i> to one another. Two arrays are considered equal if both2618* arrays contain the same number of elements, and all corresponding pairs2619* of elements in the two arrays are equal. In other words, two arrays2620* are equal if they contain the same elements in the same order. Also,2621* two array references are considered equal if both are <tt>null</tt>.<p>2622*2623* @param a one array to be tested for equality2624* @param a2 the other array to be tested for equality2625* @return <tt>true</tt> if the two arrays are equal2626*/2627public static boolean equals(short[] a, short a2[]) {2628if (a==a2)2629return true;2630if (a==null || a2==null)2631return false;26322633int length = a.length;2634if (a2.length != length)2635return false;26362637for (int i=0; i<length; i++)2638if (a[i] != a2[i])2639return false;26402641return true;2642}26432644/**2645* Returns <tt>true</tt> if the two specified arrays of chars are2646* <i>equal</i> to one another. Two arrays are considered equal if both2647* arrays contain the same number of elements, and all corresponding pairs2648* of elements in the two arrays are equal. In other words, two arrays2649* are equal if they contain the same elements in the same order. Also,2650* two array references are considered equal if both are <tt>null</tt>.<p>2651*2652* @param a one array to be tested for equality2653* @param a2 the other array to be tested for equality2654* @return <tt>true</tt> if the two arrays are equal2655*/2656public static boolean equals(char[] a, char[] a2) {2657if (a==a2)2658return true;2659if (a==null || a2==null)2660return false;26612662int length = a.length;2663if (a2.length != length)2664return false;26652666for (int i=0; i<length; i++)2667if (a[i] != a2[i])2668return false;26692670return true;2671}26722673/**2674* Returns <tt>true</tt> if the two specified arrays of bytes are2675* <i>equal</i> to one another. Two arrays are considered equal if both2676* arrays contain the same number of elements, and all corresponding pairs2677* of elements in the two arrays are equal. In other words, two arrays2678* are equal if they contain the same elements in the same order. Also,2679* two array references are considered equal if both are <tt>null</tt>.<p>2680*2681* @param a one array to be tested for equality2682* @param a2 the other array to be tested for equality2683* @return <tt>true</tt> if the two arrays are equal2684*/2685public static boolean equals(byte[] a, byte[] a2) {2686if (a==a2)2687return true;2688if (a==null || a2==null)2689return false;26902691int length = a.length;2692if (a2.length != length)2693return false;26942695for (int i=0; i<length; i++)2696if (a[i] != a2[i])2697return false;26982699return true;2700}27012702/**2703* Returns <tt>true</tt> if the two specified arrays of booleans are2704* <i>equal</i> to one another. Two arrays are considered equal if both2705* arrays contain the same number of elements, and all corresponding pairs2706* of elements in the two arrays are equal. In other words, two arrays2707* are equal if they contain the same elements in the same order. Also,2708* two array references are considered equal if both are <tt>null</tt>.<p>2709*2710* @param a one array to be tested for equality2711* @param a2 the other array to be tested for equality2712* @return <tt>true</tt> if the two arrays are equal2713*/2714public static boolean equals(boolean[] a, boolean[] a2) {2715if (a==a2)2716return true;2717if (a==null || a2==null)2718return false;27192720int length = a.length;2721if (a2.length != length)2722return false;27232724for (int i=0; i<length; i++)2725if (a[i] != a2[i])2726return false;27272728return true;2729}27302731/**2732* Returns <tt>true</tt> if the two specified arrays of doubles are2733* <i>equal</i> to one another. Two arrays are considered equal if both2734* arrays contain the same number of elements, and all corresponding pairs2735* of elements in the two arrays are equal. In other words, two arrays2736* are equal if they contain the same elements in the same order. Also,2737* two array references are considered equal if both are <tt>null</tt>.<p>2738*2739* Two doubles <tt>d1</tt> and <tt>d2</tt> are considered equal if:2740* <pre> <tt>new Double(d1).equals(new Double(d2))</tt></pre>2741* (Unlike the <tt>==</tt> operator, this method considers2742* <tt>NaN</tt> equals to itself, and 0.0d unequal to -0.0d.)2743*2744* @param a one array to be tested for equality2745* @param a2 the other array to be tested for equality2746* @return <tt>true</tt> if the two arrays are equal2747* @see Double#equals(Object)2748*/2749public static boolean equals(double[] a, double[] a2) {2750if (a==a2)2751return true;2752if (a==null || a2==null)2753return false;27542755int length = a.length;2756if (a2.length != length)2757return false;27582759for (int i=0; i<length; i++)2760if (Double.doubleToLongBits(a[i])!=Double.doubleToLongBits(a2[i]))2761return false;27622763return true;2764}27652766/**2767* Returns <tt>true</tt> if the two specified arrays of floats are2768* <i>equal</i> to one another. Two arrays are considered equal if both2769* arrays contain the same number of elements, and all corresponding pairs2770* of elements in the two arrays are equal. In other words, two arrays2771* are equal if they contain the same elements in the same order. Also,2772* two array references are considered equal if both are <tt>null</tt>.<p>2773*2774* Two floats <tt>f1</tt> and <tt>f2</tt> are considered equal if:2775* <pre> <tt>new Float(f1).equals(new Float(f2))</tt></pre>2776* (Unlike the <tt>==</tt> operator, this method considers2777* <tt>NaN</tt> equals to itself, and 0.0f unequal to -0.0f.)2778*2779* @param a one array to be tested for equality2780* @param a2 the other array to be tested for equality2781* @return <tt>true</tt> if the two arrays are equal2782* @see Float#equals(Object)2783*/2784public static boolean equals(float[] a, float[] a2) {2785if (a==a2)2786return true;2787if (a==null || a2==null)2788return false;27892790int length = a.length;2791if (a2.length != length)2792return false;27932794for (int i=0; i<length; i++)2795if (Float.floatToIntBits(a[i])!=Float.floatToIntBits(a2[i]))2796return false;27972798return true;2799}28002801/**2802* Returns <tt>true</tt> if the two specified arrays of Objects are2803* <i>equal</i> to one another. The two arrays are considered equal if2804* both arrays contain the same number of elements, and all corresponding2805* pairs of elements in the two arrays are equal. Two objects <tt>e1</tt>2806* and <tt>e2</tt> are considered <i>equal</i> if <tt>(e1==null ? e2==null2807* : e1.equals(e2))</tt>. In other words, the two arrays are equal if2808* they contain the same elements in the same order. Also, two array2809* references are considered equal if both are <tt>null</tt>.<p>2810*2811* @param a one array to be tested for equality2812* @param a2 the other array to be tested for equality2813* @return <tt>true</tt> if the two arrays are equal2814*/2815public static boolean equals(Object[] a, Object[] a2) {2816if (a==a2)2817return true;2818if (a==null || a2==null)2819return false;28202821int length = a.length;2822if (a2.length != length)2823return false;28242825for (int i=0; i<length; i++) {2826Object o1 = a[i];2827Object o2 = a2[i];2828if (!(o1==null ? o2==null : o1.equals(o2)))2829return false;2830}28312832return true;2833}28342835// Filling28362837/**2838* Assigns the specified long value to each element of the specified array2839* of longs.2840*2841* @param a the array to be filled2842* @param val the value to be stored in all elements of the array2843*/2844public static void fill(long[] a, long val) {2845for (int i = 0, len = a.length; i < len; i++)2846a[i] = val;2847}28482849/**2850* Assigns the specified long value to each element of the specified2851* range of the specified array of longs. The range to be filled2852* extends from index <tt>fromIndex</tt>, inclusive, to index2853* <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the2854* range to be filled is empty.)2855*2856* @param a the array to be filled2857* @param fromIndex the index of the first element (inclusive) to be2858* filled with the specified value2859* @param toIndex the index of the last element (exclusive) to be2860* filled with the specified value2861* @param val the value to be stored in all elements of the array2862* @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>2863* @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or2864* <tt>toIndex > a.length</tt>2865*/2866public static void fill(long[] a, int fromIndex, int toIndex, long val) {2867rangeCheck(a.length, fromIndex, toIndex);2868for (int i = fromIndex; i < toIndex; i++)2869a[i] = val;2870}28712872/**2873* Assigns the specified int value to each element of the specified array2874* of ints.2875*2876* @param a the array to be filled2877* @param val the value to be stored in all elements of the array2878*/2879public static void fill(int[] a, int val) {2880for (int i = 0, len = a.length; i < len; i++)2881a[i] = val;2882}28832884/**2885* Assigns the specified int value to each element of the specified2886* range of the specified array of ints. The range to be filled2887* extends from index <tt>fromIndex</tt>, inclusive, to index2888* <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the2889* range to be filled is empty.)2890*2891* @param a the array to be filled2892* @param fromIndex the index of the first element (inclusive) to be2893* filled with the specified value2894* @param toIndex the index of the last element (exclusive) to be2895* filled with the specified value2896* @param val the value to be stored in all elements of the array2897* @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>2898* @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or2899* <tt>toIndex > a.length</tt>2900*/2901public static void fill(int[] a, int fromIndex, int toIndex, int val) {2902rangeCheck(a.length, fromIndex, toIndex);2903for (int i = fromIndex; i < toIndex; i++)2904a[i] = val;2905}29062907/**2908* Assigns the specified short value to each element of the specified array2909* of shorts.2910*2911* @param a the array to be filled2912* @param val the value to be stored in all elements of the array2913*/2914public static void fill(short[] a, short val) {2915for (int i = 0, len = a.length; i < len; i++)2916a[i] = val;2917}29182919/**2920* Assigns the specified short value to each element of the specified2921* range of the specified array of shorts. The range to be filled2922* extends from index <tt>fromIndex</tt>, inclusive, to index2923* <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the2924* range to be filled is empty.)2925*2926* @param a the array to be filled2927* @param fromIndex the index of the first element (inclusive) to be2928* filled with the specified value2929* @param toIndex the index of the last element (exclusive) to be2930* filled with the specified value2931* @param val the value to be stored in all elements of the array2932* @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>2933* @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or2934* <tt>toIndex > a.length</tt>2935*/2936public static void fill(short[] a, int fromIndex, int toIndex, short val) {2937rangeCheck(a.length, fromIndex, toIndex);2938for (int i = fromIndex; i < toIndex; i++)2939a[i] = val;2940}29412942/**2943* Assigns the specified char value to each element of the specified array2944* of chars.2945*2946* @param a the array to be filled2947* @param val the value to be stored in all elements of the array2948*/2949public static void fill(char[] a, char val) {2950for (int i = 0, len = a.length; i < len; i++)2951a[i] = val;2952}29532954/**2955* Assigns the specified char value to each element of the specified2956* range of the specified array of chars. The range to be filled2957* extends from index <tt>fromIndex</tt>, inclusive, to index2958* <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the2959* range to be filled is empty.)2960*2961* @param a the array to be filled2962* @param fromIndex the index of the first element (inclusive) to be2963* filled with the specified value2964* @param toIndex the index of the last element (exclusive) to be2965* filled with the specified value2966* @param val the value to be stored in all elements of the array2967* @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>2968* @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or2969* <tt>toIndex > a.length</tt>2970*/2971public static void fill(char[] a, int fromIndex, int toIndex, char val) {2972rangeCheck(a.length, fromIndex, toIndex);2973for (int i = fromIndex; i < toIndex; i++)2974a[i] = val;2975}29762977/**2978* Assigns the specified byte value to each element of the specified array2979* of bytes.2980*2981* @param a the array to be filled2982* @param val the value to be stored in all elements of the array2983*/2984public static void fill(byte[] a, byte val) {2985for (int i = 0, len = a.length; i < len; i++)2986a[i] = val;2987}29882989/**2990* Assigns the specified byte value to each element of the specified2991* range of the specified array of bytes. The range to be filled2992* extends from index <tt>fromIndex</tt>, inclusive, to index2993* <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the2994* range to be filled is empty.)2995*2996* @param a the array to be filled2997* @param fromIndex the index of the first element (inclusive) to be2998* filled with the specified value2999* @param toIndex the index of the last element (exclusive) to be3000* filled with the specified value3001* @param val the value to be stored in all elements of the array3002* @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>3003* @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or3004* <tt>toIndex > a.length</tt>3005*/3006public static void fill(byte[] a, int fromIndex, int toIndex, byte val) {3007rangeCheck(a.length, fromIndex, toIndex);3008for (int i = fromIndex; i < toIndex; i++)3009a[i] = val;3010}30113012/**3013* Assigns the specified boolean value to each element of the specified3014* array of booleans.3015*3016* @param a the array to be filled3017* @param val the value to be stored in all elements of the array3018*/3019public static void fill(boolean[] a, boolean val) {3020for (int i = 0, len = a.length; i < len; i++)3021a[i] = val;3022}30233024/**3025* Assigns the specified boolean value to each element of the specified3026* range of the specified array of booleans. The range to be filled3027* extends from index <tt>fromIndex</tt>, inclusive, to index3028* <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the3029* range to be filled is empty.)3030*3031* @param a the array to be filled3032* @param fromIndex the index of the first element (inclusive) to be3033* filled with the specified value3034* @param toIndex the index of the last element (exclusive) to be3035* filled with the specified value3036* @param val the value to be stored in all elements of the array3037* @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>3038* @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or3039* <tt>toIndex > a.length</tt>3040*/3041public static void fill(boolean[] a, int fromIndex, int toIndex,3042boolean val) {3043rangeCheck(a.length, fromIndex, toIndex);3044for (int i = fromIndex; i < toIndex; i++)3045a[i] = val;3046}30473048/**3049* Assigns the specified double value to each element of the specified3050* array of doubles.3051*3052* @param a the array to be filled3053* @param val the value to be stored in all elements of the array3054*/3055public static void fill(double[] a, double val) {3056for (int i = 0, len = a.length; i < len; i++)3057a[i] = val;3058}30593060/**3061* Assigns the specified double value to each element of the specified3062* range of the specified array of doubles. The range to be filled3063* extends from index <tt>fromIndex</tt>, inclusive, to index3064* <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the3065* range to be filled is empty.)3066*3067* @param a the array to be filled3068* @param fromIndex the index of the first element (inclusive) to be3069* filled with the specified value3070* @param toIndex the index of the last element (exclusive) to be3071* filled with the specified value3072* @param val the value to be stored in all elements of the array3073* @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>3074* @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or3075* <tt>toIndex > a.length</tt>3076*/3077public static void fill(double[] a, int fromIndex, int toIndex,double val){3078rangeCheck(a.length, fromIndex, toIndex);3079for (int i = fromIndex; i < toIndex; i++)3080a[i] = val;3081}30823083/**3084* Assigns the specified float value to each element of the specified array3085* of floats.3086*3087* @param a the array to be filled3088* @param val the value to be stored in all elements of the array3089*/3090public static void fill(float[] a, float val) {3091for (int i = 0, len = a.length; i < len; i++)3092a[i] = val;3093}30943095/**3096* Assigns the specified float value to each element of the specified3097* range of the specified array of floats. The range to be filled3098* extends from index <tt>fromIndex</tt>, inclusive, to index3099* <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the3100* range to be filled is empty.)3101*3102* @param a the array to be filled3103* @param fromIndex the index of the first element (inclusive) to be3104* filled with the specified value3105* @param toIndex the index of the last element (exclusive) to be3106* filled with the specified value3107* @param val the value to be stored in all elements of the array3108* @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>3109* @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or3110* <tt>toIndex > a.length</tt>3111*/3112public static void fill(float[] a, int fromIndex, int toIndex, float val) {3113rangeCheck(a.length, fromIndex, toIndex);3114for (int i = fromIndex; i < toIndex; i++)3115a[i] = val;3116}31173118/**3119* Assigns the specified Object reference to each element of the specified3120* array of Objects.3121*3122* @param a the array to be filled3123* @param val the value to be stored in all elements of the array3124* @throws ArrayStoreException if the specified value is not of a3125* runtime type that can be stored in the specified array3126*/3127public static void fill(Object[] a, Object val) {3128for (int i = 0, len = a.length; i < len; i++)3129a[i] = val;3130}31313132/**3133* Assigns the specified Object reference to each element of the specified3134* range of the specified array of Objects. The range to be filled3135* extends from index <tt>fromIndex</tt>, inclusive, to index3136* <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the3137* range to be filled is empty.)3138*3139* @param a the array to be filled3140* @param fromIndex the index of the first element (inclusive) to be3141* filled with the specified value3142* @param toIndex the index of the last element (exclusive) to be3143* filled with the specified value3144* @param val the value to be stored in all elements of the array3145* @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>3146* @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or3147* <tt>toIndex > a.length</tt>3148* @throws ArrayStoreException if the specified value is not of a3149* runtime type that can be stored in the specified array3150*/3151public static void fill(Object[] a, int fromIndex, int toIndex, Object val) {3152rangeCheck(a.length, fromIndex, toIndex);3153for (int i = fromIndex; i < toIndex; i++)3154a[i] = val;3155}31563157// Cloning31583159/**3160* Copies the specified array, truncating or padding with nulls (if necessary)3161* so the copy has the specified length. For all indices that are3162* valid in both the original array and the copy, the two arrays will3163* contain identical values. For any indices that are valid in the3164* copy but not the original, the copy will contain <tt>null</tt>.3165* Such indices will exist if and only if the specified length3166* is greater than that of the original array.3167* The resulting array is of exactly the same class as the original array.3168*3169* @param <T> the class of the objects in the array3170* @param original the array to be copied3171* @param newLength the length of the copy to be returned3172* @return a copy of the original array, truncated or padded with nulls3173* to obtain the specified length3174* @throws NegativeArraySizeException if <tt>newLength</tt> is negative3175* @throws NullPointerException if <tt>original</tt> is null3176* @since 1.63177*/3178@SuppressWarnings("unchecked")3179public static <T> T[] copyOf(T[] original, int newLength) {3180return (T[]) copyOf(original, newLength, original.getClass());3181}31823183/**3184* Copies the specified array, truncating or padding with nulls (if necessary)3185* so the copy has the specified length. For all indices that are3186* valid in both the original array and the copy, the two arrays will3187* contain identical values. For any indices that are valid in the3188* copy but not the original, the copy will contain <tt>null</tt>.3189* Such indices will exist if and only if the specified length3190* is greater than that of the original array.3191* The resulting array is of the class <tt>newType</tt>.3192*3193* @param <U> the class of the objects in the original array3194* @param <T> the class of the objects in the returned array3195* @param original the array to be copied3196* @param newLength the length of the copy to be returned3197* @param newType the class of the copy to be returned3198* @return a copy of the original array, truncated or padded with nulls3199* to obtain the specified length3200* @throws NegativeArraySizeException if <tt>newLength</tt> is negative3201* @throws NullPointerException if <tt>original</tt> is null3202* @throws ArrayStoreException if an element copied from3203* <tt>original</tt> is not of a runtime type that can be stored in3204* an array of class <tt>newType</tt>3205* @since 1.63206*/3207public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {3208@SuppressWarnings("unchecked")3209T[] copy = ((Object)newType == (Object)Object[].class)3210? (T[]) new Object[newLength]3211: (T[]) Array.newInstance(newType.getComponentType(), newLength);3212System.arraycopy(original, 0, copy, 0,3213Math.min(original.length, newLength));3214return copy;3215}32163217/**3218* Copies the specified array, truncating or padding with zeros (if necessary)3219* so the copy has the specified length. For all indices that are3220* valid in both the original array and the copy, the two arrays will3221* contain identical values. For any indices that are valid in the3222* copy but not the original, the copy will contain <tt>(byte)0</tt>.3223* Such indices will exist if and only if the specified length3224* is greater than that of the original array.3225*3226* @param original the array to be copied3227* @param newLength the length of the copy to be returned3228* @return a copy of the original array, truncated or padded with zeros3229* to obtain the specified length3230* @throws NegativeArraySizeException if <tt>newLength</tt> is negative3231* @throws NullPointerException if <tt>original</tt> is null3232* @since 1.63233*/3234public static byte[] copyOf(byte[] original, int newLength) {3235byte[] copy = new byte[newLength];3236System.arraycopy(original, 0, copy, 0,3237Math.min(original.length, newLength));3238return copy;3239}32403241/**3242* Copies the specified array, truncating or padding with zeros (if necessary)3243* so the copy has the specified length. For all indices that are3244* valid in both the original array and the copy, the two arrays will3245* contain identical values. For any indices that are valid in the3246* copy but not the original, the copy will contain <tt>(short)0</tt>.3247* Such indices will exist if and only if the specified length3248* is greater than that of the original array.3249*3250* @param original the array to be copied3251* @param newLength the length of the copy to be returned3252* @return a copy of the original array, truncated or padded with zeros3253* to obtain the specified length3254* @throws NegativeArraySizeException if <tt>newLength</tt> is negative3255* @throws NullPointerException if <tt>original</tt> is null3256* @since 1.63257*/3258public static short[] copyOf(short[] original, int newLength) {3259short[] copy = new short[newLength];3260System.arraycopy(original, 0, copy, 0,3261Math.min(original.length, newLength));3262return copy;3263}32643265/**3266* Copies the specified array, truncating or padding with zeros (if necessary)3267* so the copy has the specified length. For all indices that are3268* valid in both the original array and the copy, the two arrays will3269* contain identical values. For any indices that are valid in the3270* copy but not the original, the copy will contain <tt>0</tt>.3271* Such indices will exist if and only if the specified length3272* is greater than that of the original array.3273*3274* @param original the array to be copied3275* @param newLength the length of the copy to be returned3276* @return a copy of the original array, truncated or padded with zeros3277* to obtain the specified length3278* @throws NegativeArraySizeException if <tt>newLength</tt> is negative3279* @throws NullPointerException if <tt>original</tt> is null3280* @since 1.63281*/3282public static int[] copyOf(int[] original, int newLength) {3283int[] copy = new int[newLength];3284System.arraycopy(original, 0, copy, 0,3285Math.min(original.length, newLength));3286return copy;3287}32883289/**3290* Copies the specified array, truncating or padding with zeros (if necessary)3291* so the copy has the specified length. For all indices that are3292* valid in both the original array and the copy, the two arrays will3293* contain identical values. For any indices that are valid in the3294* copy but not the original, the copy will contain <tt>0L</tt>.3295* Such indices will exist if and only if the specified length3296* is greater than that of the original array.3297*3298* @param original the array to be copied3299* @param newLength the length of the copy to be returned3300* @return a copy of the original array, truncated or padded with zeros3301* to obtain the specified length3302* @throws NegativeArraySizeException if <tt>newLength</tt> is negative3303* @throws NullPointerException if <tt>original</tt> is null3304* @since 1.63305*/3306public static long[] copyOf(long[] original, int newLength) {3307long[] copy = new long[newLength];3308System.arraycopy(original, 0, copy, 0,3309Math.min(original.length, newLength));3310return copy;3311}33123313/**3314* Copies the specified array, truncating or padding with null characters (if necessary)3315* so the copy has the specified length. For all indices that are valid3316* in both the original array and the copy, the two arrays will contain3317* identical values. For any indices that are valid in the copy but not3318* the original, the copy will contain <tt>'\\u000'</tt>. Such indices3319* will exist if and only if the specified length is greater than that of3320* the original array.3321*3322* @param original the array to be copied3323* @param newLength the length of the copy to be returned3324* @return a copy of the original array, truncated or padded with null characters3325* to obtain the specified length3326* @throws NegativeArraySizeException if <tt>newLength</tt> is negative3327* @throws NullPointerException if <tt>original</tt> is null3328* @since 1.63329*/3330public static char[] copyOf(char[] original, int newLength) {3331char[] copy = new char[newLength];3332System.arraycopy(original, 0, copy, 0,3333Math.min(original.length, newLength));3334return copy;3335}33363337/**3338* Copies the specified array, truncating or padding with zeros (if necessary)3339* so the copy has the specified length. For all indices that are3340* valid in both the original array and the copy, the two arrays will3341* contain identical values. For any indices that are valid in the3342* copy but not the original, the copy will contain <tt>0f</tt>.3343* Such indices will exist if and only if the specified length3344* is greater than that of the original array.3345*3346* @param original the array to be copied3347* @param newLength the length of the copy to be returned3348* @return a copy of the original array, truncated or padded with zeros3349* to obtain the specified length3350* @throws NegativeArraySizeException if <tt>newLength</tt> is negative3351* @throws NullPointerException if <tt>original</tt> is null3352* @since 1.63353*/3354public static float[] copyOf(float[] original, int newLength) {3355float[] copy = new float[newLength];3356System.arraycopy(original, 0, copy, 0,3357Math.min(original.length, newLength));3358return copy;3359}33603361/**3362* Copies the specified array, truncating or padding with zeros (if necessary)3363* so the copy has the specified length. For all indices that are3364* valid in both the original array and the copy, the two arrays will3365* contain identical values. For any indices that are valid in the3366* copy but not the original, the copy will contain <tt>0d</tt>.3367* Such indices will exist if and only if the specified length3368* is greater than that of the original array.3369*3370* @param original the array to be copied3371* @param newLength the length of the copy to be returned3372* @return a copy of the original array, truncated or padded with zeros3373* to obtain the specified length3374* @throws NegativeArraySizeException if <tt>newLength</tt> is negative3375* @throws NullPointerException if <tt>original</tt> is null3376* @since 1.63377*/3378public static double[] copyOf(double[] original, int newLength) {3379double[] copy = new double[newLength];3380System.arraycopy(original, 0, copy, 0,3381Math.min(original.length, newLength));3382return copy;3383}33843385/**3386* Copies the specified array, truncating or padding with <tt>false</tt> (if necessary)3387* so the copy has the specified length. For all indices that are3388* valid in both the original array and the copy, the two arrays will3389* contain identical values. For any indices that are valid in the3390* copy but not the original, the copy will contain <tt>false</tt>.3391* Such indices will exist if and only if the specified length3392* is greater than that of the original array.3393*3394* @param original the array to be copied3395* @param newLength the length of the copy to be returned3396* @return a copy of the original array, truncated or padded with false elements3397* to obtain the specified length3398* @throws NegativeArraySizeException if <tt>newLength</tt> is negative3399* @throws NullPointerException if <tt>original</tt> is null3400* @since 1.63401*/3402public static boolean[] copyOf(boolean[] original, int newLength) {3403boolean[] copy = new boolean[newLength];3404System.arraycopy(original, 0, copy, 0,3405Math.min(original.length, newLength));3406return copy;3407}34083409/**3410* Copies the specified range of the specified array into a new array.3411* The initial index of the range (<tt>from</tt>) must lie between zero3412* and <tt>original.length</tt>, inclusive. The value at3413* <tt>original[from]</tt> is placed into the initial element of the copy3414* (unless <tt>from == original.length</tt> or <tt>from == to</tt>).3415* Values from subsequent elements in the original array are placed into3416* subsequent elements in the copy. The final index of the range3417* (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,3418* may be greater than <tt>original.length</tt>, in which case3419* <tt>null</tt> is placed in all elements of the copy whose index is3420* greater than or equal to <tt>original.length - from</tt>. The length3421* of the returned array will be <tt>to - from</tt>.3422* <p>3423* The resulting array is of exactly the same class as the original array.3424*3425* @param <T> the class of the objects in the array3426* @param original the array from which a range is to be copied3427* @param from the initial index of the range to be copied, inclusive3428* @param to the final index of the range to be copied, exclusive.3429* (This index may lie outside the array.)3430* @return a new array containing the specified range from the original array,3431* truncated or padded with nulls to obtain the required length3432* @throws ArrayIndexOutOfBoundsException if {@code from < 0}3433* or {@code from > original.length}3434* @throws IllegalArgumentException if <tt>from > to</tt>3435* @throws NullPointerException if <tt>original</tt> is null3436* @since 1.63437*/3438@SuppressWarnings("unchecked")3439public static <T> T[] copyOfRange(T[] original, int from, int to) {3440return copyOfRange(original, from, to, (Class<? extends T[]>) original.getClass());3441}34423443/**3444* Copies the specified range of the specified array into a new array.3445* The initial index of the range (<tt>from</tt>) must lie between zero3446* and <tt>original.length</tt>, inclusive. The value at3447* <tt>original[from]</tt> is placed into the initial element of the copy3448* (unless <tt>from == original.length</tt> or <tt>from == to</tt>).3449* Values from subsequent elements in the original array are placed into3450* subsequent elements in the copy. The final index of the range3451* (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,3452* may be greater than <tt>original.length</tt>, in which case3453* <tt>null</tt> is placed in all elements of the copy whose index is3454* greater than or equal to <tt>original.length - from</tt>. The length3455* of the returned array will be <tt>to - from</tt>.3456* The resulting array is of the class <tt>newType</tt>.3457*3458* @param <U> the class of the objects in the original array3459* @param <T> the class of the objects in the returned array3460* @param original the array from which a range is to be copied3461* @param from the initial index of the range to be copied, inclusive3462* @param to the final index of the range to be copied, exclusive.3463* (This index may lie outside the array.)3464* @param newType the class of the copy to be returned3465* @return a new array containing the specified range from the original array,3466* truncated or padded with nulls to obtain the required length3467* @throws ArrayIndexOutOfBoundsException if {@code from < 0}3468* or {@code from > original.length}3469* @throws IllegalArgumentException if <tt>from > to</tt>3470* @throws NullPointerException if <tt>original</tt> is null3471* @throws ArrayStoreException if an element copied from3472* <tt>original</tt> is not of a runtime type that can be stored in3473* an array of class <tt>newType</tt>.3474* @since 1.63475*/3476public static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {3477int newLength = to - from;3478if (newLength < 0)3479throw new IllegalArgumentException(from + " > " + to);3480@SuppressWarnings("unchecked")3481T[] copy = ((Object)newType == (Object)Object[].class)3482? (T[]) new Object[newLength]3483: (T[]) Array.newInstance(newType.getComponentType(), newLength);3484System.arraycopy(original, from, copy, 0,3485Math.min(original.length - from, newLength));3486return copy;3487}34883489/**3490* Copies the specified range of the specified array into a new array.3491* The initial index of the range (<tt>from</tt>) must lie between zero3492* and <tt>original.length</tt>, inclusive. The value at3493* <tt>original[from]</tt> is placed into the initial element of the copy3494* (unless <tt>from == original.length</tt> or <tt>from == to</tt>).3495* Values from subsequent elements in the original array are placed into3496* subsequent elements in the copy. The final index of the range3497* (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,3498* may be greater than <tt>original.length</tt>, in which case3499* <tt>(byte)0</tt> is placed in all elements of the copy whose index is3500* greater than or equal to <tt>original.length - from</tt>. The length3501* of the returned array will be <tt>to - from</tt>.3502*3503* @param original the array from which a range is to be copied3504* @param from the initial index of the range to be copied, inclusive3505* @param to the final index of the range to be copied, exclusive.3506* (This index may lie outside the array.)3507* @return a new array containing the specified range from the original array,3508* truncated or padded with zeros to obtain the required length3509* @throws ArrayIndexOutOfBoundsException if {@code from < 0}3510* or {@code from > original.length}3511* @throws IllegalArgumentException if <tt>from > to</tt>3512* @throws NullPointerException if <tt>original</tt> is null3513* @since 1.63514*/3515public static byte[] copyOfRange(byte[] original, int from, int to) {3516int newLength = to - from;3517if (newLength < 0)3518throw new IllegalArgumentException(from + " > " + to);3519byte[] copy = new byte[newLength];3520System.arraycopy(original, from, copy, 0,3521Math.min(original.length - from, newLength));3522return copy;3523}35243525/**3526* Copies the specified range of the specified array into a new array.3527* The initial index of the range (<tt>from</tt>) must lie between zero3528* and <tt>original.length</tt>, inclusive. The value at3529* <tt>original[from]</tt> is placed into the initial element of the copy3530* (unless <tt>from == original.length</tt> or <tt>from == to</tt>).3531* Values from subsequent elements in the original array are placed into3532* subsequent elements in the copy. The final index of the range3533* (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,3534* may be greater than <tt>original.length</tt>, in which case3535* <tt>(short)0</tt> is placed in all elements of the copy whose index is3536* greater than or equal to <tt>original.length - from</tt>. The length3537* of the returned array will be <tt>to - from</tt>.3538*3539* @param original the array from which a range is to be copied3540* @param from the initial index of the range to be copied, inclusive3541* @param to the final index of the range to be copied, exclusive.3542* (This index may lie outside the array.)3543* @return a new array containing the specified range from the original array,3544* truncated or padded with zeros to obtain the required length3545* @throws ArrayIndexOutOfBoundsException if {@code from < 0}3546* or {@code from > original.length}3547* @throws IllegalArgumentException if <tt>from > to</tt>3548* @throws NullPointerException if <tt>original</tt> is null3549* @since 1.63550*/3551public static short[] copyOfRange(short[] original, int from, int to) {3552int newLength = to - from;3553if (newLength < 0)3554throw new IllegalArgumentException(from + " > " + to);3555short[] copy = new short[newLength];3556System.arraycopy(original, from, copy, 0,3557Math.min(original.length - from, newLength));3558return copy;3559}35603561/**3562* Copies the specified range of the specified array into a new array.3563* The initial index of the range (<tt>from</tt>) must lie between zero3564* and <tt>original.length</tt>, inclusive. The value at3565* <tt>original[from]</tt> is placed into the initial element of the copy3566* (unless <tt>from == original.length</tt> or <tt>from == to</tt>).3567* Values from subsequent elements in the original array are placed into3568* subsequent elements in the copy. The final index of the range3569* (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,3570* may be greater than <tt>original.length</tt>, in which case3571* <tt>0</tt> is placed in all elements of the copy whose index is3572* greater than or equal to <tt>original.length - from</tt>. The length3573* of the returned array will be <tt>to - from</tt>.3574*3575* @param original the array from which a range is to be copied3576* @param from the initial index of the range to be copied, inclusive3577* @param to the final index of the range to be copied, exclusive.3578* (This index may lie outside the array.)3579* @return a new array containing the specified range from the original array,3580* truncated or padded with zeros to obtain the required length3581* @throws ArrayIndexOutOfBoundsException if {@code from < 0}3582* or {@code from > original.length}3583* @throws IllegalArgumentException if <tt>from > to</tt>3584* @throws NullPointerException if <tt>original</tt> is null3585* @since 1.63586*/3587public static int[] copyOfRange(int[] original, int from, int to) {3588int newLength = to - from;3589if (newLength < 0)3590throw new IllegalArgumentException(from + " > " + to);3591int[] copy = new int[newLength];3592System.arraycopy(original, from, copy, 0,3593Math.min(original.length - from, newLength));3594return copy;3595}35963597/**3598* Copies the specified range of the specified array into a new array.3599* The initial index of the range (<tt>from</tt>) must lie between zero3600* and <tt>original.length</tt>, inclusive. The value at3601* <tt>original[from]</tt> is placed into the initial element of the copy3602* (unless <tt>from == original.length</tt> or <tt>from == to</tt>).3603* Values from subsequent elements in the original array are placed into3604* subsequent elements in the copy. The final index of the range3605* (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,3606* may be greater than <tt>original.length</tt>, in which case3607* <tt>0L</tt> is placed in all elements of the copy whose index is3608* greater than or equal to <tt>original.length - from</tt>. The length3609* of the returned array will be <tt>to - from</tt>.3610*3611* @param original the array from which a range is to be copied3612* @param from the initial index of the range to be copied, inclusive3613* @param to the final index of the range to be copied, exclusive.3614* (This index may lie outside the array.)3615* @return a new array containing the specified range from the original array,3616* truncated or padded with zeros to obtain the required length3617* @throws ArrayIndexOutOfBoundsException if {@code from < 0}3618* or {@code from > original.length}3619* @throws IllegalArgumentException if <tt>from > to</tt>3620* @throws NullPointerException if <tt>original</tt> is null3621* @since 1.63622*/3623public static long[] copyOfRange(long[] original, int from, int to) {3624int newLength = to - from;3625if (newLength < 0)3626throw new IllegalArgumentException(from + " > " + to);3627long[] copy = new long[newLength];3628System.arraycopy(original, from, copy, 0,3629Math.min(original.length - from, newLength));3630return copy;3631}36323633/**3634* Copies the specified range of the specified array into a new array.3635* The initial index of the range (<tt>from</tt>) must lie between zero3636* and <tt>original.length</tt>, inclusive. The value at3637* <tt>original[from]</tt> is placed into the initial element of the copy3638* (unless <tt>from == original.length</tt> or <tt>from == to</tt>).3639* Values from subsequent elements in the original array are placed into3640* subsequent elements in the copy. The final index of the range3641* (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,3642* may be greater than <tt>original.length</tt>, in which case3643* <tt>'\\u000'</tt> is placed in all elements of the copy whose index is3644* greater than or equal to <tt>original.length - from</tt>. The length3645* of the returned array will be <tt>to - from</tt>.3646*3647* @param original the array from which a range is to be copied3648* @param from the initial index of the range to be copied, inclusive3649* @param to the final index of the range to be copied, exclusive.3650* (This index may lie outside the array.)3651* @return a new array containing the specified range from the original array,3652* truncated or padded with null characters to obtain the required length3653* @throws ArrayIndexOutOfBoundsException if {@code from < 0}3654* or {@code from > original.length}3655* @throws IllegalArgumentException if <tt>from > to</tt>3656* @throws NullPointerException if <tt>original</tt> is null3657* @since 1.63658*/3659public static char[] copyOfRange(char[] original, int from, int to) {3660int newLength = to - from;3661if (newLength < 0)3662throw new IllegalArgumentException(from + " > " + to);3663char[] copy = new char[newLength];3664System.arraycopy(original, from, copy, 0,3665Math.min(original.length - from, newLength));3666return copy;3667}36683669/**3670* Copies the specified range of the specified array into a new array.3671* The initial index of the range (<tt>from</tt>) must lie between zero3672* and <tt>original.length</tt>, inclusive. The value at3673* <tt>original[from]</tt> is placed into the initial element of the copy3674* (unless <tt>from == original.length</tt> or <tt>from == to</tt>).3675* Values from subsequent elements in the original array are placed into3676* subsequent elements in the copy. The final index of the range3677* (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,3678* may be greater than <tt>original.length</tt>, in which case3679* <tt>0f</tt> is placed in all elements of the copy whose index is3680* greater than or equal to <tt>original.length - from</tt>. The length3681* of the returned array will be <tt>to - from</tt>.3682*3683* @param original the array from which a range is to be copied3684* @param from the initial index of the range to be copied, inclusive3685* @param to the final index of the range to be copied, exclusive.3686* (This index may lie outside the array.)3687* @return a new array containing the specified range from the original array,3688* truncated or padded with zeros to obtain the required length3689* @throws ArrayIndexOutOfBoundsException if {@code from < 0}3690* or {@code from > original.length}3691* @throws IllegalArgumentException if <tt>from > to</tt>3692* @throws NullPointerException if <tt>original</tt> is null3693* @since 1.63694*/3695public static float[] copyOfRange(float[] original, int from, int to) {3696int newLength = to - from;3697if (newLength < 0)3698throw new IllegalArgumentException(from + " > " + to);3699float[] copy = new float[newLength];3700System.arraycopy(original, from, copy, 0,3701Math.min(original.length - from, newLength));3702return copy;3703}37043705/**3706* Copies the specified range of the specified array into a new array.3707* The initial index of the range (<tt>from</tt>) must lie between zero3708* and <tt>original.length</tt>, inclusive. The value at3709* <tt>original[from]</tt> is placed into the initial element of the copy3710* (unless <tt>from == original.length</tt> or <tt>from == to</tt>).3711* Values from subsequent elements in the original array are placed into3712* subsequent elements in the copy. The final index of the range3713* (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,3714* may be greater than <tt>original.length</tt>, in which case3715* <tt>0d</tt> is placed in all elements of the copy whose index is3716* greater than or equal to <tt>original.length - from</tt>. The length3717* of the returned array will be <tt>to - from</tt>.3718*3719* @param original the array from which a range is to be copied3720* @param from the initial index of the range to be copied, inclusive3721* @param to the final index of the range to be copied, exclusive.3722* (This index may lie outside the array.)3723* @return a new array containing the specified range from the original array,3724* truncated or padded with zeros to obtain the required length3725* @throws ArrayIndexOutOfBoundsException if {@code from < 0}3726* or {@code from > original.length}3727* @throws IllegalArgumentException if <tt>from > to</tt>3728* @throws NullPointerException if <tt>original</tt> is null3729* @since 1.63730*/3731public static double[] copyOfRange(double[] original, int from, int to) {3732int newLength = to - from;3733if (newLength < 0)3734throw new IllegalArgumentException(from + " > " + to);3735double[] copy = new double[newLength];3736System.arraycopy(original, from, copy, 0,3737Math.min(original.length - from, newLength));3738return copy;3739}37403741/**3742* Copies the specified range of the specified array into a new array.3743* The initial index of the range (<tt>from</tt>) must lie between zero3744* and <tt>original.length</tt>, inclusive. The value at3745* <tt>original[from]</tt> is placed into the initial element of the copy3746* (unless <tt>from == original.length</tt> or <tt>from == to</tt>).3747* Values from subsequent elements in the original array are placed into3748* subsequent elements in the copy. The final index of the range3749* (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,3750* may be greater than <tt>original.length</tt>, in which case3751* <tt>false</tt> is placed in all elements of the copy whose index is3752* greater than or equal to <tt>original.length - from</tt>. The length3753* of the returned array will be <tt>to - from</tt>.3754*3755* @param original the array from which a range is to be copied3756* @param from the initial index of the range to be copied, inclusive3757* @param to the final index of the range to be copied, exclusive.3758* (This index may lie outside the array.)3759* @return a new array containing the specified range from the original array,3760* truncated or padded with false elements to obtain the required length3761* @throws ArrayIndexOutOfBoundsException if {@code from < 0}3762* or {@code from > original.length}3763* @throws IllegalArgumentException if <tt>from > to</tt>3764* @throws NullPointerException if <tt>original</tt> is null3765* @since 1.63766*/3767public static boolean[] copyOfRange(boolean[] original, int from, int to) {3768int newLength = to - from;3769if (newLength < 0)3770throw new IllegalArgumentException(from + " > " + to);3771boolean[] copy = new boolean[newLength];3772System.arraycopy(original, from, copy, 0,3773Math.min(original.length - from, newLength));3774return copy;3775}37763777// Misc37783779/**3780* Returns a fixed-size list backed by the specified array. (Changes to3781* the returned list "write through" to the array.) This method acts3782* as bridge between array-based and collection-based APIs, in3783* combination with {@link Collection#toArray}. The returned list is3784* serializable and implements {@link RandomAccess}.3785*3786* <p>This method also provides a convenient way to create a fixed-size3787* list initialized to contain several elements:3788* <pre>3789* List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");3790* </pre>3791*3792* @param <T> the class of the objects in the array3793* @param a the array by which the list will be backed3794* @return a list view of the specified array3795*/3796@SafeVarargs3797@SuppressWarnings("varargs")3798public static <T> List<T> asList(T... a) {3799return new ArrayList<>(a);3800}38013802/**3803* @serial include3804*/3805private static class ArrayList<E> extends AbstractList<E>3806implements RandomAccess, java.io.Serializable3807{3808private static final long serialVersionUID = -2764017481108945198L;3809private final E[] a;38103811ArrayList(E[] array) {3812a = Objects.requireNonNull(array);3813}38143815@Override3816public int size() {3817return a.length;3818}38193820@Override3821public Object[] toArray() {3822return a.clone();3823}38243825@Override3826@SuppressWarnings("unchecked")3827public <T> T[] toArray(T[] a) {3828int size = size();3829if (a.length < size)3830return Arrays.copyOf(this.a, size,3831(Class<? extends T[]>) a.getClass());3832System.arraycopy(this.a, 0, a, 0, size);3833if (a.length > size)3834a[size] = null;3835return a;3836}38373838@Override3839public E get(int index) {3840return a[index];3841}38423843@Override3844public E set(int index, E element) {3845E oldValue = a[index];3846a[index] = element;3847return oldValue;3848}38493850@Override3851public int indexOf(Object o) {3852E[] a = this.a;3853if (o == null) {3854for (int i = 0; i < a.length; i++)3855if (a[i] == null)3856return i;3857} else {3858for (int i = 0; i < a.length; i++)3859if (o.equals(a[i]))3860return i;3861}3862return -1;3863}38643865@Override3866public boolean contains(Object o) {3867return indexOf(o) != -1;3868}38693870@Override3871public Spliterator<E> spliterator() {3872return Spliterators.spliterator(a, Spliterator.ORDERED);3873}38743875@Override3876public void forEach(Consumer<? super E> action) {3877Objects.requireNonNull(action);3878for (E e : a) {3879action.accept(e);3880}3881}38823883@Override3884public void replaceAll(UnaryOperator<E> operator) {3885Objects.requireNonNull(operator);3886E[] a = this.a;3887for (int i = 0; i < a.length; i++) {3888a[i] = operator.apply(a[i]);3889}3890}38913892@Override3893public void sort(Comparator<? super E> c) {3894Arrays.sort(a, c);3895}3896}38973898/**3899* Returns a hash code based on the contents of the specified array.3900* For any two <tt>long</tt> arrays <tt>a</tt> and <tt>b</tt>3901* such that <tt>Arrays.equals(a, b)</tt>, it is also the case that3902* <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.3903*3904* <p>The value returned by this method is the same value that would be3905* obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}3906* method on a {@link List} containing a sequence of {@link Long}3907* instances representing the elements of <tt>a</tt> in the same order.3908* If <tt>a</tt> is <tt>null</tt>, this method returns 0.3909*3910* @param a the array whose hash value to compute3911* @return a content-based hash code for <tt>a</tt>3912* @since 1.53913*/3914public static int hashCode(long a[]) {3915if (a == null)3916return 0;39173918int result = 1;3919for (long element : a) {3920int elementHash = (int)(element ^ (element >>> 32));3921result = 31 * result + elementHash;3922}39233924return result;3925}39263927/**3928* Returns a hash code based on the contents of the specified array.3929* For any two non-null <tt>int</tt> arrays <tt>a</tt> and <tt>b</tt>3930* such that <tt>Arrays.equals(a, b)</tt>, it is also the case that3931* <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.3932*3933* <p>The value returned by this method is the same value that would be3934* obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}3935* method on a {@link List} containing a sequence of {@link Integer}3936* instances representing the elements of <tt>a</tt> in the same order.3937* If <tt>a</tt> is <tt>null</tt>, this method returns 0.3938*3939* @param a the array whose hash value to compute3940* @return a content-based hash code for <tt>a</tt>3941* @since 1.53942*/3943public static int hashCode(int a[]) {3944if (a == null)3945return 0;39463947int result = 1;3948for (int element : a)3949result = 31 * result + element;39503951return result;3952}39533954/**3955* Returns a hash code based on the contents of the specified array.3956* For any two <tt>short</tt> arrays <tt>a</tt> and <tt>b</tt>3957* such that <tt>Arrays.equals(a, b)</tt>, it is also the case that3958* <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.3959*3960* <p>The value returned by this method is the same value that would be3961* obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}3962* method on a {@link List} containing a sequence of {@link Short}3963* instances representing the elements of <tt>a</tt> in the same order.3964* If <tt>a</tt> is <tt>null</tt>, this method returns 0.3965*3966* @param a the array whose hash value to compute3967* @return a content-based hash code for <tt>a</tt>3968* @since 1.53969*/3970public static int hashCode(short a[]) {3971if (a == null)3972return 0;39733974int result = 1;3975for (short element : a)3976result = 31 * result + element;39773978return result;3979}39803981/**3982* Returns a hash code based on the contents of the specified array.3983* For any two <tt>char</tt> arrays <tt>a</tt> and <tt>b</tt>3984* such that <tt>Arrays.equals(a, b)</tt>, it is also the case that3985* <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.3986*3987* <p>The value returned by this method is the same value that would be3988* obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}3989* method on a {@link List} containing a sequence of {@link Character}3990* instances representing the elements of <tt>a</tt> in the same order.3991* If <tt>a</tt> is <tt>null</tt>, this method returns 0.3992*3993* @param a the array whose hash value to compute3994* @return a content-based hash code for <tt>a</tt>3995* @since 1.53996*/3997public static int hashCode(char a[]) {3998if (a == null)3999return 0;40004001int result = 1;4002for (char element : a)4003result = 31 * result + element;40044005return result;4006}40074008/**4009* Returns a hash code based on the contents of the specified array.4010* For any two <tt>byte</tt> arrays <tt>a</tt> and <tt>b</tt>4011* such that <tt>Arrays.equals(a, b)</tt>, it is also the case that4012* <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.4013*4014* <p>The value returned by this method is the same value that would be4015* obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}4016* method on a {@link List} containing a sequence of {@link Byte}4017* instances representing the elements of <tt>a</tt> in the same order.4018* If <tt>a</tt> is <tt>null</tt>, this method returns 0.4019*4020* @param a the array whose hash value to compute4021* @return a content-based hash code for <tt>a</tt>4022* @since 1.54023*/4024public static int hashCode(byte a[]) {4025if (a == null)4026return 0;40274028int result = 1;4029for (byte element : a)4030result = 31 * result + element;40314032return result;4033}40344035/**4036* Returns a hash code based on the contents of the specified array.4037* For any two <tt>boolean</tt> arrays <tt>a</tt> and <tt>b</tt>4038* such that <tt>Arrays.equals(a, b)</tt>, it is also the case that4039* <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.4040*4041* <p>The value returned by this method is the same value that would be4042* obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}4043* method on a {@link List} containing a sequence of {@link Boolean}4044* instances representing the elements of <tt>a</tt> in the same order.4045* If <tt>a</tt> is <tt>null</tt>, this method returns 0.4046*4047* @param a the array whose hash value to compute4048* @return a content-based hash code for <tt>a</tt>4049* @since 1.54050*/4051public static int hashCode(boolean a[]) {4052if (a == null)4053return 0;40544055int result = 1;4056for (boolean element : a)4057result = 31 * result + (element ? 1231 : 1237);40584059return result;4060}40614062/**4063* Returns a hash code based on the contents of the specified array.4064* For any two <tt>float</tt> arrays <tt>a</tt> and <tt>b</tt>4065* such that <tt>Arrays.equals(a, b)</tt>, it is also the case that4066* <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.4067*4068* <p>The value returned by this method is the same value that would be4069* obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}4070* method on a {@link List} containing a sequence of {@link Float}4071* instances representing the elements of <tt>a</tt> in the same order.4072* If <tt>a</tt> is <tt>null</tt>, this method returns 0.4073*4074* @param a the array whose hash value to compute4075* @return a content-based hash code for <tt>a</tt>4076* @since 1.54077*/4078public static int hashCode(float a[]) {4079if (a == null)4080return 0;40814082int result = 1;4083for (float element : a)4084result = 31 * result + Float.floatToIntBits(element);40854086return result;4087}40884089/**4090* Returns a hash code based on the contents of the specified array.4091* For any two <tt>double</tt> arrays <tt>a</tt> and <tt>b</tt>4092* such that <tt>Arrays.equals(a, b)</tt>, it is also the case that4093* <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.4094*4095* <p>The value returned by this method is the same value that would be4096* obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>}4097* method on a {@link List} containing a sequence of {@link Double}4098* instances representing the elements of <tt>a</tt> in the same order.4099* If <tt>a</tt> is <tt>null</tt>, this method returns 0.4100*4101* @param a the array whose hash value to compute4102* @return a content-based hash code for <tt>a</tt>4103* @since 1.54104*/4105public static int hashCode(double a[]) {4106if (a == null)4107return 0;41084109int result = 1;4110for (double element : a) {4111long bits = Double.doubleToLongBits(element);4112result = 31 * result + (int)(bits ^ (bits >>> 32));4113}4114return result;4115}41164117/**4118* Returns a hash code based on the contents of the specified array. If4119* the array contains other arrays as elements, the hash code is based on4120* their identities rather than their contents. It is therefore4121* acceptable to invoke this method on an array that contains itself as an4122* element, either directly or indirectly through one or more levels of4123* arrays.4124*4125* <p>For any two arrays <tt>a</tt> and <tt>b</tt> such that4126* <tt>Arrays.equals(a, b)</tt>, it is also the case that4127* <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>.4128*4129* <p>The value returned by this method is equal to the value that would4130* be returned by <tt>Arrays.asList(a).hashCode()</tt>, unless <tt>a</tt>4131* is <tt>null</tt>, in which case <tt>0</tt> is returned.4132*4133* @param a the array whose content-based hash code to compute4134* @return a content-based hash code for <tt>a</tt>4135* @see #deepHashCode(Object[])4136* @since 1.54137*/4138public static int hashCode(Object a[]) {4139if (a == null)4140return 0;41414142int result = 1;41434144for (Object element : a)4145result = 31 * result + (element == null ? 0 : element.hashCode());41464147return result;4148}41494150/**4151* Returns a hash code based on the "deep contents" of the specified4152* array. If the array contains other arrays as elements, the4153* hash code is based on their contents and so on, ad infinitum.4154* It is therefore unacceptable to invoke this method on an array that4155* contains itself as an element, either directly or indirectly through4156* one or more levels of arrays. The behavior of such an invocation is4157* undefined.4158*4159* <p>For any two arrays <tt>a</tt> and <tt>b</tt> such that4160* <tt>Arrays.deepEquals(a, b)</tt>, it is also the case that4161* <tt>Arrays.deepHashCode(a) == Arrays.deepHashCode(b)</tt>.4162*4163* <p>The computation of the value returned by this method is similar to4164* that of the value returned by {@link List#hashCode()} on a list4165* containing the same elements as <tt>a</tt> in the same order, with one4166* difference: If an element <tt>e</tt> of <tt>a</tt> is itself an array,4167* its hash code is computed not by calling <tt>e.hashCode()</tt>, but as4168* by calling the appropriate overloading of <tt>Arrays.hashCode(e)</tt>4169* if <tt>e</tt> is an array of a primitive type, or as by calling4170* <tt>Arrays.deepHashCode(e)</tt> recursively if <tt>e</tt> is an array4171* of a reference type. If <tt>a</tt> is <tt>null</tt>, this method4172* returns 0.4173*4174* @param a the array whose deep-content-based hash code to compute4175* @return a deep-content-based hash code for <tt>a</tt>4176* @see #hashCode(Object[])4177* @since 1.54178*/4179public static int deepHashCode(Object a[]) {4180if (a == null)4181return 0;41824183int result = 1;41844185for (Object element : a) {4186int elementHash = 0;4187if (element instanceof Object[])4188elementHash = deepHashCode((Object[]) element);4189else if (element instanceof byte[])4190elementHash = hashCode((byte[]) element);4191else if (element instanceof short[])4192elementHash = hashCode((short[]) element);4193else if (element instanceof int[])4194elementHash = hashCode((int[]) element);4195else if (element instanceof long[])4196elementHash = hashCode((long[]) element);4197else if (element instanceof char[])4198elementHash = hashCode((char[]) element);4199else if (element instanceof float[])4200elementHash = hashCode((float[]) element);4201else if (element instanceof double[])4202elementHash = hashCode((double[]) element);4203else if (element instanceof boolean[])4204elementHash = hashCode((boolean[]) element);4205else if (element != null)4206elementHash = element.hashCode();42074208result = 31 * result + elementHash;4209}42104211return result;4212}42134214/**4215* Returns <tt>true</tt> if the two specified arrays are <i>deeply4216* equal</i> to one another. Unlike the {@link #equals(Object[],Object[])}4217* method, this method is appropriate for use with nested arrays of4218* arbitrary depth.4219*4220* <p>Two array references are considered deeply equal if both4221* are <tt>null</tt>, or if they refer to arrays that contain the same4222* number of elements and all corresponding pairs of elements in the two4223* arrays are deeply equal.4224*4225* <p>Two possibly <tt>null</tt> elements <tt>e1</tt> and <tt>e2</tt> are4226* deeply equal if any of the following conditions hold:4227* <ul>4228* <li> <tt>e1</tt> and <tt>e2</tt> are both arrays of object reference4229* types, and <tt>Arrays.deepEquals(e1, e2) would return true</tt>4230* <li> <tt>e1</tt> and <tt>e2</tt> are arrays of the same primitive4231* type, and the appropriate overloading of4232* <tt>Arrays.equals(e1, e2)</tt> would return true.4233* <li> <tt>e1 == e2</tt>4234* <li> <tt>e1.equals(e2)</tt> would return true.4235* </ul>4236* Note that this definition permits <tt>null</tt> elements at any depth.4237*4238* <p>If either of the specified arrays contain themselves as elements4239* either directly or indirectly through one or more levels of arrays,4240* the behavior of this method is undefined.4241*4242* @param a1 one array to be tested for equality4243* @param a2 the other array to be tested for equality4244* @return <tt>true</tt> if the two arrays are equal4245* @see #equals(Object[],Object[])4246* @see Objects#deepEquals(Object, Object)4247* @since 1.54248*/4249public static boolean deepEquals(Object[] a1, Object[] a2) {4250if (a1 == a2)4251return true;4252if (a1 == null || a2==null)4253return false;4254int length = a1.length;4255if (a2.length != length)4256return false;42574258for (int i = 0; i < length; i++) {4259Object e1 = a1[i];4260Object e2 = a2[i];42614262if (e1 == e2)4263continue;4264if (e1 == null)4265return false;42664267// Figure out whether the two elements are equal4268boolean eq = deepEquals0(e1, e2);42694270if (!eq)4271return false;4272}4273return true;4274}42754276static boolean deepEquals0(Object e1, Object e2) {4277assert e1 != null;4278boolean eq;4279if (e1 instanceof Object[] && e2 instanceof Object[])4280eq = deepEquals ((Object[]) e1, (Object[]) e2);4281else if (e1 instanceof byte[] && e2 instanceof byte[])4282eq = equals((byte[]) e1, (byte[]) e2);4283else if (e1 instanceof short[] && e2 instanceof short[])4284eq = equals((short[]) e1, (short[]) e2);4285else if (e1 instanceof int[] && e2 instanceof int[])4286eq = equals((int[]) e1, (int[]) e2);4287else if (e1 instanceof long[] && e2 instanceof long[])4288eq = equals((long[]) e1, (long[]) e2);4289else if (e1 instanceof char[] && e2 instanceof char[])4290eq = equals((char[]) e1, (char[]) e2);4291else if (e1 instanceof float[] && e2 instanceof float[])4292eq = equals((float[]) e1, (float[]) e2);4293else if (e1 instanceof double[] && e2 instanceof double[])4294eq = equals((double[]) e1, (double[]) e2);4295else if (e1 instanceof boolean[] && e2 instanceof boolean[])4296eq = equals((boolean[]) e1, (boolean[]) e2);4297else4298eq = e1.equals(e2);4299return eq;4300}43014302/**4303* Returns a string representation of the contents of the specified array.4304* The string representation consists of a list of the array's elements,4305* enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are4306* separated by the characters <tt>", "</tt> (a comma followed by a4307* space). Elements are converted to strings as by4308* <tt>String.valueOf(long)</tt>. Returns <tt>"null"</tt> if <tt>a</tt>4309* is <tt>null</tt>.4310*4311* @param a the array whose string representation to return4312* @return a string representation of <tt>a</tt>4313* @since 1.54314*/4315public static String toString(long[] a) {4316if (a == null)4317return "null";4318int iMax = a.length - 1;4319if (iMax == -1)4320return "[]";43214322StringBuilder b = new StringBuilder();4323b.append('[');4324for (int i = 0; ; i++) {4325b.append(a[i]);4326if (i == iMax)4327return b.append(']').toString();4328b.append(", ");4329}4330}43314332/**4333* Returns a string representation of the contents of the specified array.4334* The string representation consists of a list of the array's elements,4335* enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are4336* separated by the characters <tt>", "</tt> (a comma followed by a4337* space). Elements are converted to strings as by4338* <tt>String.valueOf(int)</tt>. Returns <tt>"null"</tt> if <tt>a</tt> is4339* <tt>null</tt>.4340*4341* @param a the array whose string representation to return4342* @return a string representation of <tt>a</tt>4343* @since 1.54344*/4345public static String toString(int[] a) {4346if (a == null)4347return "null";4348int iMax = a.length - 1;4349if (iMax == -1)4350return "[]";43514352StringBuilder b = new StringBuilder();4353b.append('[');4354for (int i = 0; ; i++) {4355b.append(a[i]);4356if (i == iMax)4357return b.append(']').toString();4358b.append(", ");4359}4360}43614362/**4363* Returns a string representation of the contents of the specified array.4364* The string representation consists of a list of the array's elements,4365* enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are4366* separated by the characters <tt>", "</tt> (a comma followed by a4367* space). Elements are converted to strings as by4368* <tt>String.valueOf(short)</tt>. Returns <tt>"null"</tt> if <tt>a</tt>4369* is <tt>null</tt>.4370*4371* @param a the array whose string representation to return4372* @return a string representation of <tt>a</tt>4373* @since 1.54374*/4375public static String toString(short[] a) {4376if (a == null)4377return "null";4378int iMax = a.length - 1;4379if (iMax == -1)4380return "[]";43814382StringBuilder b = new StringBuilder();4383b.append('[');4384for (int i = 0; ; i++) {4385b.append(a[i]);4386if (i == iMax)4387return b.append(']').toString();4388b.append(", ");4389}4390}43914392/**4393* Returns a string representation of the contents of the specified array.4394* The string representation consists of a list of the array's elements,4395* enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are4396* separated by the characters <tt>", "</tt> (a comma followed by a4397* space). Elements are converted to strings as by4398* <tt>String.valueOf(char)</tt>. Returns <tt>"null"</tt> if <tt>a</tt>4399* is <tt>null</tt>.4400*4401* @param a the array whose string representation to return4402* @return a string representation of <tt>a</tt>4403* @since 1.54404*/4405public static String toString(char[] a) {4406if (a == null)4407return "null";4408int iMax = a.length - 1;4409if (iMax == -1)4410return "[]";44114412StringBuilder b = new StringBuilder();4413b.append('[');4414for (int i = 0; ; i++) {4415b.append(a[i]);4416if (i == iMax)4417return b.append(']').toString();4418b.append(", ");4419}4420}44214422/**4423* Returns a string representation of the contents of the specified array.4424* The string representation consists of a list of the array's elements,4425* enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements4426* are separated by the characters <tt>", "</tt> (a comma followed4427* by a space). Elements are converted to strings as by4428* <tt>String.valueOf(byte)</tt>. Returns <tt>"null"</tt> if4429* <tt>a</tt> is <tt>null</tt>.4430*4431* @param a the array whose string representation to return4432* @return a string representation of <tt>a</tt>4433* @since 1.54434*/4435public static String toString(byte[] a) {4436if (a == null)4437return "null";4438int iMax = a.length - 1;4439if (iMax == -1)4440return "[]";44414442StringBuilder b = new StringBuilder();4443b.append('[');4444for (int i = 0; ; i++) {4445b.append(a[i]);4446if (i == iMax)4447return b.append(']').toString();4448b.append(", ");4449}4450}44514452/**4453* Returns a string representation of the contents of the specified array.4454* The string representation consists of a list of the array's elements,4455* enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are4456* separated by the characters <tt>", "</tt> (a comma followed by a4457* space). Elements are converted to strings as by4458* <tt>String.valueOf(boolean)</tt>. Returns <tt>"null"</tt> if4459* <tt>a</tt> is <tt>null</tt>.4460*4461* @param a the array whose string representation to return4462* @return a string representation of <tt>a</tt>4463* @since 1.54464*/4465public static String toString(boolean[] a) {4466if (a == null)4467return "null";4468int iMax = a.length - 1;4469if (iMax == -1)4470return "[]";44714472StringBuilder b = new StringBuilder();4473b.append('[');4474for (int i = 0; ; i++) {4475b.append(a[i]);4476if (i == iMax)4477return b.append(']').toString();4478b.append(", ");4479}4480}44814482/**4483* Returns a string representation of the contents of the specified array.4484* The string representation consists of a list of the array's elements,4485* enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are4486* separated by the characters <tt>", "</tt> (a comma followed by a4487* space). Elements are converted to strings as by4488* <tt>String.valueOf(float)</tt>. Returns <tt>"null"</tt> if <tt>a</tt>4489* is <tt>null</tt>.4490*4491* @param a the array whose string representation to return4492* @return a string representation of <tt>a</tt>4493* @since 1.54494*/4495public static String toString(float[] a) {4496if (a == null)4497return "null";44984499int iMax = a.length - 1;4500if (iMax == -1)4501return "[]";45024503StringBuilder b = new StringBuilder();4504b.append('[');4505for (int i = 0; ; i++) {4506b.append(a[i]);4507if (i == iMax)4508return b.append(']').toString();4509b.append(", ");4510}4511}45124513/**4514* Returns a string representation of the contents of the specified array.4515* The string representation consists of a list of the array's elements,4516* enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are4517* separated by the characters <tt>", "</tt> (a comma followed by a4518* space). Elements are converted to strings as by4519* <tt>String.valueOf(double)</tt>. Returns <tt>"null"</tt> if <tt>a</tt>4520* is <tt>null</tt>.4521*4522* @param a the array whose string representation to return4523* @return a string representation of <tt>a</tt>4524* @since 1.54525*/4526public static String toString(double[] a) {4527if (a == null)4528return "null";4529int iMax = a.length - 1;4530if (iMax == -1)4531return "[]";45324533StringBuilder b = new StringBuilder();4534b.append('[');4535for (int i = 0; ; i++) {4536b.append(a[i]);4537if (i == iMax)4538return b.append(']').toString();4539b.append(", ");4540}4541}45424543/**4544* Returns a string representation of the contents of the specified array.4545* If the array contains other arrays as elements, they are converted to4546* strings by the {@link Object#toString} method inherited from4547* <tt>Object</tt>, which describes their <i>identities</i> rather than4548* their contents.4549*4550* <p>The value returned by this method is equal to the value that would4551* be returned by <tt>Arrays.asList(a).toString()</tt>, unless <tt>a</tt>4552* is <tt>null</tt>, in which case <tt>"null"</tt> is returned.4553*4554* @param a the array whose string representation to return4555* @return a string representation of <tt>a</tt>4556* @see #deepToString(Object[])4557* @since 1.54558*/4559public static String toString(Object[] a) {4560if (a == null)4561return "null";45624563int iMax = a.length - 1;4564if (iMax == -1)4565return "[]";45664567StringBuilder b = new StringBuilder();4568b.append('[');4569for (int i = 0; ; i++) {4570b.append(String.valueOf(a[i]));4571if (i == iMax)4572return b.append(']').toString();4573b.append(", ");4574}4575}45764577/**4578* Returns a string representation of the "deep contents" of the specified4579* array. If the array contains other arrays as elements, the string4580* representation contains their contents and so on. This method is4581* designed for converting multidimensional arrays to strings.4582*4583* <p>The string representation consists of a list of the array's4584* elements, enclosed in square brackets (<tt>"[]"</tt>). Adjacent4585* elements are separated by the characters <tt>", "</tt> (a comma4586* followed by a space). Elements are converted to strings as by4587* <tt>String.valueOf(Object)</tt>, unless they are themselves4588* arrays.4589*4590* <p>If an element <tt>e</tt> is an array of a primitive type, it is4591* converted to a string as by invoking the appropriate overloading of4592* <tt>Arrays.toString(e)</tt>. If an element <tt>e</tt> is an array of a4593* reference type, it is converted to a string as by invoking4594* this method recursively.4595*4596* <p>To avoid infinite recursion, if the specified array contains itself4597* as an element, or contains an indirect reference to itself through one4598* or more levels of arrays, the self-reference is converted to the string4599* <tt>"[...]"</tt>. For example, an array containing only a reference4600* to itself would be rendered as <tt>"[[...]]"</tt>.4601*4602* <p>This method returns <tt>"null"</tt> if the specified array4603* is <tt>null</tt>.4604*4605* @param a the array whose string representation to return4606* @return a string representation of <tt>a</tt>4607* @see #toString(Object[])4608* @since 1.54609*/4610public static String deepToString(Object[] a) {4611if (a == null)4612return "null";46134614int bufLen = 20 * a.length;4615if (a.length != 0 && bufLen <= 0)4616bufLen = Integer.MAX_VALUE;4617StringBuilder buf = new StringBuilder(bufLen);4618deepToString(a, buf, new HashSet<Object[]>());4619return buf.toString();4620}46214622private static void deepToString(Object[] a, StringBuilder buf,4623Set<Object[]> dejaVu) {4624if (a == null) {4625buf.append("null");4626return;4627}4628int iMax = a.length - 1;4629if (iMax == -1) {4630buf.append("[]");4631return;4632}46334634dejaVu.add(a);4635buf.append('[');4636for (int i = 0; ; i++) {46374638Object element = a[i];4639if (element == null) {4640buf.append("null");4641} else {4642Class<?> eClass = element.getClass();46434644if (eClass.isArray()) {4645if (eClass == byte[].class)4646buf.append(toString((byte[]) element));4647else if (eClass == short[].class)4648buf.append(toString((short[]) element));4649else if (eClass == int[].class)4650buf.append(toString((int[]) element));4651else if (eClass == long[].class)4652buf.append(toString((long[]) element));4653else if (eClass == char[].class)4654buf.append(toString((char[]) element));4655else if (eClass == float[].class)4656buf.append(toString((float[]) element));4657else if (eClass == double[].class)4658buf.append(toString((double[]) element));4659else if (eClass == boolean[].class)4660buf.append(toString((boolean[]) element));4661else { // element is an array of object references4662if (dejaVu.contains(element))4663buf.append("[...]");4664else4665deepToString((Object[])element, buf, dejaVu);4666}4667} else { // element is non-null and not an array4668buf.append(element.toString());4669}4670}4671if (i == iMax)4672break;4673buf.append(", ");4674}4675buf.append(']');4676dejaVu.remove(a);4677}467846794680/**4681* Set all elements of the specified array, using the provided4682* generator function to compute each element.4683*4684* <p>If the generator function throws an exception, it is relayed to4685* the caller and the array is left in an indeterminate state.4686*4687* @param <T> type of elements of the array4688* @param array array to be initialized4689* @param generator a function accepting an index and producing the desired4690* value for that position4691* @throws NullPointerException if the generator is null4692* @since 1.84693*/4694public static <T> void setAll(T[] array, IntFunction<? extends T> generator) {4695Objects.requireNonNull(generator);4696for (int i = 0; i < array.length; i++)4697array[i] = generator.apply(i);4698}46994700/**4701* Set all elements of the specified array, in parallel, using the4702* provided generator function to compute each element.4703*4704* <p>If the generator function throws an exception, an unchecked exception4705* is thrown from {@code parallelSetAll} and the array is left in an4706* indeterminate state.4707*4708* @param <T> type of elements of the array4709* @param array array to be initialized4710* @param generator a function accepting an index and producing the desired4711* value for that position4712* @throws NullPointerException if the generator is null4713* @since 1.84714*/4715public static <T> void parallelSetAll(T[] array, IntFunction<? extends T> generator) {4716Objects.requireNonNull(generator);4717IntStream.range(0, array.length).parallel().forEach(i -> { array[i] = generator.apply(i); });4718}47194720/**4721* Set all elements of the specified array, using the provided4722* generator function to compute each element.4723*4724* <p>If the generator function throws an exception, it is relayed to4725* the caller and the array is left in an indeterminate state.4726*4727* @param array array to be initialized4728* @param generator a function accepting an index and producing the desired4729* value for that position4730* @throws NullPointerException if the generator is null4731* @since 1.84732*/4733public static void setAll(int[] array, IntUnaryOperator generator) {4734Objects.requireNonNull(generator);4735for (int i = 0; i < array.length; i++)4736array[i] = generator.applyAsInt(i);4737}47384739/**4740* Set all elements of the specified array, in parallel, using the4741* provided generator function to compute each element.4742*4743* <p>If the generator function throws an exception, an unchecked exception4744* is thrown from {@code parallelSetAll} and the array is left in an4745* indeterminate state.4746*4747* @param array array to be initialized4748* @param generator a function accepting an index and producing the desired4749* value for that position4750* @throws NullPointerException if the generator is null4751* @since 1.84752*/4753public static void parallelSetAll(int[] array, IntUnaryOperator generator) {4754Objects.requireNonNull(generator);4755IntStream.range(0, array.length).parallel().forEach(i -> { array[i] = generator.applyAsInt(i); });4756}47574758/**4759* Set all elements of the specified array, using the provided4760* generator function to compute each element.4761*4762* <p>If the generator function throws an exception, it is relayed to4763* the caller and the array is left in an indeterminate state.4764*4765* @param array array to be initialized4766* @param generator a function accepting an index and producing the desired4767* value for that position4768* @throws NullPointerException if the generator is null4769* @since 1.84770*/4771public static void setAll(long[] array, IntToLongFunction generator) {4772Objects.requireNonNull(generator);4773for (int i = 0; i < array.length; i++)4774array[i] = generator.applyAsLong(i);4775}47764777/**4778* Set all elements of the specified array, in parallel, using the4779* provided generator function to compute each element.4780*4781* <p>If the generator function throws an exception, an unchecked exception4782* is thrown from {@code parallelSetAll} and the array is left in an4783* indeterminate state.4784*4785* @param array array to be initialized4786* @param generator a function accepting an index and producing the desired4787* value for that position4788* @throws NullPointerException if the generator is null4789* @since 1.84790*/4791public static void parallelSetAll(long[] array, IntToLongFunction generator) {4792Objects.requireNonNull(generator);4793IntStream.range(0, array.length).parallel().forEach(i -> { array[i] = generator.applyAsLong(i); });4794}47954796/**4797* Set all elements of the specified array, using the provided4798* generator function to compute each element.4799*4800* <p>If the generator function throws an exception, it is relayed to4801* the caller and the array is left in an indeterminate state.4802*4803* @param array array to be initialized4804* @param generator a function accepting an index and producing the desired4805* value for that position4806* @throws NullPointerException if the generator is null4807* @since 1.84808*/4809public static void setAll(double[] array, IntToDoubleFunction generator) {4810Objects.requireNonNull(generator);4811for (int i = 0; i < array.length; i++)4812array[i] = generator.applyAsDouble(i);4813}48144815/**4816* Set all elements of the specified array, in parallel, using the4817* provided generator function to compute each element.4818*4819* <p>If the generator function throws an exception, an unchecked exception4820* is thrown from {@code parallelSetAll} and the array is left in an4821* indeterminate state.4822*4823* @param array array to be initialized4824* @param generator a function accepting an index and producing the desired4825* value for that position4826* @throws NullPointerException if the generator is null4827* @since 1.84828*/4829public static void parallelSetAll(double[] array, IntToDoubleFunction generator) {4830Objects.requireNonNull(generator);4831IntStream.range(0, array.length).parallel().forEach(i -> { array[i] = generator.applyAsDouble(i); });4832}48334834/**4835* Returns a {@link Spliterator} covering all of the specified array.4836*4837* <p>The spliterator reports {@link Spliterator#SIZED},4838* {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and4839* {@link Spliterator#IMMUTABLE}.4840*4841* @param <T> type of elements4842* @param array the array, assumed to be unmodified during use4843* @return a spliterator for the array elements4844* @since 1.84845*/4846public static <T> Spliterator<T> spliterator(T[] array) {4847return Spliterators.spliterator(array,4848Spliterator.ORDERED | Spliterator.IMMUTABLE);4849}48504851/**4852* Returns a {@link Spliterator} covering the specified range of the4853* specified array.4854*4855* <p>The spliterator reports {@link Spliterator#SIZED},4856* {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and4857* {@link Spliterator#IMMUTABLE}.4858*4859* @param <T> type of elements4860* @param array the array, assumed to be unmodified during use4861* @param startInclusive the first index to cover, inclusive4862* @param endExclusive index immediately past the last index to cover4863* @return a spliterator for the array elements4864* @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is4865* negative, {@code endExclusive} is less than4866* {@code startInclusive}, or {@code endExclusive} is greater than4867* the array size4868* @since 1.84869*/4870public static <T> Spliterator<T> spliterator(T[] array, int startInclusive, int endExclusive) {4871return Spliterators.spliterator(array, startInclusive, endExclusive,4872Spliterator.ORDERED | Spliterator.IMMUTABLE);4873}48744875/**4876* Returns a {@link Spliterator.OfInt} covering all of the specified array.4877*4878* <p>The spliterator reports {@link Spliterator#SIZED},4879* {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and4880* {@link Spliterator#IMMUTABLE}.4881*4882* @param array the array, assumed to be unmodified during use4883* @return a spliterator for the array elements4884* @since 1.84885*/4886public static Spliterator.OfInt spliterator(int[] array) {4887return Spliterators.spliterator(array,4888Spliterator.ORDERED | Spliterator.IMMUTABLE);4889}48904891/**4892* Returns a {@link Spliterator.OfInt} covering the specified range of the4893* specified array.4894*4895* <p>The spliterator reports {@link Spliterator#SIZED},4896* {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and4897* {@link Spliterator#IMMUTABLE}.4898*4899* @param array the array, assumed to be unmodified during use4900* @param startInclusive the first index to cover, inclusive4901* @param endExclusive index immediately past the last index to cover4902* @return a spliterator for the array elements4903* @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is4904* negative, {@code endExclusive} is less than4905* {@code startInclusive}, or {@code endExclusive} is greater than4906* the array size4907* @since 1.84908*/4909public static Spliterator.OfInt spliterator(int[] array, int startInclusive, int endExclusive) {4910return Spliterators.spliterator(array, startInclusive, endExclusive,4911Spliterator.ORDERED | Spliterator.IMMUTABLE);4912}49134914/**4915* Returns a {@link Spliterator.OfLong} covering all of the specified array.4916*4917* <p>The spliterator reports {@link Spliterator#SIZED},4918* {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and4919* {@link Spliterator#IMMUTABLE}.4920*4921* @param array the array, assumed to be unmodified during use4922* @return the spliterator for the array elements4923* @since 1.84924*/4925public static Spliterator.OfLong spliterator(long[] array) {4926return Spliterators.spliterator(array,4927Spliterator.ORDERED | Spliterator.IMMUTABLE);4928}49294930/**4931* Returns a {@link Spliterator.OfLong} covering the specified range of the4932* specified array.4933*4934* <p>The spliterator reports {@link Spliterator#SIZED},4935* {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and4936* {@link Spliterator#IMMUTABLE}.4937*4938* @param array the array, assumed to be unmodified during use4939* @param startInclusive the first index to cover, inclusive4940* @param endExclusive index immediately past the last index to cover4941* @return a spliterator for the array elements4942* @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is4943* negative, {@code endExclusive} is less than4944* {@code startInclusive}, or {@code endExclusive} is greater than4945* the array size4946* @since 1.84947*/4948public static Spliterator.OfLong spliterator(long[] array, int startInclusive, int endExclusive) {4949return Spliterators.spliterator(array, startInclusive, endExclusive,4950Spliterator.ORDERED | Spliterator.IMMUTABLE);4951}49524953/**4954* Returns a {@link Spliterator.OfDouble} covering all of the specified4955* array.4956*4957* <p>The spliterator reports {@link Spliterator#SIZED},4958* {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and4959* {@link Spliterator#IMMUTABLE}.4960*4961* @param array the array, assumed to be unmodified during use4962* @return a spliterator for the array elements4963* @since 1.84964*/4965public static Spliterator.OfDouble spliterator(double[] array) {4966return Spliterators.spliterator(array,4967Spliterator.ORDERED | Spliterator.IMMUTABLE);4968}49694970/**4971* Returns a {@link Spliterator.OfDouble} covering the specified range of4972* the specified array.4973*4974* <p>The spliterator reports {@link Spliterator#SIZED},4975* {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and4976* {@link Spliterator#IMMUTABLE}.4977*4978* @param array the array, assumed to be unmodified during use4979* @param startInclusive the first index to cover, inclusive4980* @param endExclusive index immediately past the last index to cover4981* @return a spliterator for the array elements4982* @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is4983* negative, {@code endExclusive} is less than4984* {@code startInclusive}, or {@code endExclusive} is greater than4985* the array size4986* @since 1.84987*/4988public static Spliterator.OfDouble spliterator(double[] array, int startInclusive, int endExclusive) {4989return Spliterators.spliterator(array, startInclusive, endExclusive,4990Spliterator.ORDERED | Spliterator.IMMUTABLE);4991}49924993/**4994* Returns a sequential {@link Stream} with the specified array as its4995* source.4996*4997* @param <T> The type of the array elements4998* @param array The array, assumed to be unmodified during use4999* @return a {@code Stream} for the array5000* @since 1.85001*/5002public static <T> Stream<T> stream(T[] array) {5003return stream(array, 0, array.length);5004}50055006/**5007* Returns a sequential {@link Stream} with the specified range of the5008* specified array as its source.5009*5010* @param <T> the type of the array elements5011* @param array the array, assumed to be unmodified during use5012* @param startInclusive the first index to cover, inclusive5013* @param endExclusive index immediately past the last index to cover5014* @return a {@code Stream} for the array range5015* @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is5016* negative, {@code endExclusive} is less than5017* {@code startInclusive}, or {@code endExclusive} is greater than5018* the array size5019* @since 1.85020*/5021public static <T> Stream<T> stream(T[] array, int startInclusive, int endExclusive) {5022return StreamSupport.stream(spliterator(array, startInclusive, endExclusive), false);5023}50245025/**5026* Returns a sequential {@link IntStream} with the specified array as its5027* source.5028*5029* @param array the array, assumed to be unmodified during use5030* @return an {@code IntStream} for the array5031* @since 1.85032*/5033public static IntStream stream(int[] array) {5034return stream(array, 0, array.length);5035}50365037/**5038* Returns a sequential {@link IntStream} with the specified range of the5039* specified array as its source.5040*5041* @param array the array, assumed to be unmodified during use5042* @param startInclusive the first index to cover, inclusive5043* @param endExclusive index immediately past the last index to cover5044* @return an {@code IntStream} for the array range5045* @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is5046* negative, {@code endExclusive} is less than5047* {@code startInclusive}, or {@code endExclusive} is greater than5048* the array size5049* @since 1.85050*/5051public static IntStream stream(int[] array, int startInclusive, int endExclusive) {5052return StreamSupport.intStream(spliterator(array, startInclusive, endExclusive), false);5053}50545055/**5056* Returns a sequential {@link LongStream} with the specified array as its5057* source.5058*5059* @param array the array, assumed to be unmodified during use5060* @return a {@code LongStream} for the array5061* @since 1.85062*/5063public static LongStream stream(long[] array) {5064return stream(array, 0, array.length);5065}50665067/**5068* Returns a sequential {@link LongStream} with the specified range of the5069* specified array as its source.5070*5071* @param array the array, assumed to be unmodified during use5072* @param startInclusive the first index to cover, inclusive5073* @param endExclusive index immediately past the last index to cover5074* @return a {@code LongStream} for the array range5075* @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is5076* negative, {@code endExclusive} is less than5077* {@code startInclusive}, or {@code endExclusive} is greater than5078* the array size5079* @since 1.85080*/5081public static LongStream stream(long[] array, int startInclusive, int endExclusive) {5082return StreamSupport.longStream(spliterator(array, startInclusive, endExclusive), false);5083}50845085/**5086* Returns a sequential {@link DoubleStream} with the specified array as its5087* source.5088*5089* @param array the array, assumed to be unmodified during use5090* @return a {@code DoubleStream} for the array5091* @since 1.85092*/5093public static DoubleStream stream(double[] array) {5094return stream(array, 0, array.length);5095}50965097/**5098* Returns a sequential {@link DoubleStream} with the specified range of the5099* specified array as its source.5100*5101* @param array the array, assumed to be unmodified during use5102* @param startInclusive the first index to cover, inclusive5103* @param endExclusive index immediately past the last index to cover5104* @return a {@code DoubleStream} for the array range5105* @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is5106* negative, {@code endExclusive} is less than5107* {@code startInclusive}, or {@code endExclusive} is greater than5108* the array size5109* @since 1.85110*/5111public static DoubleStream stream(double[] array, int startInclusive, int endExclusive) {5112return StreamSupport.doubleStream(spliterator(array, startInclusive, endExclusive), false);5113}5114}511551165117