Java集合中Comparable与Comparator
2016-03-25 16:45
393 查看
简单说,Comparable是默认比较规则的接口。
实现了这个接口可以比较大小,可以自然排序
实现需要重写方法:CompareTo()。
返回值为正数(大于),0(相等),负数(小于)。
看下面代码:
在main方法中
关于Comparator
用于临时的一些比较规则,需要自定义。
实现该接口需要实现Compare()方法
3.看代码
Student s1 = new Student(“Tom”, 25);
Student s2 = new Student(“Jim”, 18);
StudentComparator comparator = new StudentComparator();
System.out.println(comparator.compare(s1 , s2));
“`
实现了这个接口可以比较大小,可以自然排序
实现需要重写方法:CompareTo()。
返回值为正数(大于),0(相等),负数(小于)。
看下面代码:
import java.util.*; public class Student implements Comparable<Student> { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public int compareTo(Student o) { if ( getAge() > o.getAge()) { return 1; } else if ( getAge() < o.getAge()) { return -1; } else { return 0; } } //重写toString() 用于输出 public String toString() { return name +":"+age ; }
在main方法中
Student s1 = new Student("Tom", 25); Student s2 = new Student("Jim", 18); List<Student> studentList = new ArrayList<Student>(); studentList.add(s1); studentList.add(s2); Collections.sort(studentList); System.out.printf(studentList);
关于Comparator
用于临时的一些比较规则,需要自定义。
实现该接口需要实现Compare()方法
3.看代码
public class StudentComparator implements Comparator<Student>{ @Override public int compare(Student o1, Student o2) { if (o1.getAge() > o2.getAge()) { return 1; }else if (o1.getAge() == o2.getAge()) { return 0; }else{ return -1; } } 在main方法中
Student s1 = new Student(“Tom”, 25);
Student s2 = new Student(“Jim”, 18);
StudentComparator comparator = new StudentComparator();
System.out.println(comparator.compare(s1 , s2));
“`
相关文章推荐
- 18、java中json怎么运用?
- java基础--HashSet详解
- java常见的排序算法
- Java new一个对象执行几个过程
- java基础--去除List中重复的元素
- 注解实现struts2零配置
- # 20145229吴姗珊 《Java程序设计》2天小总结
- 冒泡排序(JAVA实现)
- java 接口的作用和好处
- 安卓项目R,java文件不能自动更新,clean之后,R.java消失 (转自 Cynosure鱼)
- Java I/O流体系
- Java内存与垃圾回收调优
- java 转码
- Java实现过滤中文乱码
- 浅析spring中注解的运行
- 最长公共子子串 java
- [转]SpringMVC日期类型转换问题三大处理方法归纳
- JAVA基础--继承和权限控制
- JAVA IO流
- 工厂模式的简单实现和快速理解--------(java复习)