本帖最后由 赵家阳 于 2012-12-6 16:47 编辑
- import java.util.*;
- public class TreeSetDemo {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet();
- Student st1 = new Student("wangwu001",21);
- Student st2 = new Student("langwu001",21);
- Student st3 = new Student("wangwu001",20);
- Student st4 = new Student("wangwu001",22);
- ts.add(st1);
- ts.add(st2);
- ts.add(st3);
- ts.add(st4);
- /*
- ts.add(new Student("lisi01",18));
- ts.add(new Student("lisi02",29));
- ts.add(new Student("lisd01",21));
- ts.add(new Student("misi01",18));
- ts.add(new Student("lssi01",19));
- */
- Iterator it = ts.iterator();
- while(it.hasNext())
- {
- Student st = (Student)it.next();
- System.out.println(st.getName()+"======"+st.getAge());
- }
-
- }
- }
- class Student implements Comparable
- {
- private String name;
- private int age;
- Student(String name,int age)
- {
- this.name = name;
- this.age = age;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- public int compareTo(Object obj)
- {
- if(!(obj instanceof Student))
- {
- throw new RuntimeException("不是学生对象");
- }
- Student st = (Student)obj;
- System.out.println(st.getName()+",......,.."+st.getAge());
- if(this.age >st.age)
- {
- return 1;
- }
- if(this.age == st.age)
- {
- return this.name.compareTo(st.getName());
- }
- return -1;
- }
- }
复制代码 疑问:
在上面两种创建对象的方式结果都是正确的,
但是,在此处:public int compareTo(Object obj) 其中的obj并没有明确指定是哪个对象,CompareTo方法底层是怎么实现在
比较的过程中能与各个对象进行比较呢?
求精讲!!!!
|