If you have a list of Integer objects, and you want to use Coolections.sort to sort them. Also, you have to specify a comparer for yourself, because you want to arrange them in descending order rather than ascending order. Here are some code examples that show how to do this:
Import java.util.*
public class LocalDemo1 {
//using the Comparator anonymous class sort.
static void Sortanon (List list) {
Collections.sort (list, new Comparator () {
public int compare (
Object O1 , Object O2) {int cc = ((Integer) O1). CompareTo (O2); return (CC < 0? 1:cc > 0? -1:0);
}
});
}
///using the local class that implements Comparator
static void sortlocal (List list) {class Mycomparator implements Comparator {
public int Compare (object O1, Object O2) {int cc = ((Integer) O1). CompareTo (O2); return (CC < 0? 1:cc > 0? -1:0 );
}};
Collections.sort (list, new Mycomparator ());
}
public static void Main (string[] args) {
List list1 = new ArrayList ();
List1.add (New Integer (1);
L Ist1.add (New Integer (2));
List1.add (New Integer (3));
Sortanon (List1);
System.out.println (List1);
List list2 = new ArrayList ();
List2.add (New Integer (1));
List2.add (New Integer (2));
List2.add (New Integer (3));
Sortlocal (List2);
System.out.println (LIST2);
}}
The output of this procedure is as follows:
[3, 2, 1]
[3, 2, 1]
The Comparator interface is implemented using two different methods in the above. The first method uses anonymous classes, and the second method uses the local class, what is the difference between the two: a little different in format?? The definition of an anonymous class is simpler, and it is actually part of the following expression:
Comparator C = new Comparator () {...};