java.util.Arrays.sort() 方法用于对指定范围的数组进行升序排序。要排序的范围从索引 fromIndex(包括)开始,到索引 toIndex(不包括)结束。如果 fromIndex 和 toIndex 相等,则要排序的范围为空。
语法
public static void sort(long[] 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) {
//创建一个未排序的长数组
long MyArr[] = {10, 2, -3, 35, 56, 15, 47};
//排序前打印数组
System.out.print("MyArr contains:");
for(long i: MyArr)
System.out.print(" " + i);
//对数组进行排序
Arrays.sort(MyArr, 2, 7);
//打印排序后的数组
System.out.print("\nMyArr contains:");
for(long i: MyArr)
System.out.print(" " + i);
}
}
上述代码的输出将是:
MyArr contains: 10 2 -3 35 56 15 47
MyArr contains: 10 2 -3 15 35 47 56