本帖最后由 严学韦 于 2012-8-9 16:07 编辑
- import java.util.*;
- 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;
- if(this.age>s.age)
- return 1;
- if(this.age<s.age)
- {
- return 0;
- }
- return -1;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
- class TreeSetDemo
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet();
- ts.add(new Student("lisi01",22));
- ts.add(new Student("lisi02",43));
- ts.add(new Student("lisi03",24));
- Iterator it = ts.iterator();
- while(it.hasNext())
- {
- Student s = (Student)it.next();
- System.out.println(s.getName()+".."+s.getAge());
- }
- }
- }
复制代码 ts.add(new Student("lisi03",24)); 这行代码中学生对象不知道有没有添加进去,或者添加进去没有打印出来……
可是我把下面这段代码if(this.age<s.age) { return 0; } 改成if(this.age<s.age) { return this.name.compareTo(s.name); } 时运行就O了
哪位能用大白话帮我解释下,也可能是我看视频时间长了范2了
|
|