當把一個對象加入TreeSet集合中時,TreeSet調用該對象的compareTo(Object obj)方法與容器中的其他對象比較大小,返回-1表示該元素在前,1表示該元素在后。
方法一:讓類實現Comparable接口,並覆蓋compareTo()方法,將自定義的類加入TreeSet即可

1 import java.util.Scanner; 2 import java.util.TreeSet; 3 //TreeSet應用 4 class Main { 5 public static void main(String[] args) { 6 Scanner s = new Scanner(System.in); 7 TreeSet<StringDemo> set = new TreeSet<>(); 8 while(s.hasNextLine()) { 9 int n = Integer.parseInt(s.nextLine()); 10 for (int i = 0; i < n; i++) { 11 String string = s.nextLine(); 12 set.add(new StringDemo(string)); 13 } 14 for(StringDemo s1: set) { 15 System.out.println(s1.getString()); 16 } 17 } 18 s.close(); 19 } 20 } 21 class StringDemo implements Comparable{ 22 private String string; 23 StringDemo(String s) { 24 this.string = s; 25 } 26 public int compareTo(Object obj) { 27 StringDemo s = (StringDemo)obj; 28 if(this.string.compareTo(s.string) <= 0) 29 return -1; 30 return 1; 31 } 32 public String getString() { 33 return this.string; 34 } 35 }
方法二:自定義一個實現Comparator的排序器,實現compare()方法(兩個一起比較),在創建TreeSet的時候將此排序器加入即可

1 import java.util.Comparator; 2 import java.util.Scanner; 3 import java.util.TreeSet; 4 //TreeSet應用 5 class Main { 6 public static void main(String[] args) { 7 Scanner s = new Scanner(System.in); 8 TreeSet<String> set = new TreeSet<>(new StrComparator()); 9 while(s.hasNextLine()) { 10 int n = Integer.parseInt(s.nextLine()); 11 for (int i = 0; i < n; i++) { 12 String string = s.nextLine(); 13 set.add(string); 14 } 15 for(String s1: set) { 16 System.out.println(s1); 17 } 18 set.clear(); 19 } 20 s.close(); 21 } 22 } 23 class StrComparator implements Comparator{ 24 public int compare(Object obj1, Object obj2) { 25 String s1 = (String) obj1; 26 String s2 = (String) obj2; 27 if(s1.compareTo(s2) <= 0) 28 return -1; 29 return 1; 30 } 31 }
compare()方法,第一個參數為后加入的,第二個參數為已存在的(不按順序,使用的數據結構應該為樹),返回1表示參數一在后面,-1在前面,返回0參數一不加入Set