importjava.util.*; class StudentAndSetDeno { public static void main(String[] args) { Collection<Student> students= new TreeSet<Student>(new MyComparator()); students.add(newStudent("dengfeifei1",23,85)); students.add(newStudent("dengfeifei2",23,86)); students.add(newStudent("dengfeifei3",23,87)); students.add(newStudent("dengfeifei4",23,88)); students.add(newStudent("dengfeifei5",23,89)); Iterator<Student> it =students.iterator(); while(it.hasNext()) { Student stu = it.next(); System.out.println(stu.getName()+","+stu.getAge()+","+stu.getGrade()); } } } classMyComparator implements Comparator<Student> { public int compare(Student stu1,Studentstu2) { //从大到小排序只需将比较的对象调过来就可以了 int num = newInteger(stu2.getGrade()).compareTo(new Integer(stu1.getGrade())); return num; } } classStudent //用TreeSet集合存储自定以对象,我给集合自定义比较器了,那么这个自定义的类还需要实现Comparable接口和覆盖compareTo方法吗??? { private String name; private int age; private int grade; public Student(String name,int age,intgrade) { this.name = name; this.age = age; this.grade = grade; } 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 setGrade(int grade) { this.grade = grade; } public int getGrade() { return grade; } }
|