/*比较器的使用*/
class Student implements Comparable<Student>{ //指定泛型类型为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 +"\t\t"+age+"\t\t"+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 ComparableDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu[] = {new Student("张三",20,20.0f),
new Student("李四",30,23.5f),
new Student("王五",30,32.4f),
new Student("赵六",34,34.3f)
};
java.util.Arrays.sort(stu);
for(int i=0; i<stu.length; i++){
System.out.println(stu[i]);
}
}
}
/*
运行结果:
赵六 34 34.3
王五 30 32.4
李四 30 23.5
张三 20 20.0
*/
class Student implements Comparable<Student>{ //指定泛型类型为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 +"\t\t"+age+"\t\t"+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 ComparableDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu[] = {new Student("张三",20,20.0f),
new Student("李四",30,23.5f),
new Student("王五",30,32.4f),
new Student("赵六",34,34.3f)
};
java.util.Arrays.sort(stu);
for(int i=0; i<stu.length; i++){
System.out.println(stu[i]);
}
}
}
/*
运行结果:
赵六 34 34.3
王五 30 32.4
李四 30 23.5
张三 20 20.0
*/