Natural sorting and comparer sorting in Java _java

Source: Internet
Author: User
Tags comparable sorted by name sorts

Objective

The comparison of two objects "size" is compared when the algorithm is performed to insert sort, hill sort, and merge sort. It's easy to understand the i>j of integer types, but how do we compare the size of two objects when we sort multiple objects? Such comparisons of STU1 > Stu2 are clearly impossible to compile. To solve the problem of how to compare the size of two objects, JDK provides two interfaces java.lang.Comparable and java.util.Comparator .

One, natural sort: java.lang.Comparable

Only one method is provided in the comparable interface: the compareTo(Object obj) return value of the method is int. If the return value is positive, the current object (the object calling the method) is larger than the Obj object, or small, or zero, which means that the two objects are equal.

The following is a Student class that implements the comparable interface:

public class Student implements comparable { 
 
 private int id; 
  
 private String name; 
 
 Public Student () { 
  super (); 
 } 
 
 @Override public 
 int compareTo (Object obj) { 
  if (obj instanceof Student) { 
   Student stu = (Student) obj; 
   return id-stu.id; 
  } 
  return 0; 
 } 
 
 @Override public 
 String toString () {return 
  "<" + ID + "," + name + ">"; 
 } 

Student implements the natural sort interface comparable, how do we use this interface to sort a set of Student objects? When we were learning arrays, we used a class to sort an integer array: java.util.Arrays . We use the Arrays sort method to order an integer array. Flipping through the API document, you will find that the sort method is Arrays in many overloaded forms, including sort(Object[] obj) , in other words, Arryas can sort the array of objects, using the comparable interface when comparing the "size" of the two objects in the sorting process compare To method.

public class Comparetest {public 
 
