本帖最后由 赵彦丰 于 2014-3-26 11:51 编辑
代码如下 帮我看看那出问题了
- import java.util.*;
- /*
- * TreeSet 集合 中存储学生 按照年龄排序
- * */
- class test
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet(new myComp());
- ts.add(new Student("abs1",25));
- ts.add(new Student("abs2",30));
- ts.add(new Student("abs3",25));
- ts.add(new Student("abs4",18));
- ts.add(new Student("abs5",16));
-
- Iterator it = ts.iterator();
-
- while(it.hasNext())
- {
- Student s = (Student)it.next();
- System.out.println(s.getName()+"--"+s.getAge());
- }
- }
- }
- class myComp implements comparator
- {
- public int compare(Object o1, Object o2)
- {
- Student s1 = (Student)o1;
- Student s2 = (Student)o2;
- int num = new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
- if(num == 0)
- {
- return s1.getName().compareTo(s2.getName());
- }
- return num;
- }
- }
- class Student //implements Comparable
- {
- private String name;
- private int 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 this.name.compareTo(s.name);
- else
- return -1;
- }*/
- Student(String name, int age)
- {
- this.name = name;
- this.age = age;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
复制代码
错误提示
|