直接Arrays.sort()方法,默认升序。
Arrays.sort(a);
要实现降序排列需要实现Comparator<Integer>接口,重写里面的compare()方法;
代码如下
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Integer[]a= {1,9,878,3,55,268,999};
Comparator<Integer> c=new cmp();
Arrays.sort(a, c);;
for(int i:a) {
System.out.println(i);
}
}
class cmp implements Comparator<Integer> {
public int compare(Integer a,Integer b) {
return a-b;
}
}
在重写compare() 的时候必须要用一个具体的类实现,而基本数据类型对应的类就是它的包装类,所以此处用的Integer;
compare 默认从小到大,即a-b>0的时候是升序,降序return b-a;
具体例子如下面一段代码:
对student对象分别对id,age升序排列:
public class Student {
private int id;
private int age;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", age=" + age +
'}';
}
public Student(int id, int age){
this.id = id;
this.age = age;
}
//通过id排序
public static class SortById implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o1.id - o2.id;
}
}
//通过age排序
public static class SortByAge implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o1.age - o2.age;
}
}
public static void main(String[] args) {
Student s1 = new Student(11110,13);
Student s2 = new Student(11112,12);
Student[] ss = {s1, s2};
Arrays.sort(ss,new SortById());
for (Student s : ss) {
System.out.print(s);
}
System.out.println();
Arrays.sort(ss,new SortByAge());
for (Student s : ss) {
System.out.print(s);
}
}
}