Java.util.Arrays 类

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

语法

public static void sort(float[] 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) {
    //创建一个未排序的浮点数组
    float MyArr[] = {10f, 2f, -3f, 35f, 56f, 15f, 47f};

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

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

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

上述代码的输出将是:

MyArr contains: 10.0 2.0 -3.0 35.0 56.0 15.0 47.0
MyArr contains: 10.0 2.0 -3.0 15.0 35.0 47.0 56.0