1.按照字典順序排序,而且去重複函數
1 TreeSet<Integer> treeSet = new TreeSet<>(); 2 treeSet.add(2); 3 treeSet.add(5); 4 treeSet.add(4); 5 treeSet.add(2); 6 treeSet.add(4); 7 treeSet.add(8); 8 treeSet.add(9); 9 10 11 for (Integer integer : treeSet) { 12 System.out.print(integer + " "); 13 } 14 //輸出結果爲 2 4 5 8 9
1 TreeSet<String> treeSet = new TreeSet<>(); 2 treeSet.add("a"); 3 treeSet.add("b"); 4 treeSet.add("c"); 5 treeSet.add("b"); 6 7 8 for (String string : treeSet) { 9 System.out.print(string + " "); 10 } 11 //輸出結果爲 a b c
存儲自定義對象時,須要在自定義對象中繼承 Comparable接口,this
並在類中重寫CompareTo方法spa
1 public int compareTo(Student s) { 2 int num = this.age - s.age;
//結果相等時,也就是爲0時,就不存儲
//結果爲負數,就時倒述,從大到小
//結果爲正數,就是正述,從小到大
3 return num==0? this .name.compareTo(s.name): num; 4 }
1 //Comparator比較器,須要在自定義類上繼承Comparator接口
在重寫compare()方法
須要在主類建立集合對象時在最後的括號中添加(new 對象)
public int compare(Student s, Student s1) { 2 int num = s.age - s1.age; 3 int num1 = s.age1 - s1.age1; 4 return num==0?num1:num ; 5 }
二叉排序樹,輸出規律,先輸出左子數,在根,在輸出右子數,比根小就放在左邊,比根大就放在右邊code
特色:TreeSet是用來排序的,能夠指定一個順序,對象存入後會按照指定的順序排列對象
使用方法:blog
天然排序(Comparable)排序
TreeSet類的add()方法中會把存入的對象提高爲Comparable類型繼承
調用對象的compareTo()方法,和集合中的對象進行比較接口
根據compareTo()方法返回的結果進行存儲string
比較器順序(Comparator)
建立TreeSet的時候能夠指定一個 Comparator
若是傳入Comparator的子類對象,那麼TreeSet就會按照比照器中的順序比較
add()方法內部會自動調用 Comparator 接口中的 compare方法的第二參數
兩種方式的區別
TreeSet構造函數什麼都不傳,默認按照類中的Comparable的順序(沒有就報錯ClassCastException)
TreeSet若是傳入 Comparator,就先按照Comparator