前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【编程基础】java Comparable接口如何使用

【编程基础】java Comparable接口如何使用

作者头像
程序员互动联盟
发布2018-03-14 16:10:03
7740
发布2018-03-14 16:10:03
举报
文章被收录于专栏:程序员互动联盟

前几天有网友让解释一下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]

大家可以自己动手试试,然后修改以下比较规则,按照名字的字典顺序来比较。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2015-10-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员互动联盟 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档