package com.sdtu.cn;
import java.util.Comparator;
import java.util.TreeSet;
import java.util.Iterator;
class Student{
String name;
int age;
float score;
public Student(String name, int age, float score) {
super();
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", score=" + score
+ "]";
}
static class StudentCompare implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
int result = s1.score> s2.score?1:(s1.score==s2.score?0:-1);
if(result == 0){
result = s1.name.compareTo(s2.name);
}
return result;
}
}
}
public class TreeSetTest {
public static void main(String[]args){
TreeSet ts = new TreeSet(new Student.StudentCompare());
ts.add(new Student("老五",21,90));
ts.add(new Student("老二",23,79));
ts.add(new Student("老四",24,71));
ts.add(new Student("老三",23,75));
ts.add(new Student("老大",25,78));
Iterator it = ts.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
|