本帖最后由 李涛兴 于 2012-11-24 21:44 编辑
- import java.util.*;
- class TreeSetDemo
- {
- public static void show(Object obj)
- {
- System.out.println(obj);
- }
- 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));
- ts.add(new Student("lisi08",19));
-
- Iterator it=ts.iterator();
- while(it.hasNext())
- {
- //show(it.next());
- Student stu=(Student)it.next();
- show(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+"..compare.."+s.name);
- if (this.age>s.age)
-
- return 1;
- if (this.age==s.age)
- {
- int x=this.name.compareTo(s.name);
- return x;
- }
-
- return -1;
-
-
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
复制代码 请问代码中的“public int compareTo(Object obj)”函数被那个函数调用,它又将值返回给了谁呢?感觉很茫然,搞不清其中的实现原理,求高手们给予解答。 |