本帖最后由 lkjghvcx@163.co 于 2013-7-6 10:21 编辑
没明白楼主的意思:改了下 TreeSet ts=new TreeSet(); //应该这样
ts.add(new Student("lisi01",22)); //这样添加
- import java.util.*;
- class TreeSetDemo
- {
- public static void main(String[] args)
- {
- // TreeSet ts=new TreeSet(new Student());
- TreeSet ts=new TreeSet(); <font color="#ff0000">//应该这样</font>
- //TreeSet<Student> ts=new TreeSet<Student>(); 或者用泛型
- // ts.add("lisi01",22);
- <font color="#ff0000"> ts.add(new Student("lisi01",22)); </font>
- // ts.add("lisi02",20);
- ts.add(new Student("lisi02",20));
- // ts.add("lisi04",19);
- ts.add(new Student("lisi04",19));
- // ts.add("lisi03",19);
- ts.add(new Student("lisi03",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+"......compareTo......"+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 this.name;
- }
- public int getAge()
- {
- return this.age;
- }
- }
复制代码 控制台输出:
lisi02......compareTo......lisi01
lisi04......compareTo......lisi01
lisi04......compareTo......lisi02
lisi03......compareTo......lisi02
lisi03......compareTo......lisi04
lisi03...19
lisi04...19
lisi02...20
lisi01...22
|