首先这个两个接口是干嘛的?
Arrays.sort()
collections.sort()
这两个方法分别是用来给
数组排序和给
集合排序的
但是当我们数组中的值是
Object的时候 计算机不知道该怎么去比较
class Student{
String name="";
int age;
int score;
public Student(String name,int age,int score){
this.name=name;
this.age=age;
this.score=score;
}
}
Comparable 接口 实现
//
Student类实现这个接口将会强制 实现
compareTo()方法
//这个接口相当于
自己本身 去与
传进来的对象去比较
class Student implements Comparable<Student>{
String name="";
int age;
int score;
public Student(String name,int age,int score){
this.name=name;
this.age=age;
this.score=score;
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
//返回值为负数: 本对象 放在 穿件来的对象 前面 我们让她按照年龄排序
//为正数 本对象 放在 传件来的对象 后面
//返回值为零时 本对象等于 传进来的对象
if(this.age<o.age){
return -1;
}else if(this.age>o.age){
return 1;
}else{
return 0;
}
}
}此时就可以比较排序了
public class Main {
public static void main(String[] args){
Student[] message={new Student("王老吉",20,50),
new Student("零丁洋",20,51),new Student("康奶昔",15,60),
new Student("惶恐滩",20,80),new Student("大腊肠",30,90)
};
Arrays.sort(message);
for(int i=0;i<5;i++){
System.out.println("姓名:"+message[i].name+"\t年龄:"+message[i].age+"\t成绩"+message[i].score);
}
}
}
将会按照年龄排序
姓名:康奶昔 年龄:15 成绩60
姓名:王老吉 年龄:20 成绩50
姓名:零丁洋 年龄:20 成绩51
姓名:惶恐滩 年龄:20 成绩80
姓名:大腊肠 年龄:30 成绩90
Comparator 接口 实现
//实现这个接口将会强制 实现
compare()方法
// 这个接口不是让
Student 实现的 而是相当于另外创建了一个专门用来比较的
比较器
class useAgeSort implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
//返回值为负数: o1 放在 o2 前面
//为正数 o1 放在 o2 后面
//返回值为零时 o1等于 o2
if(o1.age<o2.age){
return -1;
}else if(o1.age>o2.age){
return 1;
}else{
return 0;
}
}
}按照年龄排序
此时我们应该调用
sort(list,比较器) sort 的这个重载方法
意思是 让他使用我们自己写的 比较器 去比较
public class Main {
public static void main(String[] args){
Student[] message={new Student("王老吉",20,50),
new Student("零丁洋",20,51),new Student("康奶昔",15,60),
new Student("惶恐滩",20,80),new Student("大腊肠",30,90)
};
useAgeSort bijiaoqi = new useAgeSort();//比较器对象
Arrays.sort(message,bijiaoqi);
for(int i=0;i<5;i++){
System.out.println("姓名:"+message[i].name+"\t年龄:"+message[i].age+"\t成绩"+message[i].score);
}
}
}结果
姓名:康奶昔 年龄:15 成绩60
姓名:王老吉 年龄:20 成绩50
姓名:零丁洋 年龄:20 成绩51
姓名:惶恐滩 年龄:20 成绩80
姓名:大腊肠 年龄:30 成绩90
这个两个接口的区别是什么?
Comparable: 在需要比较的类中 使用该接口 让他知道自己排序的时候该怎么排
Comparator: 定义一个 外置的
比较器 比较的时候 sort()把比较器传进去
为什么要存在两个这样功能差不多的接口?
实际案例:
我的软件要实现两个功能,一个是按年龄排序,一个是按成绩排序
class useAgeSort implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
//返回值为负数: o1 放在 o2 前面
//为正数 o1 放在 o2 后面
//返回值为零时 o1等于 o2
if(o1.age<o2.age){
return -1;
}else if(o1.age>o2.age){
return 1;
}else{
return 0;
}
}
}
class useScoreSort implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
//返回值为负数: o1 放在 o2 前面
//为正数 o1 放在 o2 后面
//返回值为零时 o1等于 o2
if(o1.score<o2.score){
return -1;
}else if(o1.score>o2.score){
return 1;
}else{
return 0;
}
}
}
本文详细介绍了Java中Arrays.sort()和Collections.sort()方法的使用,并对比了Comparable与Comparator接口的区别及应用场景,通过实例展示了如何实现自定义类的排序。
1万+

被折叠的 条评论
为什么被折叠?



