比较

Comparable 是排序接口;若一个类实现了 Comparable 接口,就意味着 “该类支持排序”。
Comparator 是比较器;我们若需要控制某个类的次序,可以建立一个 “该类的比较器” 来进行排序。
前者应该比较固定,和一个具体类相绑定,而后者比较灵活,它可以被用于各个需要比较功能的类使用。可以说前者属于 “静态绑定”,而后者可以 “动态绑定”。 我们不难发现:Comparable 相当于 “内部比较器”,而 Comparator 相当于 “外部比较器”

  1. 自定义的类型,谁大谁小默认情况下,系统是无法识别的,引入比较器的目的是自定义对象的比较规则。
  2. 类比较:Comparable 接口 (规则一般定义死,修改比较麻烦)
  3. 自比较:Comparator 接口 (建议使用,比较灵活)
  4. 数值用-:
  5. s1.getScore()-s2.getScore();
  6. String类型用compare.to():
  7. s1.getStuName().compareTo(s2.getStuName());
  8. 若是字母比较,如:A a D排序之后为A D a,采用a1.toUpperCase().compare.to(a2.toUpperCase())

实例

1 使用集合工具类对对象进行排序(对象实现Comparable接口)

  1. //1.定义学生类
  2. public class Student implements Comparable<Student>{
  3. private int id;
  4. private String stuName;
  5. private int score;
  6. public Student() {
  7. super();
  8. }
  9. public Student(int id, String stuName, int score) {
  10. super();
  11. this.id = id;
  12. this.stuName = stuName;
  13. this.score = score;
  14. }
  15. public int getId() {
  16. return id;
  17. }
  18. public void setId(int id) {
  19. this.id = id;
  20. }
  21. public String getStuName() {
  22. return stuName;
  23. }
  24. public void setStuName(String stuName) {
  25. this.stuName = stuName;
  26. }
  27. public int getScore() {
  28. return score;
  29. }
  30. public void setScore(int score) {
  31. this.score = score;
  32. }
  33. @Override
  34. public String toString() {
  35. return "Student [id=" + id + ", stuName=" + stuName + ", score=" + score + "]";
  36. }
  37. //定义学生对象的比较规则 arr[j+1]-arr[j]>0
  38. //1.如果成绩一样,按照编号进行顺序排列 Comparable
  39. // @Override
  40. // public int compareTo(Student stu) {
  41. // if(stu.getScore()==this.getScore()) {
  42. // return stu.getId()-this.getId();
  43. // }
  44. // return this.getScore()-stu.getScore();
  45. // }
  46. //2.按成绩排序,如果成绩一样,按照名字进行顺序排列
  47. @Override
  48. public int compareTo(Student stu) {
  49. if(stu.getScore()==this.getScore()) {
  50. return this.getStuName().compareTo(stu.getStuName());
  51. }
  52. return this.getScore()-stu.getScore();
  53. }
  54. }
  55. //2.测试类中添加学生信息,然后进行排序
  56. public static void main(String[] args) {
  57. ArrayList<Student> list=new ArrayList<>();
  58. list.add(new Student(3,"jack",89));
  59. list.add(new Student(1,"rouse",79));
  60. list.add(new Student(4,"tina",99));
  61. list.add(new Student(2,"apple",69));
  62. list.add(new Student(6,"oracle",89));
  63. list.add(new Student(5,"marry",59));
  64. System.out.println("排序之前:"+list);
  65. Collections.sort(list);
  66. System.out.println("排序之后:"+list);
  67. Student stuMax=Collections.max(list);
  68. System.out.println("最高分:"+stuMax);
  69. Student stuMin=Collections.min(list);
  70. System.out.println("最低分:"+stuMin);
  71. }

运行结果:

排序之前:[Student [id=3, stuName=jack, score=89], Student [id=1, stuName=rouse, score=79], Student [id=4, stuName=tina, score=99], Student [id=2, stuName=apple, score=69], Student [id=6, stuName=oracle, score=89], Student [id=5, stuName=marry, score=59]]
排序之后:[Student [id=5, stuName=marry, score=59], Student [id=2, stuName=apple, score=69], Student [id=1, stuName=rouse, score=79], Student [id=3, stuName=jack, score=89], Student [id=6, stuName=oracle, score=89], Student [id=4, stuName=tina, score=99]]
最高分:Student [id=4, stuName=tina, score=99]
最低分:Student [id=5, stuName=marry, score=59]

2 采用匿名内部类的方式实现Comparator 接口

更加的灵活,一般会采用匿名内部类的方式自定义比较规则(写法更加的简洁)
public static void main(String[] args) {
        ArrayList<Student> list=new ArrayList<>();
        list.add(new Student(3,"jack",89));
        list.add(new Student(1,"rouse",79));
        list.add(new Student(4,"tina",99));
        list.add(new Student(2,"apple",69));
        list.add(new Student(6,"oracle",89));
        list.add(new Student(5,"marry",59));
        //1.顺序排列
        Collections.sort(list,new Comparator<Student>() {
            @Override
            public int compare(Student stu1, Student stu2) {
                return stu1.getScore()-stu2.getScore();
            }    
        });
        System.out.println("按照成绩排序之后:"+list);
        //2.返回最高分
        Student maxStu=Collections.max(list,new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getScore()-o2.getScore();
            }
        });
        System.out.println(maxStu);
    }

运行结果:

按照成绩排序之后:[Student [id=5, stuName=marry, score=59], Student [id=2, stuName=apple, score=69], Student [id=1, stuName=rouse, score=79], Student [id=3, stuName=jack, score=89], Student [id=6, stuName=oracle, score=89], Student [id=4, stuName=tina, score=99]]
Student [id=4, stuName=tina, score=99]

比较器的练习题

创建一个商品类Goods(int id, String goodsName,int num,double price) 99.99 99.89,99.79创建一个测试类 定义集合,存入6件商品信息<1>.按照价格进行顺序排列,如果价格一样按照商品的数量排序。<2>.求出最高价格的商品,以及价格最低的商品

public class Goods {
    private int id;
    private String goodsName;
    private int num;
    private double price;
    public Goods() {
    }
    public Goods(int id, String goodsName, int num, double price) {
        this.id = id;
        this.goodsName = goodsName;
        this.num = num;
        this.price = price;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getGoodsName() {
        return goodsName;
    }
    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Goods{" +
                "id=" + id +
                ", goodsName='" + goodsName + '\'' +
                ", num=" + num +
                ", price=" + price +
                '}';
    }
}

注意:比较器只能返回int类型,当比较的结果是double类型时,需进行转换判断(>0则互换位置)