本帖最后由 李万海 于 2013-3-22 18:17 编辑
- import java.util.*;
- class CompareToDemo
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet(new MyCompare());
- ts.add(new Student("李雷",18,94));
- ts.add(new Student("韩梅",19,97));
- ts.add(new Student("露西",17,96));
- ts.add(new Student("莉莉",17,94));
- ts.add(new Student("汤姆",18,95));
- Iterator it = ts.iterator();
- while(it.hasNext())
- {
- Student stu = (Student)it.next();
- System.out.println("\t"+"姓名:"+stu.getName()+" "+"年龄:"+stu.getAge()+" "+"成绩:"+stu.getResult());
- }
- }
- }
- class Student implements Comparable
- {
- private String name;
- private int age;
- private int result;
- Student(String name,int age,int result)
- {
- this.name=name;
- this.age=age;
- this.result=result;
- }
- public void setName(String name)
- {
- this.name=name;
- }
- public String getName()
- {
- return name;
- }
- public void setAge(int age)
- {
- this.age=age;
- }
- public int getAge()
- {
- return age;
- }
- public void setResult(int result)
- {
- this.result=result;
- }
- public int getResult()
- {
- return result;
- }
- }
- class MyCompare implements Comparator
- {
- public int compare(Object o1,Object o2)
- {
- Student s1 =(Student)o1;
- Student s2 =(Student)o2;
- int num = new Integer(s1.getResult()).compareTo(new Integer (s2.getResult()));
- if(num==0)
- return s1.getName().compareTo(s2.getName());
- }
- }
复制代码 编译时提示没有覆盖Comparator中的方法,要覆盖方法后才能调用,应该如何覆盖?
|