When a collection or array that needs to be sorted is not a purely numeric type, you can usually use comparator or comparable to implement object sorting or custom sorting in a simple way. The following two examples are used to sort the age of the user object using comparable and comparator respectively.
1. By implementing the comparable interface, sort according to the age of the user.
import java.util.arrays;/** * @author pengcqu * */public class comparableuser implements comparable {private string id;private int age; Public comparableuser (string id, int age) {this.id = id;this.age = age;} Public int getage () {return age;} Public void setage (Int age) {this.age = age;} Public string getid () {return id;} Public void setid (String id) {this.id = id;} Public int compareto (Object o) {return this.age - ((comparableuser) o) . Getage ();} /** * test Method */public static void main (String[] args) {ComparableUser[] users = new comparableuser[] {new comparableuser ("u1001", 25),new Comparableuser ("u1002", 20), New comparableuser ("u1003", 21) }; Arrays.sort (Users);for (int i = 0; i < users.length; i++) { comparableuser user = users[i]; System.out.println (User.getid () + " " + user.getage ());}}
2. By implementing the comparator interface, sort according to the age of the user.
public class User {private string id;private int age;public user (String ID, int.) {this.id = Id;this.age = age;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public String GetId () {return ID;} public void SetId (String id) {this.id = id;}}
import java.util.arrays;import java.util.comparator;/** * @author pengcqu * */public class Usercomparator implements comparator {public int compare (Object arg0, OBJECT&NBSP;ARG1) {return (user) arg0. Getage () - ((user) arg1). Getage (); /** * test Method */public static void main (String[] args) {User[] users = new user[] { new user ("u1001", 25), New user ("u1002", 20), new user ("u1003", 21) }; Arrays.sort (Users, new usercomparator ());for (int i = 0; i < users.length; i++) {User user = users[i]; System.out.println (User.getid () + " " + user.getage ());}}
Select comparable interface or comparator?
A class that implements the comparable interface indicates that objects of this class can be compared to each other, and that a collection of such objects can be sorted directly using the Sort method.
Comparator can be regarded as an algorithm implementation, the algorithm and data separation, comparator can also be used in the following two kinds of environments:
1, the designer of the class did not consider the comparison problem and did not implement comparable, can be comparator to achieve the sort without having to change the object itself
2, can use a variety of sorting standards, such as ascending, descending and so on.
Comparable and comparator implementation object comparisons in Java