1. TreeMap对键实现了Comparable接口的对象排序
import java.util.TreeMap;
import java.util.Map.Entry;
/**
* TreeMap对键实现了Comparable接口的对象排序
*/
public class TreeMapComparable {
public static void main(String[] args) {
TreeMap<Person, Integer> tm = new TreeMap<Person, Integer>();
tm.put(new Person("zhangsan", 19), 1005);
tm.put(new Person("cuihua", 16), 1000);
tm.put(new Person("fanbingbing", 39), 1009);
tm.put(new Person("zhaoliying", 29), 1001);
for (Entry<Person, Integer> kv : tm.entrySet()) {
System.out.println(kv.getKey() + ":" + kv.getValue());
}
}
}
class Person implements Comparable<Person>{
public String name;
public int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int compareTo(Person o) {
return o.age - age;
}
public String toString() {
return "[name = " + name + " age = " + age + "]";
}
}