- /*
- 往TreeSet集合里面存储自定义对象学生
- 想按照学生的年龄进行排序
- */
- import java.util.*;
- class Demo1
- {
- 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("lisi01",19));
- 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("不是学生对象");
- Student s=(Student)obj;
- System.out.println(this.name+"..."+s.name);
- if(this.age>s.age)
- return 1;
- if(this.age==s.age)
- {
- return this.name.compareTo(s.name);
- }
- return -1;
- }
- public String getname()
- {
- return name;
- }
- public int getage()
- {
- return age;
- }
- }
复制代码
|
|