- import java.util.*;
- class Student
- {
- private String name;
- private int age;
- Student(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
-
- public String getName()
- {
- return name;
- }
-
- public int getAge()
- {
- return age;
- }
- }
-
- class StudentDemo
- {
- public static void main(String[] args)
- {
- TreeSet<Student> ts=new TreeSet<Student>(new MyCompare());
-
- ts.add(new Student("zhangsan01",20));
- ts.add(new Student("zhangsan02",25));
- ts.add(new Student("zhangsan03",21));
- ts.add(new Student("lisi",22));
-
- Iterator<Student> it=ts.iterator();
-
- while(it.hasNext())
- {
- System.out.println(it.next().getName()+"....."+it.next().getAge());
- }
- }
- }
-
- class MyCompare implements Comparator<Student>
- {
- public int compare(Student o1,Student o2)
- {
- int num=new Integer(o1.getAge()).compareTo(new Integer(o2.getAge()));
- if(num==0)
- return o1.getName().compareTo(o2.getName());
- return num;
- }
- }
- 运行的结果是:
- zhangsan01.....21
- lisi.....25
- 但我明明写的是四个人呀!为什么只存了两个
复制代码
|