当前位置:网站首页>类的比较大小(Comparable -> compareTo(类自己实现接口),Comparator -> compare(新建一个类作为比较器))
类的比较大小(Comparable -> compareTo(类自己实现接口),Comparator -> compare(新建一个类作为比较器))
2022-08-02 15:05:00 【学习追求高效率】
7. 比较大小的接口
1. Comparable -> compareTo
这个是在类里面定义比较函数,要比较的时候,调用的是比较函数,但是这个就会限制比较的条件,所以比较器更方便一点
1.1 sort排序
1.1.1 Compara接口实现后,可以用sort之间排序
1.1.2 排序前后可用用 toString 输出数组
class Student implements Comparable<Student>{
public String name;
public int age;
public double score;
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
@Override
public int compareTo(Student o) {
return this.age-o.age;
}
}
public class Test {
public static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student("bit",10,78.9);
students[1] = new Student("abc",4,98.9);
students[2] = new Student("gb",14,38.9);
System.out.println("排序前"+Arrays.toString(students));
sort(students);
System.out.println("排序后"+Arrays.toString(students));
}
}
1.1.3 sort排序规则
前 - 后 是从小到大
后 - 前 是从大到小
2. 比较器 Comparator -> compare
//比较器
class AgeComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.age-o2.age;
}
}
class ScoreComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return (int)(o1.score-o2.score);
}
}
class NameComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.name.compareTo(o2.name);
}
}
public static void main8(String[] args) {
Student[] students = new Student[3];
students[0] = new Student("bit",10,78.9);
students[1] = new Student("abc",4,98.9);
students[2] = new Student("gb",14,38.9);
System.out.println("排序前"+Arrays.toString(students));
AgeComparator ageComparator = new AgeComparator();
ScoreComparator scoreComparator = new ScoreComparator();
NameComparator nameComparator = new NameComparator();
Arrays.sort(students,nameComparator);
System.out.println("排序后"+Arrays.toString(students));
}
补充:String自带compareTo 用于字符串比较
class NameComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.name.compareTo(o2.name);
}
}
边栏推荐
猜你喜欢
随机推荐
"No title"
PAT Class A 1130 Infix Expressions
阿里巴巴《MySQL成长手册》精简版
China's garment industry has formed a complete industrial system
PAT tree DP (memory search) class a, 1079, 1090, 1106
面试了个阿里P7大佬,他让我见识到什么才是“精通高并发与调优”
aPaaS低代码平台(二) | 快速构建业务模型
树状DP(记忆化搜索)PAT甲级 1079 1090 1106
Vest bag access process record
Reed-Solomon Codes——RS纠错码
暴力破解美团最新JVM面试题:无限执行
23.支持向量机的使用
QT | VS2017 + Qt5.14.2 环境搭建
面试必问的HashCode技术内幕
【Untitled】
CS5210的参数详情资料分享
Basic management of system storage -- mounts, partitions, user quotas
剑指Offer 49.丑数 动态规划
2022 VMware下载安装教程
How to check the WeChat applet server domain name and modify it