1-Letter Comparator Implementation method code in reverse order
Import Java.util.Comparator;
Import Java.util.Iterator;
Import Java.util.TreeSet;
public class TreeSetTest3 {public
static void Main (string[] args) {
TreeSet set = new TreeSet (new Mycomparator ()) ;
Set.add ("C");
Set.add ("A");
Set.add ("B");
Set.add ("E");
Set.add ("F");
Set.add ("D");
for (Iterator iter = Set.iterator (); Iter.hasnext ();) {
String value = (string) iter.next ();
System.out.println (value);
}} Class Mycomparator implements comparator{
@Override public
int Compare (object O1, Object O2) {
String S1 = (String) O1;
String s2 = (string) O2;
Return S2.compareto (S1);
}
2 people in ascending order to achieve the comparator interface method, the source code is as follows
Import Java.util.Comparator;
Import Java.util.TreeSet;
public class TreeSetTest2 {public
static void Main (string[] args) {
TreeSet set = new TreeSet (New Mycomparator2 () );
person P1 = new person (a);
person P2 = new person (a);
Person P3 = new person (a);
person P4 = new person (n);
Set.add (p1);
Set.add (p2);
Set.add (p3);
Set.add (p4);
SYSTEM.OUT.PRINTLN (set);
}
Class person{
int score;
Public person (int score) {
this.score = score;
}
@Override public
String toString () {return
string.valueof (this.score);
}
}
Class Mycomparator2 implements comparator{
@Override public
int Compare (object O1, Object O2) {person
p1 = (person) O1;
person P2 = (person) O2;
if (P1.score>p2.score) {return
1;
}
if (P1.score==p2.score) {return
0;
}
Return-1
}
}
3 This uses a policy pattern.