由文生义:
继承Comparable ,表示该类的实例是可以相互比较的;
继承Comparator,表示该类是一个比较器,里面设置了按什么属性比较,list需要按这个比较器里的规则来比较;
使用方法如下:
1.Comparable
public class User implements Comparable {
private string id;
private int age;
//必须实现的方法:
public int compareTo(Object o) {
return this.age - ((ComparableUser) o).getAge();
}
}
//调用:
User[] users = new User[] {
new ComparableUser("u1001", 25),
new ComparableUser("u1002", 20),
new ComparableUser("u1003", 21)
};
Arrays.sort(users);
2.Comparator
public class User {
private string id;
private int age;
}
public class ComparableUser implements Comparable {
//必须实现的方法:
public int compareTo(Object o) {
return this.age - ((ComparableUser) o).getAge();
}
}
//调用
User[] users = new User[] {
new User("u1001", 25),
new User("u1002", 20),
new User("u1003", 21) };
Arrays.sort(users, new UserComparator());
//也可以零时定义
// key的格式[菜单类型显示顺序:菜单类型名称]
Map<String, List<UserMenu>> map = new TreeMap<String, List<UserMenu>>(new Comparator() {
public int compare(Object o1, Object o2) {
String str1 = (String)o1;
String str2 = (String)o2;
int showOrder1 = Integer.valueOf(str1.split(":")[0]);
int showOrder2 = Integer.valueOf(str2.split(":")[0]);
return showOrder2 - showOrder1;
}
});