Java.util.Arrays 类

java.util.Arrays.sort() 方法用于对指定范围的数组进行升序排序。要排序的范围从索引 fromIndex(包括)开始,到索引 toIndex(不包括)结束。如果 fromIndex 和 toIndex 相等,则要排序的范围为空。

语法

public static void sort(double[] a,, int fromIndex, int toIndex)

参数

a 指定要排序的数组。
fromIndex 指定索引要排序的第一个元素(包括)。
toIndex 指定最后一个元素(不包括)的索引

返回值

void类型。

异常

  • 如果 fromIndex > toIndex,则抛出 IllegalArgumentException
  • 如果 fromIndex < 0 或 toIndex > a.length,则抛出 ArrayIndexOutOfBoundsException

示例:

下面的示例中,使用 java.util.Arrays.sort() 方法对指定范围进行排序双精度数组。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建一个未排序的双精度数组
    double MyArr[] = {10.1, 2.34, -3.6, 35.01, 56.23, 15.2, 47.9};

    //排序前打印数组
    System.out.print("MyArr contains:"); 
    for(double i: MyArr)
      System.out.print(" " + i);

    //对数组进行排序
    Arrays.sort(MyArr, 2, 7);

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

上述代码的输出将是:

MyArr contains: 10.1 2.34 -3.6 35.01 56.23 15.2 47.9
MyArr contains: 10.1 2.34 -3.6 15.2 35.01 47.9 56.23