TreeMap,與TreeSet類似,可以對集合中的元素進行排序,同時保持元素的唯一性。
應注意,Comparable(實現接口,記得覆蓋comparaTo方法),Comparator的使用。
1 import java.util.Iterator;
2 import java.util.TreeMap;
3
4 import cn.itcast.p2.bean.Student;
5 import cn.itcast.p3.comparator.ComparatorByName;
6
7 public class TreeMapDemo {
8
9 public static void main(String[] args) {
10 TreeMap<Student,String> tm = new TreeMap<Student,String>(new ComparatorByName());
11
12 tm.put(new Student("lisi",38), "北京");
13 tm.put(new Student("zhaoliu",24), "上海");
14 tm.put(new Student("xiaoqiang",31), "沈陽");
15 tm.put(new Student("wangcai",38), "大連");
16 tm.put(new Student("zhaoliu",24), "鐵嶺");
17
18 Iterator<Student> it = tm.keySet().iterator();
19 while (it.hasNext())
20 {
21 Student key = it.next();
22 String value = tm.get(key);
23 System.out.println(key.getName()+":"+key.getAge()+"--"+value);
24 }
25
26
27 }
28
29 }
