本帖最后由 王靖远 于 2013-5-25 17:32 编辑
- class TreeSetDemo
- {
- public static void sop(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("lisi01",40));
-
- Iterator it = ts.iterator();
- while(it.hasNext())
- {
- Student stu = (Student)it.next();
- sop(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 0;
- return -1;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
复制代码
这里的第一行为什么 lisi02和lisi02比?明明只有一个lisi02啊。我把除了lisi02都注释掉也无法运行成功,毕老师就可以。帮忙看下哪里出了问题。
|
|