本帖最后由 崔一恒 于 2013-7-22 19:24 编辑
- import java.util.*;
- class Student
- {
- private String name;
- private int age;
- private int scores;
- Student(String name,int age,int scores)
- {
- this.name = name;
- this.age = age;
- this.scores=scores;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- public int getScores()
- {
- return scores;
- }
- }
- class Test10
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet(new MyCompare());
- ts.add(new Student("lisi",22,66));
- ts.add(new Student("llinghu",21,87));
- ts.add(new Student("lliuhua",20,96));
- ts.add(new Student("lxiaolei",19,88));
- ts.add(new Student("lzhangsan",18,78));
- Iterator it = ts.iterator();
- while(it.hasNext())
- {
- Student stu = (Student)it.next();
- System.out.println(stu.getName()+"..."+stu.getAge()+"---"+stu.getScores());
- }
- }
- }
- class MyCompare implements Comparator
- {
- public int compare(Object o1,Object o2)
- {
- Student s1 = (Student)o1;
- Student s2 = (Student)o2;
- int num = s1.getScores().compareTo(s2.getScores());
- if(num==0)
- {
- int num1= new Integer(s1.getName()).compareTo(new Integer(s2.getName()));
- if(num1==0){
- return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
- return num1;
- }
- }
-
- return num;
- }
- }
复制代码 运行该代码提醒无法取消引用int[int num = s1.getScores().compareTo(s2.getScores());]
|