import java.util.*;
public class TreeSetTest2
{
public static void main(String args[])
{
TreeSet tree=new TreeSet(new MComparator());
Student stu1=new Student(90);
Student stu2=new Student(85);
Student stu3=new Student(95);
Student stu4=new Student(88);
tree.add(stu1);
tree.add(stu2);
tree.add(stu3);
tree.add(stu4);
Iterator i=tree.iterator();
while(i.hasNext())
{
Student s=(Student)i.next();
System.out.print(s.score+" ");
}
}
}
class Student
{
int score;
public Student(int score)
{
this.score=score;
}
}
//集合中存放的为对象,自定义的对象,java默认的排序方法无法对其进行排序,出现异常,因而需要自己定义排序法则!
class MComparator implements Comparator
{
@Override
public int compare(Object o1, Object o2)
{
// TODO Auto-generated method stub
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.score>s2.score)
return 1;
else if(s1.score<s2.score)
return -1;
else return 0;
}
}