The use and difference of comparatable interface and comparator interface

Source: Internet
Author: User
Tags comparable integer definition

The following articles go from this blog:


Http://blog.sina.com.cn/s/blog_63c66eb60100slyc.html


The questions that this blog can solve for you are as follows: What is the natural sort collections.sort () and Arrays.sort () the similarities and differences between Comparatable interface and comparator interface are sorted according to each other (theoretical explanation) Comparatable interface and comparator interface practical sorting method (actual example analysis) combined using comparatable and comparator to sort the whole of the following, I wrote this blog post according to the above question:

1, what is the natural sort

Natural sorting is an ascending sort. For different data types, the ascending rule is not the same:
BigDecimal BigInteger Byte Double Integer Long short type, sorted according to the size of the number. For example: 12<23, 111.111>3.23 character, and string types, are sorted by the Unicode value size of each character. For example: "3BC" < "AB" < "ABC" < "one or two"
2, the similarities and differences between Collections.sort () and Arrays.sort ()

First, let's look at the definitions of these two methods:
Collections.sort ()://Its definition has only the following two public static <t extends comparable Super t>> void Sort (list <T> list);

public static <T> void sort (list<t> List, comparator< super t> C);
Arrays.sort ()://There are a number of definitions, here are the representative three public static void sort (int[] a);
public static void sort (object[] a);
public static <T> void sort (t[] A, Comparator. Super t> C);

From their definition, we can see two points:
different points: They apply to different objects.   Collections.sort () only applies to the list type, Arrays.sort () only the array type, of course the array can be int, float, etc., can even be object. 2. Common Ground: They use either the Comparatable interface or the comparator interface, either directly or indirectly.
The Collections.sort () clearly references the two interfaces, which are not discussed here; in Arrays.sort (), in fact, int, float, etc. corresponding encapsulation class integer, float, etc. Have a reference to the docking port comparable, for example: the integer definition is as follows:
Public final class Integer
The extends number implements comparable< integer> comparable interface has a natural sort function by default. So, when we use Arrays.sort (int[]), we have implemented a natural sort of int[] function.

3, Comparatable interface and comparator interface of their respective sorting basis
Introduction:
Since it is sort, you need to specify the sort by element, and you must be able to sort successfully if you specify the sort by element and the method that is invoked is appropriate. (Please remember this sentence firmly)
For a single element class, such as int, float, double, char, string, and so on, the sort by element is the single element that it corresponds to. For multiple-element classes, such as: We customize a student class, its properties have int age; String name, and so on, we need to specify a sort based element.
The comparable interface is sorted by:
Cell class sort. (generally refers to Java in the implementation of the comparable interface of the class, commonly used are: Integer, Float, Double, String, character, etc.), these classes have been sorted by element, so you can directly sort. So in the sort, we can do this: (take int as an example) int[] Intarray = {12,34,0,5,-7,8,1,3};
Arrays.sort (Intarray); This is directly sorted by the size of the int value.
for (int i=0;i<intarray.length;i++)
System.out.println (Intarray[i]);
The results of the program running are: (Natural sort)
A sort of multivariate class.

First, this multivariate class (such as: Student) that needs to be sorted must implement the Comparable<t> interface, and T is the class name of the multiple-element class.
For example: public static Student implments comparable<student>
The Comparato () method is then implemented in the class (which must be inside within that), where we specify the sort by element.
For example:
@Override
public int CompareTo (Student arg0) {
Return Arg0.getname (). CompareTo (THIS.name); Here we specify name as the sort based element
}
Finally, based on the Student instantiation, it is implemented with list<student>, or student[], choosing to use Collection.sort () or Arrays.sort () for sorting.
The comparator interface is sorted by:
Unlike comparable, to implement the comparator interface, it is important to specify the sort by element (either cell or multiple elements) in the program. Also, the class that implements the comparator interface must be outside of the sorted class (such as student). Can be an anonymous class, such as:
Collection.sort (allstudents,new comparator<student> () {
public int Compare (Student one, Student another) {
Return One.getage ()-another.getage ();
}
});
It can also be an external class, such as an instance of class Studentsort implments<student>{};, Collention.sort (allstudent,new studentsort ());
Summary: The comparatable interface must be implemented by the multivariate class itself that needs to be sorted, and the Comparato () method is overridden within it; The comparator interface is implemented outside of the multivariate class that needs to be sorted (that is, using an external class). And you must override the Compara () method in the outer class.

4, Comparatable interface and comparator interface practical sorting method (actual example analysis)

Now we will use the sort of student information system to explain:
Class Name: Student property value: Long ID; String Name;int age;float score; Requirements: According to the school number, name or grade in ascending order all student instances below the two methods, the orange part of two different methods of the place.
First, the use of Camparable interface (a total of 2 files, sorted by the number of ascending order)

Package keNan.com.stu.StudentInfomation;

public class Student implements comparable<student>{
Private String ID;
private String name;
private int age;
private double score;

Define two construction methods for student


Public Student (String ID, string name) {
This (id,name,0,0);
}
Public Student (String ID, string name, int age, double score) {
This.id = ID;
THIS.name = name;
This.age = age;
This.score = score;
}

Property value Access and modification
Public String GetID () {
return ID;
}
Public String GetName () {
return name;
}
public int getage () {
return age;
}
Public double Getscore () {
return score;
}

public void SetID (String newID) {
ID = NewID;
}
public void SetName (String newName) {
name = NewName;
}
public void setage (int newage) {
if (NewAge < 0)
NewAge = 0;
age = NewAge;
}
public void SetScore (double newscore) {
if ((NewsCore < 0) | | (NewsCore > 100))
NewsCore = 0;
Score = NewsCore;
}

Overriding the object string representation method
@Override
Public String toString () {
String info = new string ();
info = ID + ' \ t ' + name + ' \ t ' + age + ' \ t ' + score + ' \ n ';
return info;
}

@Override
public int CompareTo (Student arg0) {
Return This.ID.compareTo (arg0.id);//This is in ascending order, if Arg0.ID.compareTo (this.id) is descending
}
}

Package keNan.com.stu.StudentInfomation;

Import Java.util.Arrays;

public class studentmanage{
public static void Main (string[] args) {
Define a student database
Final int student_num = 4;
student[] allstudents = new Student[student_num];

Initializing student databases
Allstudents[0] = new Student ("00001", "a");
ALLSTUDENTS[1] = new Student ("00003", "B");
ALLSTUDENTS[2] = new Student ("00002", "C");
ALLSTUDENTS[3] = new Student ("00004", "D");
for (int i=0;i<allstudents.length;i++) {
Allstudents[i].setage (I*10);
}
for (int i=0;i<allstudents.length;i++) {
Allstudents[i].setscore (99-i*1.5);
}

Sort by School Number ascending

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.