由文生義:this
繼承Comparable ,表示該類的實例是能夠相互比較的;spa
繼承Comparator,表示該類是一個比較器,裏面設置了按什麼屬性比較,list須要按這個比較器裏的規則來比較;繼承
使用方法以下:get
1.Comparablestring
public class User implements Comparable {
private string id;it
private int age;class
//必須實現的方法:List
public int compareTo(Object o) { map
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; } });