该方法是Arrays类的静态方法,默认对数组进行从小到大进行排序。
1、Arrays.sort(int[] a)
这种形式是对一个数组的所有元素进行排序,并且是按从小到大的顺序。
import java.util.*;
public class Test
{
public static void main(String args[]) {
int[] a = {9, 5, 7, 6, 3, 4, 1, 0, 2, 8};
Arrays.sort(a);
for(int i = 0; i < a.length; i ++) {
System.out.print(a[i] + " ");
}
}
}
运行结果:
2、Arrays.sort(int[] a, int fromIndex, int toIndex)
对指定区间的元素进行排序。
3、public static void sort(T[] a,int fromIndex,int toIndex, Comparator c)
import java.util.*;
public class Test
{
public static void main(String args[]) {
//注意,要想改变默认的排列顺序,不能使用基本类型(int,double, char)
//而要使用它们对应的类
Integer[] a = {9, 5, 7, 6, 3, 4, 1, 0, 2, 8};
//定义一个自定义类MyComparator的对象
Comparator cmp = new MyComparator();
Arrays.sort(a, cmp);
for(int i = 0; i < a.length; i ++) {
System.out.print(a[i] + " ");
}
}
}
class MyComparator implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
//如果o1小于o2,返回正值,如果o1大于o2,返回负值,
//这样颠倒一下,就可以实现反向排序了
if(o1 < o2) {
return 1;
}else if(o1 > o2) {
return -1;
}else {
return 0;
}
}
}
运行结果:
默认情况下,Comparator比较器对给定的两个操作对象o1, o2,根据比较结果返回正数(o1 > o2)、负数(o1<o2)、零(o1=o2),这样实现对数组进行从小到大的排序。
重写完是根据比较结果返回 1(o1 < o2)、-1(o1 > o2)与默认相反,从而实现从大到小的排序。
4、二维数组排序
对二维数组排序是按照第二个数的数值进行升序排列。