Java.util.Arrays 类

java.util.Arrays.parallelSort()方法用于对指定范围的对象数组按照指定顺序进行排序到指定比较器引起的顺序。要排序的范围从索引 fromIndex(包含)扩展到索引 toIndex(不包含)。 (如果 fromIndex==toIndex,则要排序的范围为空。)该范围内的所有元素必须可以通过指定的比较器相互比较(即,c.compare(e1, e2) 不得对任何元素 e1 抛出 ClassCastException和 e2 在范围内)。

这种排序保证是稳定的:相等的元素不会因排序而重新排序。

语法

public static <T> void parallelSort(T[] a,
                                    int fromIndex,
                                    int toIndex,
                                    Comparator<? super T> cmp)

这里,T是数组中元素的类型。

参数

a 指定待排序的数组。
fromIndex 指定待排序的第一个元素(含)的索引。
toIndex 指定要排序的最后一个元素(不包括)的索引。
cmp 指定比较器以确定数组的顺序。 null 值表示应使用元素的自然排序。

返回值

void 类型。

Exception

  • 如果数组包含使用指定比较器无法相互比较的元素,则抛出 ClassCastException
  • 抛出 IllegalArgumentException ,如果 fromIndex > toIndex 或(可选)如果发现比较器违反了 Comparator 契约。
  • 抛出 ArrayIndexOutOfBoundsException,如果 fromIndex < 0 或 toIndex > a。

示例:

在下面的示例中,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);

    //创建一个用于逆序排序的比较器
    Comparator<Integer> comp = Comparator.reverseOrder();

    //对范围[1,5)的数组进行排序
    Arrays.sort(Arr, 1, 5, comp);

    //打印排序后的数组
    System.out.print("\nArr contains:"); 
    for(Integer i: Arr)
      System.out.print(" " + i);   
  }
}

上述代码的输出将是:

Arr contains: 10 2 -3 35 56 25
Arr contains: 10 56 35 2 -3 25