Method One: Let the class implement the comparable interface, and overwrite the CompareTo () method, add the custom class to TreeSet
1 ImportJava.util.Scanner;2 ImportJava.util.TreeSet;3 //TreeSet Applications4 classMain {5 Public Static voidMain (string[] args) {6Scanner s =NewScanner (system.in);7Treeset<stringdemo> set =NewTreeset<>();8 while(S.hasnextline ()) {9 intn =Integer.parseint (S.nextline ());Ten for(inti = 0; I < n; i++) { OneString string =s.nextline (); ASet.add (NewStringdemo (String)); - } - for(Stringdemo s1:set) { the System.out.println (s1.getstring ()); - } - } - s.close (); + } - } + classStringdemoImplementscomparable{ A Privatestring string; at Stringdemo (String s) { - This. String =s; - } - Public intcompareTo (Object obj) { -Stringdemo s =(Stringdemo) obj; - if( This. String.CompareTo (s.string) <= 0) in return-1; - return1; to } + PublicString getString () { - return This. String; the } *}
View Code
Method Two: Customize a sequencer that implements comparator, implement the Compare () method (two comparisons), add this sequencer when creating treeset
1 ImportJava.util.Comparator;2 ImportJava.util.Scanner;3 ImportJava.util.TreeSet;4 //TreeSet Applications5 classMain {6 Public Static voidMain (string[] args) {7Scanner s =NewScanner (system.in);8Treeset<string> set =NewTreeset<> (Newstrcomparator ());9 while(S.hasnextline ()) {Ten intn =Integer.parseint (S.nextline ()); One for(inti = 0; I < n; i++) { AString string =s.nextline (); - Set.add (string); - } the for(String s1:set) { - System.out.println (S1); - } - set.clear (); + } - s.close (); + } A } at classStrcomparatorImplementscomparator{ - Public intCompare (Object Obj1, Object obj2) { -String S1 =(String) obj1; -String s2 =(String) obj2; - if(S1.compareto (S2) <= 0) - return-1; in return1; - } to}
View Code
TreeSet (non-repeatable, automatic sorting) for custom sorting