首页 > 代码库 > TreeSet(不可重复,自动排序)实现自定义排序

TreeSet(不可重复,自动排序)实现自定义排序

方法一:让类实现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 }
View Code

 

方法二:自定义一个实现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 }
View Code

 

TreeSet(不可重复,自动排序)实现自定义排序