本帖最后由 我叫MT 于 2014-1-3 17:44 编辑
- 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("lisi007",20));
- ts.add(new Student("lisi09",19));[b][/b]
- ts.add(new Student("lisi08",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 name;
- }
- public int getAge()
- {
- return age;
- }
- }
复制代码
第34行,有一个转换不懂Student s = (Student)obj;为什么要在这里转换,还有就是为什么要转obj,这里的obj代表什么 |
|