TreeMap的练习(该例需要上例的学生类)

 1 import java.util.*;
2 class TreeMapTest
3 {
4 public static void main(String[] args)
5 {
6 TreeMap<Student,String> tm=new TreeMap<Student,String>(new mycompare()); //new TreeMap<Student,String>(); 不带参数的构造函数,Student中 已经写了compareTo 方法比较
7 tm.put(new Student("lisi01",25),"beijing");
8 tm.put(new Student("lisi02",22),"tianjing");
9 tm.put(new Student("lisi02",22),"dongjing"); //put的特点:后者会覆盖前面的value。
10 tm.put(new Student("lisi04",20),"shanghai");
11 tm.put(new Student("lisi03",23),"xiamen");
12
13 Set<Student> ks=tm.keySet();
14 for(Iterator<Student> it=ks.iterator();it.hasNext();)
15 {
16 Student stu=it.next();
17 String address=tm.get(stu);
18 System.out.println(stu.getName()+".."+stu.getAge()+".."+address);
19 }
20 /*
21 Set<Map.Entry<Student,String>> et=tm.entrySet();
22 for(Iterator<Map.Entry<Student,String>> it=et.iterator();it.hasNext();) //Iterator 泛型别忘了<Map.Entry<Student,String>>
23 {
24 Map.Entry<Student,String> me=it.next();
25 String address=me.getValue();
26 Student info =me.getKey();
27 System.out.println(info.getName()+".."+info.getAge()+".."+address);
28 } */
29 }
30 }
31 class mycompare implements Comparator<Student>
32 {
33 public int compare(Student s1,Student s2)
34 {
35 // Student s1=(Student)o1;
36 // Student s2=(Student)o2;
37 int num= new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
38 if(num==0)
39 {
40 return s1.getName().compareTo(s2.getName()) ;
41 }
42 return num;
43 }
44 }



原文地址:https://www.cnblogs.com/pinotao/p/2314878.html