Java uses the Comparator and Comparable interfaces to sort objects.

Source: Internet
Author: User
Tags comparable

Java uses the Comparator and Comparable interfaces to sort objects.

In programming, you may often sort an object array. Objects often have multiple attributes. Generally, objects are sorted by a specific attribute value, there are many ways to sort by one of the attributes. The most direct one is to directly use an attribute value in the object for comparison when writing the sorting algorithm.

The sort method is provided in the java array. If we want to sort a common integer array a, we can directly write Arrars. sort (a), and the output array is the sorted array. The default sorting method is ascending. Java should be able to judge the integer size. Therefore, we do not need to process the parameters of the sort function or the array. However, if you want to sort an array of objects, the system does not know how to compare the sizes of these two objects, therefore, we need to define a comparison function in the class for the sort sorting function to compare the size of objects. Therefore, you need to use the Comparator or Comparable interface.

The most intuitive difference between Comparator and Comparable is that Comparator needs to input two objects as parameters and add a class. The Comparable parameter only needs one object and directly adds the code of the comparison module to the class.

Comparator:

// If o1 is less than, equal to, or greater than o2, negative integer, zero, or positive integer is returned. Int compare (Object o1, Object o2 );
Sample Code:

Import java. util. *; class Student {private String stuNum; private int score; public Student (String stuNum, int score) {this. stuNum = stuNum; this. score = score;} public int getScore () {return score;} public String toString () {return "student ID:" + this. stuNum + "score:" + this. score ;}} class stuCompare implements Comparator {// define the class implementation interface public int compare (Object a, Object B) {return (Student) ). getScore ()-(Student) B ). getScore () ;}} public class example1 {public static void main (String [] args) {final int MAX = 10; Student [] stuArray = new Student [MAX]; for (int I = 0; I <MAX; I ++) {stuArray [I] = new Student (String. valueOf (I), (int) (Math. random () * 100);} System. out. println ("Raw data"); for (Student t: stuArray) {System. out. println (t);} // the following line will give a warning as shown in the following figure during compilation. I do not know how to handle it yet. I hope you can give me some advice on Arrays. sort (stuArray, new stuCompare (); // transmits arrays and objects containing comparison functions at the same time: System. out. println ("sorted data"); for (Student t: stuArray) {System. out. println (t );}}}
Warning:

Comparable: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + PC9wPgo8cHJlIGNsYXNzPQ = "brush: java;"> // if the object is less than, equal to, or greater than the specified object o, negative integers, zero, or positive integers are returned respectively. Int compareTo (Object o );
Sample Code:

Import java. util. *; class Student implements Comparable {// note the difference between private String stuNum; private int score; public Student (String stuNum, int score) {this. stuNum = stuNum; this. score = score;} public int getScore () {return score;} public int compareTo (Object a) {// Add a comparison function return this to the class. score-(Student) ). score;} public String toString () {return "student ID:" + this. stuNum + "score:" + this. score ;}} public class example1 {public static void main (String [] args) {final int MAX = 10; Student [] stuArray = new Student [MAX]; for (int I = 0; I <MAX; I ++) {stuArray [I] = new Student (String. valueOf (I), (int) (Math. random () * 100);} System. out. println ("Raw data"); for (Student t: stuArray) {System. out. println (t);} Arrays. sort (stuArray); // only the Array System is input during sorting. out. println ("sorted data"); for (Student t: stuArray) {System. out. println (t );}}}
Of course, if we write the sorting function by ourselves, we don't need to consider that much. We can simply write the relevant attributes in the sorting algorithm to sort objects. The following uses Bubble sorting to sort objects:

Sample Code:

Import java. util. *; class Student {private String stuNum; private int score; public Student (String stuNum, int score) {this. stuNum = stuNum; this. score = score;} public int getScore () {return score;} public String toString () {return "student ID:" + this. stuNum + "score:" + this. score ;}} public class example1 {public static void main (String [] args) {final int MAX = 10; Student [] stuArray = new Student [MAX]; for (int I = 0; I <MAX; I ++) {stuArray [I] = new Student (String. valueOf (I), (int) (Math. random () * 100);} System. out. println ("Raw data"); for (Student t: stuArray) {System. out. println (t) ;}for (int I = 0; I <MAX-1; I ++) {for (int j = 0; j <MAX-I-1; j ++) {if (stuArray [j]. getScore ()> stuArray [j + 1]. getScore () {Student temp = stuArray [j]; stuArray [j] = stuArray [j + 1]; stuArray [j + 1] = temp ;}} System. out. println ("sorted data"); for (Student t: stuArray) {System. out. println (t );}}}

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.