前几天有网友让解释一下CompareTo函数,今天在这里给大家讲一下。
CompareTo函数是Comparable接口的一个方法,Comparable接口源码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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的接口,这样它就拥有了对比的能力。具体怎么做呢?看下面的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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]
大家可以自己动手试试,然后修改以下比较规则,按照名字的字典顺序来比较。
本文属原创,转载请注明出处,违者必究
关注微信公众平台:程序员互动联盟(coder_online),你可以第一时间获取原创技术文章,和(java/C/C++/Android/Windows/Linux)技术大牛做朋友,在线交流编程经验,获取编程基础知识,解决编程问题。程序员互动联盟,开发人员自己的家。
本文原始地址:http://www.coderonline.net/java-based-use-comparable-interface.html
本站所有文章,除特别注明外,均为本站原创,转载请注明出处来自http://www.coderonline.net/
否则保留追究法律责任的权利!
暂无评论