本帖最后由 潘际昌 于 2013-11-24 00:53 编辑
import java.util.*;
public class Test
{
public static void main(String[] args) {
TreeSet<Student> ts=new TreeSet<Student>(new myComparator());
ts.add(new Student("zhangsan1",20,97));
ts.add(new Student("zhangsan2",21,99));
ts.add(new Student("zhangsan5",25,95));
ts.add(new Student("zhangsan3",19,98));
ts.add(new Student("zhangsan7",15,90));
Iterator<Student> it = ts.iterator();
while(it.hasNext())
{
Student s= it.next();
System.out.println(s.getName()+","+s.getAge()+","+s.getScore());
}
}
}
class myComparator implements Comparator<Student>
{
public int compare(Student s1,Student s2)
{
int num=new Integer(s1.getScore()).compareTo(new Integer(s2.getScore()));
if(num==0)
{
return s1.getName().compareTo(s2.getName());
}
return num;
}
}
class Student
{
String name;
int age;
int score;
Student(String name,int age,int score)
{
this.name=name;
this.age=age;
this.score=score;
}
String getName()
{
return name;
}
int getAge()
{
return age;
}
int getScore()
{
return score;
}
}比较器里面,为什么 s1.getName().compareTo(s2.getName());字符型可以直接比较,而int型
int num=new Integer(s1.getScore()).compareTo(new Integer(s2.getScore()));还需要new Interger()呢?
|