java.util.Arrays类也可以对Object数组进行排序,但是要使用这种方法排序必须实现Comparable接口,此接口就是用于指定对象排序规则的。
设计一个学生类,成绩由高到低排序,成绩相等,按年龄由低到高排序。
//=================================================
// File Name : Array_demo
//------------------------------------------------------------------------------
// Author : Common
// 类名:student_
// 属性:
// 方法:
class student_ implements Comparable<student_>{
private String name;
private int age;
private float score;
public student_(String name, int age, float score) {
super();
this.name = name;
this.age = age;
this.score = score;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", score=" + score + "]";
}
public int compareTo(student_ stu){ //覆写compareTo()方法,实现排序规则的应用
if(this.score>stu.score){
return -1;
}else if(this.score<stu.score){
return 1;
}else{
if(this.age>stu.age){
return 1;
}else if(this.age<stu.age){
return -1;
}else{
return 0;
}
}
}
}
//主类
//Function : Comparable_demo
public class Comparable_demo {
public static void main(String[] args) {
// TODO 自动生成的方法存根
student_ stu[] = {new student_("张三",20,90.0f),new student_("李四",22,90.0f),
new student_("王五",20,99.0f),new student_("赵六",20,70.0f),
new student_("孙七",22,100.0f)};
java.util.Arrays.sort(stu);
for(int i=0;i<stu.length;i++){
System.out.println(stu[i]);
}
}
}