TreeSet有四种构造方法,默认方法创建一个自然顺序的tree set,指定排序选择第三种构造方法,Comparator是一种接口,想要使用它首先应该创建子类实现接口,重写其中的compare方法进行指定排序。
compare方法的两个形参,都是Object类型的,返回值可以是负数,0,或者正数,代表第一个参数小于,等于或者大于第二个参数。
<span style="font-size:18px;">
</span>
<span style="font-size:18px;">源代码如下:</span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;">package control;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetTest04
{
public static void main(String[] args)
{
Student student1 = new Student(49);
Student student2 = new Student(68);
Student student3 = new Student(93);
Student student4 = new Student(77);
TreeSet set =new TreeSet(new MyComparator());
set.add(student1);
set.add(student2);
set.add(student3);
set.add(student4);
for (Iterator iterator = set.iterator();iterator.hasNext();)
{
Student S = (Student)iterator.next();
System.out.println(S.score);
}
}
}
class Student
{
int score;
public Student(int value)
{
this.score = value;
}
public String toSting()
{
return String.valueOf(this.score);
}
}
class MyComparator implements Comparator
{
@Override
public int compare(Object o1, Object o2)
{
Student s1 = (Student)o1;
Student s2 = (Student)o2;
return -(s2.score - s1.score) ;
}
}
</span>
今天才知道可以直接选择粘贴源代码,哈哈