本帖最后由 聖手`书生 于 2013-4-25 23:09 编辑
- 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));
- ts.add(new Student("lisi08",19));
- //ts.add(new Student("lisi007",20));
- //ts.add(new Student("lisi01",40));
- 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)
- {
- //return 0;
- 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;
- }
- }
复制代码 老师讲解的时候,明明打印的结果没有lisi02和lisi02 对比,但是我自己运行时候,就会产生这情况,如图中红色框框结果。确实不解,需求合理解释。 |
|