一、场景介绍
java中给了我们两个接口Comparable和Comparator,对自己定义的数据结构需要进行指定排序。
comparable接口定义一个方法:
public interface Comparable<T> {
public int compareTo(T o);
}
comparator接口定义方法(有些类实现了comparator,但是没有实现equals方式是因为Object类已经实现了equals方法):
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}
comparable接口和Comparator接口 主要区别
- 1、实现了comparable的对象直接就可以成为一个可以比较的对象,不过得在类中进行方法定义。
- 2、comparator在对象外比较,不修改实体类。
二、两个接口用法介绍
public class Student implements Comparable<Student> {
private String name;
private int 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;
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
super();
}
@Override
public int compareTo(Student o) {
if(this.age == o.getAge() &&this.name == o.getName()){
return 0;
}else if(this.age > o.getAge()){
return 1;
}else{
return -1;
}
}
@Override
public String toString() {
return "Student[name="+this.name+",age="+this.age+"]";
}
}
main方法测试
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
list.add(new Student("Hello1",32));
list.add(new Student("Hello2",100));
list.add(new Student("Hello3",19));
list.add(new Student("Hello4",34));
System.out.println("===================未排序结果========================");
for (Student student : list) {
System.out.println(student.toString());
}
System.out.println("===============Comparable接口排序结果=================");
Collections.sort(list);
for (Student student : list) {
System.out.println(student.toString());
}
System.out.println("===============Comparator接口排序结果=================");
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if(o1.age == o1.getAge() &&o1.name == o2.getName()){
return 0;
}else if(o1.age < o2.age){
return 1;
}else{
return -1;
}
}
});
for (Student student : list) {
System.out.println(student.toString());
}
System.out.println("===============lambda表达式排序结果===================");
Collections.sort(list,(o1,o2)->(o1.getAge()-o2.getAge()));
list.forEach(student->{
System.out.println(student.toString());
});
}
执行结果
===================未排序结果========================
Student[name=Hello1,age=32]
Student[name=Hello2,age=100]
Student[name=Hello3,age=19]
Student[name=Hello4,age=34]
===============Comparable接口排序结果=================
Student[name=Hello3,age=19]
Student[name=Hello1,age=32]
Student[name=Hello4,age=34]
Student[name=Hello2,age=100]
===============Comparator接口排序结果=================
Student[name=Hello2,age=100]
Student[name=Hello4,age=34]
Student[name=Hello1,age=32]
Student[name=Hello3,age=19]
===============lambda表达式排序结果===================
Student[name=Hello3,age=19]
Student[name=Hello1,age=32]
Student[name=Hello4,age=34]
Student[name=Hello2,age=100]