代码如下:- package Map1;
- import java.util.*;
- class Student_1 implements Comparable<Student_1>
- {
- private String name;
- private int age;
- Student_1(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
-
- public int compareTo(Student_1 stu)
- {
- if(!(stu instanceof Student_1))
- throw new ClassCastException("error!");
- System.out.println("!!!!");
- int num=new Integer(this.age).compareTo(new Integer(stu.age));
-
- if(num==0)
- return this.name.compareTo(stu.name);
- return num;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
-
- public String toString()
- {
- return name+":"+age;
- }
- }
- public class TreeMapTest_2 {
- public static void main(String[] args)
- {
- TreeMap<Student_1,String> ts=new TreeMap<Student_1,String>();
-
- ts.put(new Student_1("sunyan3",3),"wuhan");
- ts.put(new Student_1("sunyan2",4),"hunan");
- ts.put(new Student_1("sunyan3",1),"wuhan");
-
- //第一种取出方式:keySet
- /*Set<Student_1> s=ts.keySet();
- Iterator<Student_1> it=s.iterator();
- while(it.hasNext())
- {
- Student_1 s1=it.next();
- String addr=ts.get(s1);
- System.out.println(s1+":"+addr);
- }*/
-
- //第二种取出方式:entrySet
- Set<Map.Entry<Student_1,String>> entry=ts.entrySet();
- Iterator<Map.Entry<Student_1,String>> it=entry.iterator();
-
- while(it.hasNext())
- {
- Map.Entry<Student_1,String> s=it.next();
- Student_1 key=s.getKey();
- String Value=s.getValue();
- System.out.println(key+":"+Value);
- }
- }
-
- }
复制代码
问题:将TreeMap<Student_1,String>改为TreeMap<String,Student_1>后,在往其中存入:
ts.put("wuhan",new Student_1("sunyan3",3));
ts.put("hunan",new Student_1("sunyan2",4));
ts.put("wuhan",new Student_1("sunyan3",1));
结果显示的是:wuhan:sunyan3,1 hunan:sunyan2,4;
为什么显示的不是:wuhan:sunyan3:1 suhan:sunyan3:3 hunan:sunyan2:4 |