java: Comparable比较器,数组对象比较器
2024-09-04 06:27:21
Arrays只适合一个数组/对象内的数值进行比较,
Comparable比较器(Compara)适合数组,对象,队列等排序,
Comparable是一个接口类,实现此接口必须复写:compareTo 方法,
compareTo方法会返回三个值:1,0,-1,可以利用这三个值进行排序
//比较器
class Student2 implements Comparable<Student2>{
private int strno;
private String name;
private int age;
private float score; public Student2(int strno, String name, int age, float score) {
this.strno = strno;
this.name = name;
this.age = age;
this.score = score;
} @Override
public String toString() {
// TODO 自动生成的方法存根
return "学号:"+this.strno+",姓名:"+this.name+",年龄:"+this.age+",成绩:"+this.score;
}
@Override
public int compareTo(Student2 stu) {
// TODO 自动生成的方法存根
if(this.score > stu.score)
{
return 1;
}else if(this.score < stu.score){
return -1;
}else{
return 0;
}
} } public class CompareDemo { public static void main(String args[])
{
Student2 stu[] = {new Student2(1,"张三",20,98.13f),
new Student2(2,"李四",33,88.18f),
new Student2(3,"王五",41,80.32f),
new Student2(4,"赵六",28,89.77f),
new Student2(5,"田七",25,90.53f)}; //排序
System.out.println("++++++++++++数组排序前+++++++++++++++");
print(stu);
System.out.println("++++++++++++数组排序后+++++++++++++++");
Arrays.sort(stu);
print(stu);
} public static void print(Student2 stu[])
{
for(int i=0;i<stu.length; i++)
{ System.out.println(stu[i]);
}
} }
最新文章
- IOS开发之—— 在AFN基础上进行的网络请求的封装
- CharSequence cannot be resolved. It is indirectly referenced from required .class files
- 敏捷软件开发vs传统软件开发
- Delphi中函数定义和声明的位置
- bzoj4514: [Sdoi2016]数字配对--费用流
- Java基础之理解Annotation(与@有关,即是注释)
- 25.usb固件深入
- 与电子钱包相关的APDU指令
- 如何在Android应用程序中使用传感器模拟器SensorSimulator
- [引]MSDN Visual Basic 和 C# 中都会用到的编程概念
- 【转】Android开发中adb启动失败adb连接异常的解决办法 offline
- SSH框架整合 日志处理Spring结合 log4j、slf4j
- js中的各种“位置”——“top、clientTop、scrollTop、offsetTop……”,你知道多少
- v-cloak的用法和注意事项
- SpringBoot系列——jar包与war包的部署
- java面试一、1.5JVM
- word公式大小
- SQLServer: 解决“错误15023:当前数据库中已存在用户或角色”
- tp5模型笔记---多对多
- 表格(table)