package com.itcast.testlist;
import java.util.*;
public class TestError {
public static void main(String[] args) {
TreeSet ss = new TreeSet(new Comparator() {
public int compare(Object o1,Object o2) {
Student s1 = (Student)o1;
Student s2 = (Student)o2;
//这里这样判断很不好,加入score相等的话,就要有次要条件比较,比如姓名和年龄。
//这里我将第二条件变为年龄,当然,当年龄相同时,你还可以判断姓名。
return s1.score > s2.score ? -1 : s1.score < s2.score ? 1 : Integer.valueOf(s1.age).compareTo(s2.age) ;
}
});
ss.add(new Student("张三",17,89));
ss.add(new Student("张一",16,89));//加入这个元素为了验证,当分数一样的时候,年龄越小顺序就在前面。
ss.add(new Student("李四",19,85));
ss.add(new Student("王五",18,90));
ss.add(new Student("赵六",17,92));
ss.add(new Student("小明",18,90));
System.out.println(ss);
}
}
class Student{
String name;
int age;
int score;
public Student(String name, int age, int score) {//你的代码中的形参写的不对应。
this.name = name;
this.age = age;
this.score = score;
}
public String toString(){
return "Student[name:"+name+",age:"+age+",score:"+score+"]";
}
}
|