java.util.Arrays.parallelSort()方法用于将指定范围的对象数组排序为升序,根据其元素的自然顺序。要排序的范围从索引 fromIndex(包含)扩展到索引 toIndex(不包含)。 (如果 fromIndex==toIndex,则要排序的范围为空。)此范围内的所有元素都必须实现 Comparable 接口。此外,此范围内的所有元素必须是相互可比较的(即,e1.compareTo(e2) 不得对数组中的任何元素 e1 和 e2 抛出 ClassCastException)。
这种排序保证是stable:相等的元素不会因排序而重新排序。
语法
public static <T extends Comparable<? super T>> void parallelSort(T[] a,
int fromIndex,
int toIndex)
这里,T 是数组中元素的类型。
参数
a | 指定要排序的数组。 |
fromIndex | 指定要排序的第一个元素(含)的索引。 |
toIndex | 指定要排序的最后一个元素(不包括)的索引。 |
返回值
void 类型。
异常
- 如果数组包含不可相互比较的元素(例如字符串和整数),则抛出 ClassCastException。
- 如果 fromIndex > toIndex 或(可选)如果发现数组元素的自然顺序违反了 Comparable 约定,则抛出 IllegalArgumentException。
- 抛出 ArrayIndexOutOfBoundsException,如果 fromIndex < 0 或 toIndex > a.length。
示例:
在下面的示例中,java.util.Arrays.parallelSort() 方法用于对指定范围内的指定对象数组进行排序。
import java.util.*;
public class MyClass {
public static void main(String[] args) {
//创建一个未排序的整数数组
Integer Arr[] = {10, 2, -3, 35, 56, 25};
//排序前打印数组
System.out.print("Arr contains:");
for(Integer i: Arr)
System.out.print(" " + i);
//对范围[1,5)的数组进行排序
Arrays.sort(Arr, 1, 5);
//打印排序后的数组
System.out.print("\nArr contains:");
for(Integer i: Arr)
System.out.print(" " + i);
}
}
上述代码的输出将是:
Arr contains: 10 2 -3 35 56 25
Arr contains: 10 -3 2 35 56 25