本帖最后由 飘落 于 2013-9-26 23:09 编辑
- import java.util.*;
- class TreeMapDemo {
- public static void main(String[] args) {
-
- TreeMap<Student,String> tm=new TreeMap<Student,String>();
- tm.put(new Student("S1",31),"sn001");
- tm.put(new Student("S2",11),"sn002");
- tm.put(new Student("S3",41),"sn003");
- tm.put(new Student("S4",11),"sn004");
- tm.put(new Student("S5",51),"sn005");
- tm.put(new Student("S6",91),"sn006");
- System.out.println(tm);
- }
- }
- class Student implements Comparable<Student>
- {
- private String name;
- private int age;
-
- Student(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
- public void setName(String name)
- {
- this.name=name;
- }
- public void setAge(int age)
- {
- this.age=age;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- public String toString()
- {
- return name+":"+age;
- }
- public int compareTo(Student s)
- {
- int num=age-s.age;
- return num!=0?num:name.compareTo(s.name);
- }
- }
复制代码 重写compareTo()时,代码里面写成s.age、s.name,为什么能正常运行?
因为变量age和name前面有private修饰,所以个人觉得写成s.getAge()、s.getName()才对。
然而,运行结果出乎我的预料。
求解释。
|
|