Arrays.sort () in Java uses two methods (comparable and comparator interfaces) to sort objects or references

Source: Internet
Author: User
Tags comparable sorts

First, describe

Custom classes are sorted in a certain way, such as when a person class is ordered from small to large according to age, such as a student class to be ranked from highest to lowest by grade.

Here we take two ways, one is to use the comparable interface: the class to which the object is to be sorted implements the comparable interface, and overrides the CompareTo () method in the comparable interface, with the disadvantage that it can only be sorted by one rule.

Another way is to use the comparator interface: Write multiple sort methods to implement the comparator interface, and override the Compare () method in the new comparator interface, in the call Arrays sort () When the sort class object is passed as a parameter: public static <T> void sort (t[] a,comparator<? super T> C), the specified array of objects is sorted according to the order produced by the specified comparer. All elements in an array must be compared by specifying the comparer (that is, C.compare (E1, E2) cannot throw classcastexception for any E1 and E2 elements in the array).

The advantage is that you can sort by a variety of ways, you create a sort class that implements the comparator interface, and then pass an object of that sort class to Arrays.sort (the object that you want to sort on, the sort class)


Second, the source code

Method 1: Use the comparable interface

Package Tong.day4_27.systemuse;import java.util.arrays;/** * uses comparable interface: Enables the class where the object to be sorted implements the comparable interface, And overriding the CompareTo () method in the comparable interface * 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];p ersons[0] =new person ("Tom", "a");p ersons[1] =new person ("Jack", a);p ersons[2] = New Person ("Bill", +);p ersons[3] =new person ("Kandy");p ersons[4] =new person (); Arrays.sort (persons); for (person person:persons) {System.out.println (person);}}} Class Person implements comparable<person>{private string name;private int age;public person (string Name,int age) { THIS.name = Name;this.age = age;} Public person () {This ("unknown", 0);} Override the CompareTo () method of the class so that it sorts @overridepublic int compareTo (person o) {return age-o.age;} In order from small to large. Override the ToString () method of the student class to output @overridepublic String ToString () {return "Person[name:" +name+ ", Age:" +age+ when you enter an object in the following manner "]";}}
Operation Result:


Method 2: Use the Comparator interface

Package Tong.day4_27.systemuse;import Java.util.arrays;import java.util.comparator;/** * Use Comparator interface: Write multiple sort methods to implement the comparator interface and override the Compare () method in the new comparator interface * public static <T> void sort (t[] a, comparator<? Super t> C) to sort the specified array of objects according to the order produced by the specified comparer. All elements in an array must be compared by specifying a comparer (that is, C.compare (E1, E2) should not throw classcastexception for any of the E1 and E2 elements in the array). * The advantage is that you can sort in a variety of ways, you create a sort class that implements the comparator interface, and then pass the object of that sort class to Arrays.sort (the object to be sorted, the sort Class) * @author Tong * */ public class Comparatoruse {public static void main (string[] args) {student[] persons = new STUDENT[5];p ersons[0] =new Stu Dent ("Tom", 1,88,45);p ersons[1] =new Student ("Jack", 6,80,12);p ersons[2] =new Student ("Bill", 4,68,21);p ersons[3] =new Student ("Kandy", 2,98,34);p ersons[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 into the Arrays.sort (Persons,sortbynumber) method Sortbynumber Sortbynumber = new Sortbynumber (); Arrays.sort (Persons,sortbynuMber); System.out.println ("Sort from low to high according to student number:"); for (Student student:persons) {System.out.println (Student);} Sortbyscore Sortbyscore = new Sortbyscore (); Arrays.sort (Persons,sortbyscore); System.out.println ("rank from highest to lowest according to student grades:"); 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 num Ber,int Score,int age) {this.name = Name;this.number = Number;this.score = Score;this.age = age;} Override the ToString () method of the Student class to output @overridepublic String ToString () {return "Student[name:" +name+ ", Age:" +age when you enter an object in the following manner + ", 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.) {this.age = AGe;}} Follow the number from low to high, create the Sortbynumber class, which implements the Comparator, overriding the interface's compare () class Sortbynumber implements Comparator<student >{//overrides the interface's compare () so that it is sorted by the number from small to large (the former minus the latter) @Overridepublic int compare (Student O1, Student O2) {return o1.getnumber ()- O2.getnumber ();}} The Sortbyscore class is created according to the score from high to low, and the class implements Comparator, overriding the interface's compare () class Sortbyscore implements comparator<student>{ Override the interface's compare () so that it sorts by fractions from high to low (the latter minus the former) @Overridepublic int compare (Student O1, Student O2) {return O2.getscore ()- O1.getscore ();}}
Operation Result:




Arrays.sort () in Java uses two methods (comparable and comparator interfaces) to sort objects or references

Related Article

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.