In JAVA, Arrays. sort () uses two methods (Comparable and Comparator interfaces) to sort objects or references.

Source: Internet
Author: User

In JAVA, Arrays. sort () uses two methods (Comparable and Comparator interfaces) to sort objects or references.

I. Description

Custom classes should be sorted in a certain way. For example, a Person class should be sorted in ascending order by age. For example, a Student class should be sorted in descending order by score.

Here we use two methods: one is to use the Comparable interface: Let the class of the object to be sorted implement the Comparable interface, and rewrite the compareTo () method in the Comparable interface, the disadvantage is that you can only sort by one rule.

The other method is to use the Comparator interface: write multiple sort mode classes to implement the Comparator interface, rewrite the compare () method in the new Comparator interface, and call the sort () method of Arrays () when the sort class object is passed as a parameter: public static Void sort (T [] a, Comparator C) sorts the array of specified objects according to the sequence generated by the specified comparator. All elements in the array must be comparable by specifying the comparator (that is, for any e1 and e2 elements in the array, c. compare (e1, e2) cannot throw ClassCastException ).

The advantage is that you can sort by multiple methods. If you want to sort by any method, create a sort class that implements the Comparator interface, and then pass the sorting class objects to Arrays. sort (object to be sorted, object of this sort type)

 

Ii. Source Code

Method 1: Use the Comparable Interface

 

Package tong. day4_27.systemUse; import java. util. arrays;/*** use the Comparable interface to implement the Comparable interface for the class of the object to be sorted, and override compareTo () in the Comparable Interface () method * the disadvantage is that you can only sort by one rule * @ author tong */public class ObjectSort {public static void main (String [] args) {Person [] persons = new Person [5]; persons [0] = new Person ("tom", 45); persons [1] = new Person ("jack ", 12); persons [2] = new Person ("bill", 21); persons [3] = new Person ("kandy", 34 ); persons [4] = new Person (); Arrays. sort (persons); for (Person person: persons) {System. out. println (person) ;}} class Person implements Comparable
 
  
{Private String name; private int age; public Person (String name, int age) {this. name = name; this. age = age ;}public Person () {this ("unknown", 0) ;}// rewrite the compareTo () method of the class, sort it in ascending order @ Overridepublic int compareTo (Person o) {return age-o.age;} // override the toString () method of the Student class, output @ Overridepublic String toString () {return "Person [name:" + name + ", age:" + age + "]" ;}} as follows
 
Running result:

 

 

Method 2: Use the Comparator Interface

 

Package tong. day4_27.systemUse; import java. util. arrays; import java. util. comparator;/*** use the Comparator interface: write multiple sort mode classes to implement the Comparator interface, and override the compare () method * public static in the new Comparator Interface
 
  
Void sort (T [] a, Comparator
  C) sorts the array of specified objects according to the sequence generated by the specified comparator. All elements in the array must be comparable by specifying the comparator * (that is, for any e1 and e2 elements in the array, c. compare (e1, e2) cannot throw ClassCastException ). * The advantage is that you can sort data in multiple ways. If you want to sort data in any way, you can create a sort class that implements the Comparator interface, and then pass the sorting class objects to Arrays. sort (object to be sorted, object of this sorting method class) * @ author tong **/public class ComparatorUse {public static void main (String [] args) {Student [] persons = new Student [5]; persons [0] = new Student ("tom", 1,88, 45 ); persons [1] = new Student ("jack", 6,80, 12); persons [2] = new Student ("bill", 4,68, 21 ); persons [3] = new Student ("kandy", 2, 98, 34); persons [4] = new Student ("lily", 5, 94, 20); System. out. println ("data before sorting:"); for (Student student: persons) {System. out. println (student);} // create a SortByNumber object and pass it as a parameter to Arrays. sortByNumber SortByNumber = new sortByNumber (); Arrays. sort (persons, sortByNumber); System. out. println ("sort by Student ID from low to high:"); for (student Student: persons) {System. out. println (student);} SortByScore sortByScore = new SortByScore (); Arrays. sort (persons, sortByScore); System. out. println ("sorted by Student scores from high to low:"); for (student Student: persons) {System. out. println (student) ;}} class Student {private String name; private int number; private int score; private int age; public Student (String name, int number, int score, int age) {this. name = name; this. number = number; this. score = score; this. age = age;} // override the toString () method of the Student class. Output @ Overridepublic String toString () {return "Student [name: "+ name +", age: "+ age +", number: "+ number +", score: "+ score +"] ";} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getNumber () {return number;} public void setNumber (int number) {this. number = number;} public int getScore () {return score;} public void setScore (int score) {this. score = score;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}}// sort by student ID from low to high and create a SortByNumber class. This class implements Comparator and overrides the compare () class SortByNumber implements Comparator of this interface.
  
   
{// Rewrite the compare () of this interface to sort it by Student ID from small to big (the former minus the latter) @ Overridepublic int compare (Student o1, Student o2) {return o1.getNumber ()-o2.getNumber () ;}// sort by score from high to low and create a SortByScore class. This class implements Comparator and overrides compare () of this interface () class SortByScore implements Comparator
   
    
{// Rewrite the compare () of this interface so that it is sorted by score from high to low (the latter minus the former) @ Overridepublic int compare (Student o1, Student o2) {return o2.getScore ()-o1.getScore ();}}
   
  
 
Running result:

 

Vcg = "src =" http://www.bkjia.com/uploads/allimg/150429/04292W210-1.png "/>

 

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.