Application of comparator and comparable in sorting
When the set or array to be sorted is not simply numeric, comparator or comparable can be used to sort objects or customize the sorting in a simple way.
I. Comparator
A comparison function that forcibly sorts a collection object. It can pass the comparator to collections. sort or arrays. sort.
Interface Method:
/*** @ Return O1 is less than, equal to, or greater than O2, and returns negative integer, zero, or positive integer respectively. */INT compare (Object O1, object O2 );
// Import Java. util. arrays; import Java. util. *; // import Java. util. comparator; class he {int X, Y;} class mycmp implements comparator <He >{/ * because the type <He> is specified above, you can directly (he, he B) * otherwise, it must be written as (Object A, object B), and then forcibly converted to the he type: (HE) ). x */Public int compare (He A, he B) {if (. x-B.x! = 0) return. A x-B.x; else return. y-B.y;} class sort1 {public static void main (string [] ARGs) {Summary In = new example (system. in); int N, I; n = in. nextint (); he d [] = new he [10]; for (I = 0; I <n; I ++) {d [I] = new he (); d [I]. X = in. nextint (); D [I]. y = in. nextint ();} arrays. sort (D, 0, N, new mycmp (); // Number of N rows, arrays. for sort (D, new mycmp (), all rows for (I = 0; I <n; I ++) {system. out. println (d [I]. X + "" + d [I]. Y );}}}
Ii. Comparable
Forcibly sorts the objects of each class. Objects (and arrays) of this interface can be automatically sorted by collections. sort or arrays. sort.
Interface Method:
/*** @ Return: if the object is less than, equal to, or greater than the specified object O, a negative integer, zero, or positive integer is returned. */INT compareto (Object O );
Import Java. util. *; import Java. util. arrays; class he implements comparable <He> {int X, Y;/* because the type <He> is specified above, you can directly (He) * Otherwise, object A must be written and then forcibly converted to the he type: (HE) ). x */Public int compareto (he a) {If (this. x-a.x! = 0) return this. A x-a.x; else return this. y-a.y;} class Hee {public static void main (string ARGs []) {supplied in = new supplied (system. in); int N, I; n = in. nextint (); he d [] = new he [10]; for (I = 0; I <n; I ++) {d [I] = new he (); d [I]. X = in. nextint (); D [I]. y = in. nextint ();} arrays. sort (D, 0, n); // Number of N rows, arrays. sort (d) then all for (I = 0; I <n; I ++) system by default. out. println (d [I]. X + "" + d [I]. Y );}}