可比 -java.lang.Comparable: int compareTo(Object o1)
可比较的对象能够将自身与另一个对象进行比较。该类本身必须实现java.lang.Comparable接口,以便能够比较其实例。
- 能够将当前对象与提供的对象进行比较。
- 通过使用它,我们可以
only one sort sequence
基于实例属性来实现。例如:Person.id
- 一些预定义的类(如String,包装类,日期,日历)已实现Comparable接口。
比较器 -java.util.Comparator: int compare(Object o1, Object o2)
比较器对象能够比较两个不同的对象。该类不是在比较其实例,而是在比较其他一些类的实例。此比较器类必须实现java.util.Comparator接口。
- 能够比较任何两个相同类型的对象。
- 通过使用它,我们可以
many sort sequence
根据实例属性实现和命名每个。例如:Person.id, Person.name, Person.age
- 我们可以为我们的预定义类实现Comparator接口,以进行自定义排序。
例:
public class Employee implements Comparable<Employee> {
private int id;
private String name;
private int age;
private long salary;
// Many sort sequences can be created with different names.
public static Comparator<Employee> NameComparator = new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return e1.getName().compareTo(e2.getName());
}
};
public static Comparator<Employee> idComparator = new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return Integer.valueOf(e1.getId()).compareTo(Integer.valueOf(e2.getId()));
}
};
public Employee() { }
public Employee(int id, String name, int age, long salary){
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
// setters and getters.
// Only one sort sequence can be created with in the class.
@Override
public int compareTo(Employee e) {
//return Integer.valueOf(this.id).compareTo(Integer.valueOf(e.id));
//return Character.toString(this.name.charAt(0)).compareToIgnoreCase(Character.toString(e.name.charAt(0)));
if (this.id > e.id) {
return 1;
}else if(this.id < e.id){
return -1;
}else {
return Character.toString(this.name.charAt(0)).compareToIgnoreCase(Character.toString(e.name.charAt(0)));
}
}
public static void main(String[] args) {
Employee e1 = new Employee(5, "Yash", 22, 1000);
Employee e2 = new Employee(8, "Tharun", 24, 25000);
List<Employee> list = new ArrayList<Employee>();
list.add(e1);
list.add(e2);
Collections.sort(list); // call @compareTo(o1)
Collections.sort(list, Employee.nameComparator); // call @compare (o1,o2)
Collections.sort(list, Employee.idComparator); // call @compare (o1,o2)
}
}
- 对于自定义排序,对于其他情况,我们使用比较器@compare(o1,o2),对于类似方案,我们使用比较器@compareTo(o1),如果我们要对多个字段进行排序,则无需更改代码,然后使用比较器。
对于Java 8 Lambda:比较器,请参阅我的文章。