private Student stu[]= {new Student(1,"张三",2),new Student(2,"李四",4),new Student(3,"王五",1),new Student(4,"赵六",0)};
代码如上,如何对上面的stu[]数组第三列从大到小进行排序
输出stu[0]的时候是 李四那一行。
这是对对象数组进行排序,有两种方法:1、一种是实现Comparable接口,复写compareTo()方法。2、另一种是自定义一个比较器即实现Comparator接口,复写compare()方法。
import java.util.Arrays;
import java.util.Comparator;
class Student
{
public int id;
public String name;
public int age;
public Student(int id,String name,int age){
this.id=id;
this.name=name;
this.age=age;
}
public String toString(){
return "根据第三列排序:"+this.name+".."+this.age;
}
}
class StudentComparator implements Comparator<Student>//定义一个Student比较器
{
public int compare(Student stu1,Student stu2){
if(stu1==stu2){
return 0;
}
if(stu1.age<stu2.age){
return 1;
}else if(stu1.age>stu2.age){
return -1;
}else{
return 0;
}
}
}
public class StudentTest
{
public static void main(String[] args){
Student stu[]= {new Student(1,"张三",2),new Student(2,"李四",4),
new Student(3,"王五",1),new Student(4,"赵六",0)};
StudentComparator sc=new StudentComparator();
Arrays.sort(stu,sc);
for(int i=0;i<stu.length;i++){
System.out.println(stu[i]);
}
}
}