本帖最后由 騛鹏 于 2013-3-20 11:02 编辑
- import java.util.*;
- class TreeSetDemo
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet();
- ts.add(new Student("lisi02",22));
- ts.add(new Student("lisi07",20));
- ts.add(new Student("lisi09",19));
- ts.add(new Student("lisi08",23));
- Iterator it = ts.iterator();
- while (it.hasNext())
- {
- Student stu = (Student)it.next();
- System.out.println(stu.getName()+"...."+stu.getAge());
- }
- }
- }
- class Student implements Comparable
- {
- private String name;
- private int age;
- Student(String name,int age)
- {
- this.name = name;
- this.age = age;
- }
- public int compareTo(Object obj)
- {
- if(!(obj instanceof Student))
- throw new RuntimeException("No Student");
- Student s = (Student)obj;
- System.out.println(this.name+".....compareto....."+s.name);
- if(this.age == s.age)
- return this.name.compareTo(s.name);
- if(this.age > s.age)
- return -1;
- return 1;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
复制代码
为何 Lisi 08没有与 Lisi 09比较呢 |