Local classes in the Java language

Source: Internet
Author: User

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 () {...};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.