java中Comparable接口(比较器)的使用

本文介绍了一个使用Java实现的学生类比较器示例。通过实现Comparable接口,该示例可以根据学生的分数和年龄对学生对象进行排序。示例展示了如何定义一个包含姓名、年龄和分数属性的学生类,并提供了一个主方法来演示排序过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*比较器的使用*/
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


*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值