┳ TreeSet (實現(xiàn)了SortedSet接口的類)
1.? TreeSet是依靠TreeMap來實現(xiàn)的。
2.? TreeSet是一個有序集合,TreeSet中的元素按照升序排列,缺省是按照自然排序,一位著TreeSet要實現(xiàn)Comparable接口。
3.? 可以在構造TreeSet對象時,傳遞實現(xiàn)了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類型,它實現(xiàn)了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;
?}
}