目录
二、Comparator接口,重写compare(Object o1,Object o2)
三、Comparable接口,重写compareTo(Object o);
一、java中的compareTo():
String s1="abc";
String s2="ace";
int result=s1.compareTo(s2);
System.out.println(result);
用于比较前后2个字符串的asc码的差值,如果result=0,表示s1=s2; <0表示s1<s2;>0表示s1>s2;
注意:数字类型比较不能用compareTo,直接用 >,<,==,!=比较即可;
二、Comparator<Object>接口,重写compare(Object o1,Object o2)
写法一:
List<Student> stuLs=new ArrayList<Student>();
Student stu1=new Student("xiaoming","beijing");
Student stu2=new Student("xiaozhang","tianjin");
Student stu3=new Student("xiaoliu","hangzhou");
stuLs.add(stu1);
stuLs.add(stu2);
stuLs.add(stu3);
Student[] students=new Student[]{stu1,stu2,stu3};
Arrays.sort(students,new Comparator<Student>() { //数组用Arrays.sort
public int compare(Student o1, Student o2) {
return o1.getAddress().compareTo(o2.getAddress());
}
});
System.out.println(Arrays.toString(students));
// [xiaoming:beijing, xiaoliu:hangzhou, xiaozhang:tianjin]
Collections.sort(stuLs, new Comparator<Student>() { //集合用Collections.sort
public int compare(Student o1, Student o2) {
return o1.getAddress().compareTo(o2.getAddress());
}
});
System.out.println(stuLs.toString());
//[xiaoming:beijing, xiaoliu:hangzhou, xiaozhang:tianjin]
写法二:
Collections.sort(stuLs,new nameComparator()); //自定义类比较器
System.out.println(stuLs.toString());
//[xiaoliu:hangzhou, xiaoming:beijing, xiaozhang:tianjin]
static class nameComparator implements Comparator<Object>{
@Override
public int compare(Object o1, Object o2) {
Student stu1= (Student) o1;
Student stu2= (Student) o2;
return stu1.getName().compareTo(stu2.getName());
}
}
三、Comparable接口,重写compare
先根据学生的成绩降序排序,如果成绩相同再根据年龄升序排序,如果年龄相同再根据名字升序排序:
public class StudentComparable implements Comparable{
private String name;
private int age;
private int score;
public StudentComparable(String name, int age,int score){
this.name=name;
this.age=age;
this.score=score;
}
@Override
public int compareTo(Object o) {
StudentComparable sc= (StudentComparable) o;
//return sc.score-this.score; //按分数降序排序
//return this.age-sc.age; //按年龄升序排序
//return this.name.compareTo(sc.name); //按名字升序排序
//先按 分数 再按年龄 最后按名字排序
int result=sc.score-this.score;
if(result==0){
result=this.age-sc.age;
}
if(result==0){
result=this.name.compareTo(sc.name);
}
return result;
}
..........
}
StudentComparable sc1=new StudentComparable("xiaozhang",21,89);
StudentComparable sc2=new StudentComparable("xiaoliang",20,99);
StudentComparable sc3=new StudentComparable("xiaofeng",23,99);
StudentComparable sc4=new StudentComparable("xiaocao",20,99);
List scLs=new ArrayList();
scLs.add(sc1);
scLs.add(sc2);
scLs.add(sc3);
scLs.add(sc4);
Collections.sort(scLs);
System.out.println("scLs---"+scLs.toString());
//scLs---[99:20:xiaocao, 99:20:xiaoliang, 99:23:xiaofeng, 89:21:xiaozhang]
内容描述有不当之处,欢迎大家指正,讨论,一起进步。
练习参考文章链接:https://www.cnblogs.com/lukelook/p/11101366.html