1       比较排序Comparable和Comparator

1.1      接口作用说明

Comparable和Comparator都是用来实现对象的比较、排序,对比时需要实现Comparable或Comparator接口,Comparator位于java.util包下,而Comparable位于java.lang包下。

实现类需要实现Comparable接口,在类的内部实现compareTo方法。如 String、Integer已经实现了Comparable接口,自己就可以完成比较大小操作;而Comparator接口,需要定义一个对比类,实现Comparator接口。然后将需要的比较的两个实现类对象传入比较器的compare函数进行比较。前者自己继承接口,内部实现比较;后者外部实现接口,作为一个比较器,将实现类传入对比类方法中。如果比较的方法在很多类中需要用到,就自己写个比较类实现Comparator接口,这样当要比较的时候,把实现了Comparator接口的比较类传过去,省得重复造轮子。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

1.2      接口的定义

(1)Comparable的定义

package java.lang;

import java.util.*;

public interface Comparable<T> {

    public int compareTo(T o);

}

(2)Comparator的定义如下

package java.util;

public interface Comparator<T> {

    int compare(T o1, T o2);

    boolean equals(Object obj);

}

实现Comparable接口要重写compareTo方法,实现Comparator需要重写 compare 方法。

1.3      比较

1.3.1   实现Comparable接口,实现compareTo方法

class Student implements Comparable{

    public String name;

    public int age;

    public Student(String name, int age){

        this.name = name;

        this.age = age;

    }

 

    @Override

    public int compareTo(Object o) {

        Student student = (Student)o;

        return this.age- student.age          }

 

1.3.2   实现Comparator接口,实现compare方法

定义比较器类

class NameSorter implements Comparator{

    @Override

    public int compare(Object o1, Object o2) {

        Student s1 =(Student) o1;

        Student s2 =(Student) o2;

        return s1.name.compareTo(s2.name);

    }

class Student implements Comparator{

    public String name;

    public int age;

    public Student(String name, int age){

        this.name = name;

        this.age = age;

    }

 

  @Override ///按名称排序

  public int compare(Object o1, Object o2) {

        Student s1 =(Student) o1;

        Student s2 =(Student) o2;

        return s1.name.compareTo(s2.name);

 

1.3.3   比较使用实例

(1)Comparable比较

使用实例:

Student stuA=new Student(“A”,10);

Student stuB=new Student(“B”,11);

If(stuB. compareTo(stuA)>0){}

(2)Comparator比较

NameSorter NameCompare =new NameSorter;

NameCompare.compare(stuA,stuB);

1.4      排序

(1)Comparable 排序

ArrayList<Student> students = new ArrayList<>();

Students.add(stuA);

Students.add(stuB);

Collections.sort(students);//按照年龄排序, students 列表中的对象已经实现了Comparable接口,会根据CompareTo方法进行排序。Collections 是一个包装类。它包含有各种有关集合操作的静态多态方法。此类不能实例化,就像一个工具类,服务于Java的Collection框架。

(2)Comparator排序

students.sort(new NameSorter());//传入比较器,按照名称排序

或者调用Collections的静态方法,传入比较器。

Collections.sort(students, new NameSorter());

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