对象的比较--Comparable接口和Comparator接口的使用
来源:互联网 发布:淘宝店铺装修毕业设计 编辑:程序博客网 时间:2024/05/22 14:03
实现对象之间的比较通常有两种办法:
1.实现Comparable接口,这种方法比较简单。因为Comparable接口中只定义了一个方法:compareTo()
使需要比较的对象实现Comparable接口并覆盖compareTo()方法:
public class User implements Comparable
@Override public int compareTo(Object o) { User other = (User)o; return this.age - other.age; }
如上方法所示:比较对象age的大小作为判断对象大小的依据。
2.虽然实现Comparable接口的方法比较简单,但是缺乏灵活性。比如,如果在排序的时候,如果集合A中的User对象需要按照age排序,而集合B中的User对象需要按照id排序,就难以实现。
因此可以使用Comparator接口:
分别定义两个类,实现Comparator接口:
public class UserComparatorById implements Comparator<User>{ @Override public int compare(User o1, User o2) { return o1.getId()-o2.getId(); }}
public class UserComparatorByAge implements Comparator<User>{ @Override public int compare(User o1, User o2) { return o1.getAge()-o2.getAge(); }}
在测试方法里:
public class Test { public static void main(String[] args) { User user1 = new User(1,"John",24,new Date()); User user2 = new User(2,"John",20,new Date()); User user3 = new User(3,"John",25,new Date()); List<User> list = new ArrayList<User>(); list.add(user1); list.add(user3); list.add(user2); Collections.sort(list, new UserComparatorById()); System.out.println("---sort by id---"); for(User u : list){ System.out.println(u); } Collections.sort(list, new UserComparatorByAge()); System.out.println("---sort by age---"); for(User u : list){ System.out.println(u); } }}
输出结果:
---sort by id---User [id=1, name=John, age=24, birthday=1430142616520]User [id=2, name=John, age=20, birthday=1430142616520]User [id=3, name=John, age=25, birthday=1430142616520]---sort by age---User [id=2, name=John, age=20, birthday=1430142616520]User [id=1, name=John, age=24, birthday=1430142616520]User [id=3, name=John, age=25, birthday=1430142616520]
这样便可以根据情况灵活地选择比较器进行排序。
0 0
- 对象的比较--Comparable接口和Comparator接口的使用
- 使用Comparable和Comparator接口比较对象
- Comparable接口和Comparator接口的使用
- Comparable接口和Comparator类的使用
- java 接口Comparable和Comparator的使用
- Java中实现对象的比较:Comparable接口和Comparator接口
- Java中实现对象的比较:Comparable接口和Comparator接口
- Java中实现对象的比较:Comparable接口和Comparator接口
- comparator接口与Comparable接口的使用
- 使用TreeSet集合比较Comparable接口和Comparator接口的区别
- 使用TreeSet集合比较Comparable接口和Comparator接口的区别
- 使用TreeSet集合比较Comparable接口和Comparator接口的区别
- 使用TreeSet集合比较Comparable接口和Comparator接口的区别
- Comparable接口和Comparator接口的区别
- java的comparable接口和comparator接口
- Comparable接口和Comparator接口的区别
- Comparator接口和Comparable接口的区别
- Java中Comparator接口和Comparable接口的使用
- java泛型-泛型的内部原理
- MySQL的数据类型
- Tomcat 发布网站
- The specified module could not be found
- 轻松搞定面试中的二叉树题目
- 对象的比较--Comparable接口和Comparator接口的使用
- leetCode刷题——Same Tree
- css学习笔记(三)——布局模型
- vs2013 gstreamer1.4.5 配置
- (思维分析)12th浙江省赛,B.Team Formation
- 黑马程序员-java中scanner的使用
- 如何解决Eclipse启动时画面一闪而过
- 通用缩写表
- 关于熵的一些理解