###如何区分Comparable和Comparator
able结尾是形容词,是具有(比较)特性的
tor结尾是名词,是(比较)器
如果一个类实现了Comparable,那么它就具有了排序的特性
或者可以外部实现一个比较器Comparator来进行排序。
如果不能修改某个类的源码,就可以利用Comparator接口来在外面对它进行排序,并且该实现可以复用.
注:Comparator优先级高于Comparable
###Comparable 简介
Comparable 是排序接口。
若一个类实现了Comparable接口,就意味着“该类支持排序”。 即然实现Comparable接口的类支持排序,假设现在存在“实现Comparable接口的类的对象的List列表(或数组)”,则该List列表(或数组)可以通过 Collections.sort(或 Arrays.sort)进行排序。
此外,“实现Comparable接口的类的对象”可以用作“有序映射(如TreeMap)”中的键或“有序集合(TreeSet)”中的元素,而不需要指定比较器。
###Comparator 简介
Comparator 是比较器接口。
我们若需要控制某个类的次序,而该类本身不支持排序(即没有实现Comparable接口);那么,我们可以建立一个“该类的比较器”来进行排序。这个“比较器”只需要实现Comparator接口即可。
也就是说,我们可以通过“实现Comparator类来新建一个比较器”,然后通过该比较器对类进行排序。
###举例
我想对我自己定义的对象User根据UserId进行排序
public class User {
private Integer UserId;
private String UserName;
public User(Integer UserId,String UserName){
this.UserId = UserId;
this.UserName = UserName;
}
//getter and setter
...
}
有下面两种做法
1、外部实现Comparator接口
class MyComparator implements Comparator<User>{
@Override
public int compare(User user1, User user2) {
int thisVal = user1.getUserId();
int anotherVal = user2.getUserId();
return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
}
}
public class TestMain{
public static void main(String[] args) {
Map<User,String> testmap = new TreeMap<User,String>(new MyComparator());
testmap.put(new User(3, "a"), "a");
testmap.put(new User(1, "a"), "a");
testmap.put(new User(5, "a"), "a");
testmap.put(new User(2, "a"), "a");
for(Entry<User, String> entry : testmap.entrySet()) {
System.out.println(entry.getKey().getUserId());
}
}
}
2、User内部实现Comparable接口
public class User implements Comparable<User>{
private Integer UserId;
private String UserName;
public User(Integer UserId,String UserName){
this.UserId = UserId;
this.UserName = UserName;
}
//getter and setter
...
@Override
public int compareTo(User user) {
// TODO Auto-generated method stub
int thisVal = this.UserId;
int anotherVal = user.UserId;
return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
}
}
public class TestMain{
public static void main(String[] args) {
Map<User,String> testmap = new TreeMap<User,String>();
testmap.put(new User(3, "a"), "a");
testmap.put(new User(1, "a"), "a");
testmap.put(new User(5, "a"), "a");
testmap.put(new User(2, "a"), "a");
for(Entry<User, String> entry : testmap.entrySet()) {
System.out.println(entry.getKey().getUserId());
}
}
}