java比较器comparable接口和comparator接口

来源:互联网 发布:陕西省大数据集团股东 编辑:程序博客网 时间:2024/05/16 17:03

1. comparable接口

此接口强行对实现它的每个类的对象进行整体排序。此排序被称为该类的自然排序 ,类的 compareTo 方法被称为它的自然比较方法 。实现此接口的对象列表(和数组)可以通过 Collections.sort (和 Arrays.sort )进行自动排序。实现此接口的对象可以用作有序映射表中的键或有序集合中的元素,无需指定比较器。 强烈推荐(虽然不是必需的)使自然排序与 equals 一致。所谓与equals一致是指对于类 C 的每一个 e1 和 e2 来说,当且仅当 (e1.compareTo((Object)e2) == 0) 与e1.equals((Object)e2) 具有相同的布尔值时,类 C 的自然排序才叫做与 equals 一致 。

1.2 实现方法

int compareTo(T o)
比较此对象与指定对象的顺序。如果该对象小于、等于或大于指定对象,则分别返回负整数、零或正整数。
强烈推荐 (x.compareTo(y)==0) == (x.equals(y)) 这种做法,但不是 严格要求这样做。一般来说,任何实现 Comparable 接口和违背此条件的类都应该清楚地指出这一事实。推荐如此阐述:“注意:此类具有与 equals 不一致的自然排序。”
参数:
       o - 要比较的对象。
返回:        负整数、零或正整数,根据此对象是小于、等于还是大于指定对象。
抛出:        ClassCastException - 如果指定对象的类型不允许它与此对象进行比较。

代码示例:

class Student implements Comparable<Student>{    private String name;    private int age;    private float score;        public Student(String name, int age, float score) {        this.name = name;        this.age = age;        this.score = score;    }        public String toString()    {        return name+"\t\t"+age+"\t\t"+score;    }    @Override    public int compareTo(Student o) {        // TODO Auto-generated method stub        if(this.score>o.score)//score是private的,为什么能够直接调用,这是因为在Student类内部            return -1;//由高到底排序        else if(this.score<o.score)            return 1;        else{            if(this.age>o.age)                return 1;//由底到高排序            else if(this.age<o.age)                return -1;            else                return 0;        }    }}public class ComparableDemo01 {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        Student stu[]={new Student("zhangsan",20,90.0f),                new Student("lisi",22,90.0f),                new Student("wangwu",20,99.0f),                new Student("sunliu",22,100.0f)};        java.util.Arrays.sort(stu);        for(Student s:stu)        {            System.out.println(s);        }    }}

运行结果:

sunliu 22 100.0
wangwu 20 99.0
zhangsan 20 90.0
lisi 22 90.0

2. comparator接口


Comparator位于包java.util下,而Comparable位于包java.lang下,Comparable接口将比较代码嵌入自身类中,而后者在一个独立的类中实现比较。 如果类的设计师没有考虑到Compare的问题而没有实现Comparable接口,可以通过  Comparator来实现比较算法进行排序,并且为了使用不同的排序标准做准备,比如:升序、降序。

compareTo(T o)只有一个参数,而Comparator接口中必须要实现的compare(T o1,T o2)就有两个参数。

代码示例:

package edu.sjtu.ist.comutil;import java.util.Comparator;class Student {    private String name;    private int age;    private float score;        public Student(String name, int age, float score) {        this.name = name;        this.age = age;        this.score = score;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public float getScore() {        return score;    }    public void setScore(float score) {        this.score = score;    }    public String toString()    {        return name+"\t\t"+age+"\t\t"+score;    }}class StudentComparator implements Comparator<Student>{    @Override    public int compare(Student o1, Student o2) {        // TODO Auto-generated method stub        if(o1.getScore()>o2.getScore())            return -1;        else if(o1.getScore()<o2.getScore())            return 1;        else{            if(o1.getAge()>o2.getAge())                return 1;            else if(o1.getAge()<o2.getAge())                return -1;            else                 return 0;        }    }    }public class ComparableDemo02 {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        Student stu[]={new Student("zhangsan",20,90.0f),                new Student("lisi",22,90.0f),                new Student("wangwu",20,99.0f),                new Student("sunliu",22,100.0f)};        java.util.Arrays.sort(stu,new StudentComparator());        for(Student s:stu)        {            System.out.println(s);        }    }}


 

0 0
原创粉丝点击