Comparator,comparable interface differences between object sorting:
Comparable is a general-purpose interface that users can implement to perform their own specific comparisons, while comparator can be seen as an implementation of an algorithm that specifies the comparator when a container set collection needs to compare functions, which shows a design pattern Separates the algorithm from the data, just like the function object in the C + + STL.
The former should be more fixed and binding to a specific class, which is flexible and can be used for each class that needs to compare functions. It can be said that the former belongs to "static binding", while the latter can be "dynamic binding."
A class implements a Camparable interface that indicates that objects of this class can be compared to each other. If it is described in mathematical language, there is a whole sequence in the set of objects of this class. This way, the collection of class objects can be sorted by using the Sort method.
And the comparator has two functions:
1, if the class designers do not take into account the compare problem and do not implement the comparable interface, you can use comparator to implement the comparison algorithm to sort
2, in order to use different sorting criteria to prepare, such as: ascending, descending or other order
The first thing to know is two classes: Java.util.Arrays and java.util.Collections (Note and collection) collection are the top-level interfaces of the collection framework, and the collections contains many static methods. We use the arrays array to sort, and use collections to sort the binding frame container, such as arrayslist,linkedlist.
To sort a set of arrays
Sort the base data type (primitive type) or string-type array
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 section of the array to sort for example, we want to sort the parts of table 0-2 (assuming that the array length is greater than 3), and the rest of the list, we can use:
Arrays.sort (strarray,0,2);
In this way, we just sort the first three elements without affecting the rest.
To sort an array of objects
The natural order of this array is unknown, so we need to implement the comparable interface for the 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 to output test
Return firstname+ "" +lastname;
}
}
In this way, when we sort the array of objects, we compare the LastName, then compare FirstName and then draw 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 frame
if the Arrays.sort () array is already understood, the use of the collection framework is similar. Just replace arrays with collections, note that collections is a class and collection is an interface.
If there is such a list:
linkedlist list=new LinkedList ();
list.add ( 4);
list.add (34);
list.add (22);
list.add (2);
We only need to use:
collections.sort (list),
You can order the elements will be in the sequence of small to large, the result is:
[2, 4, a.
If the elements inside the LinkedList are string, they will also be sorted from small to large like the basic data type.
If you want to implement a sort of reverse order, which is from large to small:
collections.sort (List,collectons.reverseorder ());
If the elements inside the LinkedList are custom objects, you can implement the comparable interface just like the name object above, so that Collection.sort () is sorted for you.
To customize the sort of objects
You can sort by using this method of sort (list<t> List, comparator<? super T> C).
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 namesort above, Arrays.sort (NameArray) is replaced with the following statement
List<name> list=arrays.aslist (NameArray); Converts the array of names to list
Collections.sort (List,new first_name_order ());
Here's an example of descending sort based on TreeMap key
import java.util.*; public class Descmap implements the public int comparator<string>{
E (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 (AR
Rayvalue[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)); }
}
Reproduced from: http://blog.sina.com.cn/s/blog_4fb846a90100d8q0.html