TreeSet
- TreeSet是依靠TreeMap來實現的;
- TreeSet是一個有序集合,TreeSet中元素將按照升序排列,缺省是按照自然順序進行排列,意味着TreeSet中元素要實現Comparable接口;
- 我們可以在構造TreeSet對象時,傳遞實現了Comparator接口的比較器對象;
- HashSet和TreeSet的比較
- HashSet是基於Hash算法實現的,其性能通常都優於TreeSet。我們通常都應該使用HashSet。在我們需要排序的功能時,我們才使用TreeSet;
import java.util.*;
class TreeSetTest{
public static void main(String[] arg){
TreeSet ts = new TreeSet(new Students.StudentCompare());
ts.add(new Students(11,"zhangsan"));
ts.add(new Students(14,"wangwu"));
ts.add(new Students(10,"lisi"));
ts.add(new Students(11,"ihangsan"));
Iterator it = ts.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
class Students{
int num;
String name;
Students(int num,String name){
this.num = num;
this.name = name;
}
static class StudentComparator implements Comparator{
public int compare(Object o1,Object o2){
Students s1 = (Students)o1;
Students s2 = (Students)o2;
int result = s1.num > s2.num ? 1 : s1.num == s2.num ? 0 : -1;
if(result == 0){
result = s1.name.compareTo(s2.name);
}
return result;
}
}
public String toString(){
return "num="+num+"name="+name;
}
}