java_comparable接口
来源:互联网 发布:黑客入侵网站盗取数据 编辑:程序博客网 时间:2024/06/11 07:56
在数组中,我们可以直接使用Arrays类对数据进行排序操作 。而且Arrays类的srot方法被重载多次,可以对任意类型的数组进行排序,排列时会根据数值的大小进行排序。同样,它也可以对Object数组进行排序,但是有一个要求,即对象所在的类必须实现Comparable接口。
Comparable接口的定义如下:
public interface Comparable<T>{ public int compareTo(T o);}
int的值有一下三种:
- 1 表示大于
- -1 表示小于
- 0 表示相等
下面来看一个实例:要求设计一个学生类,此类包括姓名,年龄,成绩三个字段,并产生一个对象数组,要求按照成绩从高到低排序,如果成绩相同,则按年龄从低到高排序。
student类:
public class Student implements Comparable<Student>{ private String name; private int age; private int score; public Student(String name, int age, int score) { this.name = name; this.age = age; this.score = score; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public String toString() { return name+"\t\t"+age +"\t\t"+ score; } @Override public int compareTo(Student o) { if(this.score > o.score){ return -1; }else if(this.score<o.score){ return 1; }else { if(this.age>o.age){ return 1; }else if(this.age<o.age){ return -1; }else { return 0; } } }}
测试类:
public class StudentTest { public static void main(String[] args) { Student stu[] = {new Student("张三",24,99), new Student("李四",22,100), new Student("王五",19,30), new Student("赵七",20,99), new Student("孙八",43,23)}; Arrays.sort(stu); for (Student s :stu){ System.out.println(s); } }}
运行结果:
李四 22 100
赵七 20 99
张三 24 99
王五 19 30
孙八 43 23
阅读全文
0 0
- java_comparable接口
- 接口
- 接口
- 接口
- 接口
- 接口
- 接口
- 接口
- 接口
- 接口
- 接口
- 接口
- 接口
- 接口
- 接口
- 接口
- 接口
- 接口
- java学习 EL表达式输出实体对象
- shape使用总结
- SQLserver数据库每月有多少天基表
- 欢迎使用CSDN-markdown编辑器
- IplImage* cvmat* mat 释放
- java_comparable接口
- app包中的fragment和v4包中的fragment的使用的区别
- 移植开源库到嵌入式开发板的一般步骤
- 用yum源配合源码包安装openresty、mariadb、php7服务
- 解决浏览器Adobe Flash Player不是最新版本问题
- 关于CentOS 7 链路聚合的一些见解
- Linux下.run文件的安装和卸载
- 无聊
- 【C++】学习笔记四十五——存储持续性、作用域、链接性