/设计一个学生类,包含姓名、年龄、成绩,并产生一个对象数组,要求按成绩由高到底排序,如果成绩相等,则按年龄由低到高排序
import java.util.Arrays;
class Student implements Comparable<Student>{
private String name;
private int age;
private float score;
public Student(String name,int age,float score){
this.name = name;
this.age = age;
this.score = score;
}
public String toString(){
return name + " " + age + " " + score;
}
public int compareTo(Student stu){
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;
}
}
}
}
public class Root{
public static void main(String[] args) {
Student[] stu = {new Student("stu1",20,90.0f),
new Student("stu2",22,90.0f),
new Student("stu3",20,70.0f),
new Student("stu4",34,98)};
Arrays.sort(stu);
for (Student x:stu){
System.out.println(x);
}
}
}
实现Comparable接口的类,不能排序