本帖最后由 王超 于 2012-6-12 23:17 编辑
- import java.util.*;
- class TreeSetDemo_2
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet(new MyCompare());
- ts.add(new Student("lisi02",22));
- ts.add(new Student("lisi022",20));
- ts.add(new Student("lisi01",19));
- ts.add(new Student("lisi03",24));
- ts.add(new Student("lisi02",24));
- Iterator it = ts.iterator();
- while(it.hasNext())
- {
- Student stu = (Student)it.next();
- System.out.println(stu.getName()+"....."+stu.getAge());
- }
- }
- class MyCompare implements Comparator
- {
- public int compare(Object o1,Object o2)
- {
- Student s1 = (Student)o1;
- Student s2 = (Student)o2;
- return s1.getName().compareTo(s2.getName());
- }
- }
- 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)
- {
- //return 1;
- 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 this.name.compareTo(s.name);
- }
- return -1;
- }
- }
复制代码 错误是:
TreeSetDemo_2.java:77: 进行语法解析时已到达文件结尾
|
|