比较器

来源:互联网 发布:2017流行的网络歌曲 编辑:程序博客网 时间:2024/05/06 01:20

比较器,加到实体类上

public class Student implements Comparable {    int num;    String name;    public Student(int num, String name) {        this.num = num;        this.name = name;    }    @Override    public String toString() {        return "Student [num=" + num + ", name=" + name + "]";    }    public int compareTo(Object o) {//排序,从num的最大到最小        Student tmp = (Student)o;        if(tmp.num > num) {            return 1;        } else {            return -1;        }     }}

测试代码:

List<Student> sList = new ArrayList<Student>();        sList.add(new Student(1, "one"));        sList.add(new Student(2, "two"));        sList.add(new Student(3, "three"));        sList.add(new Student(0, "zero"));        sList.add(new Student(0, "zero2"));        Collections.sort(sList);        System.out.println(sList);

单独写比较器

public class Teacher {    int num;    double salary;    public Teacher(int num, double salary) {        this.num = num;        this.salary = salary;    }    @Override    public String toString() {        return "Teacher [num=" + num + ", salary=" + salary + "]";    }}
public class TeacherComparator  implements Comparator<Teacher>{    public int compare(Teacher o1, Teacher o2) {        int result;        if(o2.num > o1.num) {//排序,从num的最大到最小            return 1;        } else {            return -1;        }    }}

测试代码:

List<Teacher> tList = new ArrayList<Teacher>();        tList.add(new Teacher(1, 12));        tList.add(new Teacher(2, 3));        tList.add(new Teacher(3, 4));        tList.add(new Teacher(0, 6));        tList.add(new Teacher(0, 1));        Collections.sort(tList, new TeacherComparator());        System.out.println(tList);

总体来看:方式二会更加面向对象一些。具体还要看业务需求去决定使用哪种实现方式。

原创粉丝点击