Arrays and collections's sort method

Source: Internet
Author: User
Tags comparable

Differences between comparator and comparable interfaces for object sorting:
Comparable is a common interface that allows you to perform specific comparisons. comparator can be seen as an algorithm implementation. When the collection of containers requires a comparison function, to specify the comparator. This shows a design mode that separates algorithms from data, just like function objects in C ++ STL.
The former should be relatively fixed and bound to a specific class, while the latter is flexible. It can be used for various classes that require comparative functions. It can be said that the former belongs to "static binding", while the latter can "dynamic binding ".
A class implements the camparable interface, indicating that the objects of this class can be compared with each other. If described in mathematical language, there is a full order in the collection composed of objects of this class. In this way, the collection composed of this class object can be sorted using the sort method.
Comparator has two functions:
1. If the class designer does not consider the Compare problem and does not implement the comparable interface, you can use comparator to implement comparison algorithms for sorting.
2. Prepare for using different sorting criteria, such as ascending, descending, or otherwise

 

First, you must know two classes: Java. util. arrays and Java. util. collections (note the difference with collection) collection is the top-level interface of the Collection framework, while collections contains many static methods. We use arrays to sort arrays and collections to sort containers in combination with frameworks, such as arrayslist and sort list.

Sort Arrays
Sorts arrays of the basic data type (primitive type) or string type.
 Int [] intarray = new int [] {4, 1, 3,-23 };
   Arrays. Sort (intarray );
   // [-23, 1, 3, 4]
   
   String [] strarray = new string [] {"Z", "A", "C "};
   Arrays. Sort (strarray );
   // [C, A, Z]
   
   // Case-insensitive sort
   Arrays. Sort (strarray, String. case_insensitive_order );
   // [A, C, Z]
   
   // Reverse-Order sort
   Arrays. Sort (strarray, collections. reverseorder ());
   // [Z, a, c]
   
   // Case-insensitive reverse-Order sort
   Arrays. Sort (strarray, String. case_insensitive_order );
   Collections. Reverse (arrays. aslist (strarray ));
   // [Z, C, A]
Of course, we can also specify a part of the array for sorting. For example, we want to sort the part 0-2 of the array table (assuming the array length is greater than 3), and the other part remains unchanged. We can use:
   Arrays. Sort (strarray, 0, 2 );
In this way, we only sort the first three elements without affecting the subsequent parts.

Sort object arrays
The natural order of this array is unknown, so we need to implement the comparable interface for this class.
Name class
Public class name implements comparable <Name> {
 Public String firstname, lastname;
  
 Public name (string firstname, string lastname ){
         This. firstname = firstname;
         This. lastname = lastname;
     }
    Public int compareto (name o ){        // Implementation Interface
         Int lastcmp = lastname. compareto (O. lastname );
         Return (lastcmp! = 0? Lastcmp: firstname. compareto (O. firstname ));
     }  
    Public String tostring (){              // Easy output test
         Return firstname + "" + lastname;
     }
}
In this way, when we sort the array of this object, we will first compare the lastname, then compare the firstname, and then get the order of the two objects, as implemented in compareto (name o ).

Test with a program
Namesort class
Import java. util .*;
Public class namesort {
 Public static void main (string [] ARGs ){
  // Todo auto-generated method stub
  Name [] namearray = new name [] {
               New name ("John", "Lennon "),
               New name ("Karl", "Marx "),
               New name ("Groucho", "Marx "),
               New name ("Oscar", "grouch ")
           };
           Arrays. Sort (namearray );
           For (INT I = 0; I <namearray. length; I ++ ){
               System. Out. println (namearray [I]. tostring ());
           }
 }
}

Sort the collection framework
If arrays. Sort () is understood to sort arrays, the use of the Collection framework is similar. Replace arrays with collections. Note that collections is a class and collection is an interface.
Suppose there is such a linked list:
   Jsonlist list = new jsonlist ();
   List. Add (4 );
   List. Add (34 );
   List. Add (22 );
   List. Add (2 );
We only need to use:
   Collections. Sort (list );
You can sort the elements in ll in the ascending order, and the result is:
   [2, 4, 22, 34]
If the element in the SORT list is string, the basic data type is also sorted from small to large.
If you want to implement reverse sorting, that is, sorting from large to small:
   Collections. Sort (list, collectons. reverseorder ());
If the elements in the sorted list are custom objects, You can implement the comparable interface like the name object above, so that collection. Sort () can be sorted for you.

Custom sorting of Objects
You can use sort (list <t> list, comparator <? Super T> C) This method is sorted,
First_name_order class
Import java. util .*;
Public class first_name_order implements comparator <Name> {
 Public int compare (name N1, name N2 ){
       Int firstcmp = n1.firstname. compareto (n2.firstname );
       Return (firstcmp! = 0? Firstcmp: n1.lastname. compareto
               (N2.firstname ));
 }
}

In the above namesort, replace arrays. Sort (namearray); with the following statement:
List <Name> List = arrays. aslist (namearray); // convert the name array to list
Collections. Sort (list, new first_name_order ());

 

 

The following example shows how to sort keys in descending order.

Import java. util .*;
Public class descmap implements comparator <string> {

Public int compare (string O1, string O2)
{
Int map1 = integer. parseint (O1 );
Int MAP2 = integer. parseint (O2 );
Return map2-map1;
}

Public static void main (string [] ARGs)
{
String [] arraysources = {"1", "2", "3", "0 "};
Int [] arrayvalue = {1,424, 32,123 };
Map mapcurrentwebsite = new treemap (New descmap ());

For (INT I = 0; I <arraysources. length; I ++)
{
Mapcurrentwebsite. Put (arraysources [I], new INTEGER (arrayvalue [I]);

}

Collection Col = mapcurrentwebsite. Values ();
Vector V1 = new vector (COL );
For (INT I = 0; I <v1.size (); I ++)
System. Out. println (integer) v1.get (I ));
}
}

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.