 static void Main (string[] args) { 
  Student stu1 = new Student (1, "Little"); 
  Student STU2 = new Student (2, "Cyntin"); 
  Student stu3 = new Student (3, "Tony"); 
  Student stu4 = new Student (4, "Gemini"); 
   
  student[] Stus = new Student[4]; 
  Stus[0] = STU1; 
  STUS[1] = Stu4; 
  STUS[2] = STU3; 
  STUS[3] = STU2; 
  System.out.println ("Array:" + arrays.tostring (stus)); 
  Arrays.sort (stus); 
  System.out.println ("Sort:" + arrays.tostring (stus)); 
 } 

The order in which elements are added in the Student array is not added by the number ID. After the call Arrays.sort(stus) , the Student array is sorted, regardless of which sort algorithm is used to implement, compare two objects "size" This operation, it is sure to do. So how do you compare the "size" of two objects? Student implementation of the comparable interface to play a role. The Sort method converts the object that is to be compared to the comparable, and calls the CompareTo method to determine the size of the two objects based on their return value. So, the original Student unordered ordinal group in this example becomes the Student array sorted by the school number.

But we notice that the sort algorithm is bound to the Student class, and Student has only one sort algorithm. But the real world is not like this, if we do not want to sort by the number of learning how to do? What if we want to sort the students by name? We can only modify the CompareTo method of the comparable interface of the Student class and change it to sort by name. What if there are two operations in the same system, one is sorted by school number, and the other is sorted by name? It is not possible to write the implementation of two CompareTo methods in the Student class body. So it seems that comparable has its limitations. To make up for this shortcoming, the JDK also provides us with another sort of order, which is the comparator sort to say below.

Second, the comparator sort: java.util.Comparator

As I mentioned above, the reason to provide a comparer is to sort the interface, because sometimes it is necessary to sort the same object in many different ways, and this natural sort comparable is not possible. In addition, one advantage of the Comparator interface is that it separates the comparison sort algorithm from the concrete entity classes.

The flip API will find that Arrays.sort has an overloaded form: The sort(T[] a, Comparator<? super T> c) method parameter is written in generics, which we haven't mentioned yet. We can think of it as this: the sort(Object[] a, Comparator c) method means to sort the Object array according to the comparison sort algorithm given by the comparator C. The Comparator interface defines two methods: compare(Object o1, Object o2) and methods, equals because methods equals are available for all objects, so when we implement the Comparator interface, we simply rewrite compare the method without overriding equals the method. The description of the overridden Equals method in the Comparator interface is: "Note that it is always safe not to override the Object.equals(Object) method." However, in some cases, overriding this method allows the program to determine whether two different Comparator enforce the same sort, thereby improving performance. ”。 We just need to know the first sentence is OK, that is, you can not think how to implement the Equals method, because even if we do not show the implementation of the Equals method, but using the object class Equals method, the code is still safe.

So let's write a code to sort by using a comparer. Or use the Student class to do, just did not implement comparable interface. Because the implementation class of the comparer only implements a method with the display, we can implement it without writing a class specifically, and when we need to use the comparer, we can write an anonymous inner class to implement the Comparator.

Here's how we sort by name:

public void Sortbyname () { 
 Student stu1 = new Student (1, "Little"); 
 Student STU2 = new Student (2, "Cyntin"); 
 Student stu3 = new Student (3, "Tony"); 
 Student stu4 = new Student (4, "Gemini"); 
  
 student[] Stus = new Student[4]; 
 Stus[0] = STU1; 
 STUS[1] = Stu4; 
 STUS[2] = STU3; 
 STUS[3] = STU2; 
 System.out.println ("Array:" + arrays.tostring (stus)); 
 
 Arrays.sort (Stus, New Comparator () { 
 
  @Override public 
  int Compare (object O1, Object O2) { 
   if (O1 instanceo F Student && O2 instanceof Student) {Student S1 
    = (Student) O1; 
    Student s2 = (Student) O2; 
    Return S1.getid ()-S2.getid (); Return by ID 
    s1.getname (). CompareTo (S2.getname ());///By name 
   } return 
   0;} 
   
 ); 
  
 System.out.println ("Sorted:" + arrays.tostring (stus)); 

When we need to sort Student by number, we simply modify the code in the inner class that implements comparator in our sorting method without modifying the Student class.

Note: Of course, you can also implement the Comparator interface with the Student class, so that Student is the (is a) comparer (Comparator). When you need to use this sort, you can use Student as a Comparator, and you can pass Student as a parameter to the sort method, because Student is a Comparator. But such code is not a good code, because we use the comparator (Comparator), one of the important reasons is that this can be the comparison algorithm and the specific class separation, reduce the coupling between classes.

TreeSet provides support for both methods of comparison, corresponding to the two construction methods of TreeSet:

1, TreeSet (): Based on the TREESET elements implemented by the comparable interface of the CompareTo method of comparison sorting

2, TreeSet (Comparator Comparator): Compare the ordering of elements in TreeSet according to the given Comparator comparator

When you add an element to the TreeSet, TreeSet sorts the elements. As for whether it is sorted by nature or by comparison, it depends on how your TreeSet structure is written. Of course, when you add the first element, there is no comparison, there are no elements in the TreeSet, and who is it?

Next, give the TreeSet test code that uses two sorts of comparison methods:

/** * Using the natural sort * Student must implement the comparable interface, or it will throw classcastexception/public void tes 
 TSortedSet3 () {Student stu1 = new Student (1, "Little"); 
 Student STU2 = new Student (2, "cyntin"); 
 Student stu3 = new Student (3, "Tony"); 
 
 Student stu4 = new Student (4, "Gemini"); 
 SortedSet set = new TreeSet (); 
 Set.add (STU1); Set.add (STU3); 
 If student does not implement comparable interface, throw ClassCastException set.add (STU4); 
 Set.add (STU2); 
 Set.add (STU4); 
 
 Set.add (New Student ("Little")); 
SYSTEM.OUT.PRINTLN (set); } 
/** * Using comparer to sort * Student can just be a simple Java class without implementing the comparable interface/public void Testsortedse 
 T3 () {Student stu1 = new Student (1, "Little"); 
 Student STU2 = new Student (2, "cyntin"); 
 Student stu3 = new Student (3, "Tony"); 
 
 Student stu4 = new Student (4, "Gemini"); SortedSet set = new TreeSet (new Comparator () {@Override public int compare (object O1, Object O2) {if (O1 ins 
    tanceof Student && O2 instanceof Student) {Student S1 = (Student) O1; 
    Student s2 = (Student) O2; 
   Return S1.getname (). CompareTo (S2.getname ()); 
  return 0; 
 
 } 
   
 }); 
 Set.add (STU1); 
 Set.add (STU3); 
 Set.add (STU4); 
 Set.add (STU2); 
 Set.add (STU4); 
 
 Set.add (New Student ("Little")); 
SYSTEM.OUT.PRINTLN (set); } 

In addition, the introduction of a tool class, java.util.Collections . Note that this is not a collection interface. Collections is very much like the arrays class. Arrays provides a series of static methods for array operations, lookup sorting, and so on. Collections also provides a series of such methods, but it is used to handle the collection, although the collections class and the collection interface are very similar, but do not be deceived by the name of collections, It is not only the implementation classes that handle collection interfaces and sub-interfaces, but also the implementation classes of the map interface.

Summarize

Java in the natural sorting and comparator sorting is here, the article introduced or relatively detailed, I hope that the study or work to bring some help, if you have questions you can message exchange.

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.