Java中的Comparable接口

类对象之间比较“大小”往往是很有用的操作,比如让对象数组排序时,就需要依赖比较操作。对于不同的类有不同的语义。如Student类,比较2个学生对象可以比较他们的score分数来评判。

Java不支持预算符重载,我们通过实现Comparable接口达到相同的目的。当类实现了Comparable接口,则认为这个类的对象之间是可比较的。

Comparable是java SDK中的一个内置的泛型接口。

源代码:(很简单,只有规定了一个接口方法)

public interface Comparable<T> {
  public int compareTo(T o);

  //按照规定:如果 this 比 o 小,则返回一个负数,如果 this 比 o 大,则返回正数,否则返回0


}

例子

public class Test {

   
    public static void main(String[] args) {
       
       
        Student[] students = { new Student("bob", 90.0)  , new Student("jack", 89.0),new Student("mary", 99.0)};
       
       
        Arrays.sort(students);
       
        for(Student s:students)
            System.out.println(s);

    }
}


class Student implements Comparable<Student>
{

   
    Student(String name,double score)
    {
        this.name = name;
        this.score = score;
    }
   
    private double score;
    private String name;
   
   
   
    @Override
    public int compareTo(Student o) {
       
        return Double.compare(this.score, o.score);     //借用Double包装类本身的compare方法
    }
   
    @Override
    public String toString() {
       
        return String.format("name:%s  score:%f", name,score);
    }
}

猜你喜欢

转载自www.linuxidc.com/Linux/2016-12/138181.htm