┳ TreeSet (实现了SortedSet接口的类)
1. TreeSet是依靠TreeMap来实现的。
2. TreeSet是一个有序集合,TreeSet中的元素按照升序排列,缺省是按照自然排序,一位着TreeSet要实现Comparable接口。
3. 可以在构造TreeSet对象时,传递实现了Comparable接口的比较器对象。
demo
import java.util.*;
class TreeSetTest
{
public static void main(String[] args){
TreeSet ts = new TreeSet();
ts.add(new Student("one",1));
ts.add(new Student("two",4));
ts.add(new Student("three",3));
Iterator it = ts.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
class Student implements Comparable
{
private String name;
private int num;
//为了调用方便声明为static
static class StudentComparator implements Comparator
{
public int compare(Object o1,Object o2){
Student s1 =(Student)o1;
Student s2 =(Student)o2;
int result;
result = s1.num > s2.num ? 1 :(s1.num==s2.num ? 0 : -1);
if(result == 0){ //student的num相同,比较name,因为name为String类型,它实现了Comparable<String>
result = s1.name.compareTo(s2.name);
}
return result;
}
}
public Student(String name,int num){
this.name = name;
this.num = num;
}
public int compareTo(Object o){
Student s =(Student)o;
return num > s.num ? 1 : (num == s.num ? 0 : -1);
}
public String toString(){
return "num="+num+" "+"name="+name;
}
}