前几天有网友让解释一下CompareTo函数,今天在这里给大家讲一下。
CompareTo函数是Comparable接口的一个方法,Comparable接口源码如下:
public interface Comparable<T> { /** * Compares this object to the specified object to determine their relative * order. * * @param another * the object to compare to this instance. * @return a negative integer if this instance is less than {@code another}; * a positive integer if this instance is greater than * {@code another}; 0 if this instance has the same order as * {@code another}. * @throws ClassCastException * if {@code another} cannot be converted into something * comparable to {@code this} instance. */ int compareTo(T another); }
一个实现了Comparable接口的对象的实例可以被用于和相同对象的不同实例做对比,它本身必须实现java.lang.Comparable的接口,这样它就拥有了对比的能力。具体怎么做呢?看下面的代码。
public class Student implements Comparable<Student> { int age; String name; Student(int age, String name) { this.age = age; this.name = name; } @Override public String toString() { return " age = " + age + " name = " + name; } @Override public int compareTo(Student o) { return this.age - o.age; } public static void main(String[] arg) { ArrayList<Student> students = new ArrayList<Student>(); students.add(new Student(23, "dd")); students.add(new Student(22, "cc")); students.add(new Student(22, "bb")); students.add(new Student(25, "aa")); Collections.sort(students); System.out.print(students); } }
上面的代码是让Student类实现Comparable接口,实现compareTo方法,然后再compareTo方法中实现比较的逻辑,这样Student类的实例就可以相互之间进行比较了。
上面的代码运行结果是:
[ age = 22 name = cc, age = 22 name = bb, age = 23 name = dd, age = 25 name = aa]
大家可以自己动手试试,然后修改以下比较规则,按照名字的字典顺序来比较。