Detailed explanation of the difference between java compare compareTo methods

  • 2021-11-14 05:42:39
  • OfStack

1. The compareTo (Object o) method is java. lang. Comparable < T > Interface, when you need to sort objects of a class, the class needs to implement Comparable < T > Interface, you must override the public int compareTo (T o) methods, such as those handled by the Map and Reduce functions in MapReduce < key,value > In which the key-value pairs need to be sorted according to key, so key implements WritableComparable < T > Interface, which can be used for both serialization and deserialization. WritableComparable < T > The interfaces (for serialization and deserialization) are the Writable interface and the Comparable interface < T > Combination of interfaces;

2. The compare (Object o1, Object o2) method is java. util. Comparator < T > Interface, which actually uses the compareTo (Object o) method of the object to be compared.

compareTo

The compareTo (Object o) method is java. lang. Comparable < T > Interface, when you need to sort objects of a class, the class needs to implement Comparable < T > Interface, you must override the public int compareTo (T o) method. It forcibly sorts the objects of each class that implements it as a whole-called natural sorting of the class. The list and array of objects that implement this interface can be sorted automatically with Collections. sort () and Arrays. sort (); That is to say, as long as the object (array) of this interface is implemented, it is equivalent to having the ability of sorting, so it is called comparable-sortable, so it can be said that this is an internal sorting method, by implementing its only 1 method compareTo (). For example, MapReduce, Map and Reduce functions in Hadoop < key,value > In which the key-value pairs need to be sorted according to key, so key implements WritableComparable < T > Interface, which can be used for both serialization and deserialization. WritableComparable < T > The interfaces (for serialization and deserialization) are the Writable interface and the Comparable < T > Combination of interfaces;

compare

The compare (Object o1, Object o2) method is java. util. Comparator < T > Interface, which actually uses the compareTo (Object o) method of the object to be compared. For it, it is aimed at some objects (arrays) that have no comparison ability, so it is called a comparator, which is an external thing. Through it, it defines the way of comparison, and then transmits it to Collection. sort () and Arrays. sort () to sort the targets, and through its own method compare (), it defines the content of comparison and the ascending and descending order of the results;

Let's write 1 to see how the above two methods are used:

First, write an User class with the following code:


public class User implements Comparable<Object>{
    int id;
    String name;
 
    public User(int id,String name){
        this.id = id;
        this.name = name;
    }
    /*
     * Getters and Setters
    */
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
 
    @Override
    public int compareTo(Object o) {
        if(this ==o){
            return 0;            
        }
        else if (o!=null && o instanceof User) {   
            User u = (User) o; 
            if(id<=u.id){
                return -1;
            }else{
            return 1;
        }
    }else{
        return -1;
    }
}
}

Next, we write a test class Test:


public class Test{
    // Write Comparator, According to User Adj. id Right User Sort 
    private static final Comparator<User> COMPARATOR = new Comparator<User>() {
       public int compare(User o1, User o2) {
           return o1.compareTo(o2);// Utilize User Class compareTo Method compares two objects        
      }
   };
 
    public static void main(String[] args) {
        ArrayList<User> student = new ArrayList<User>();
        User user1 = new User(1,"yueliming");
        User user2 = new User(2,"yueliming");
 
        Collections.sort(student, COMPARATOR);// Use what we wrote Comparator Right student Sort 
        for(int i=0;i<student.size();i++){
            System.out.println(student.get(i).getId());
        }
    }
}

Summary: Comparable < Object > Is an interface with a sort method compareTo (Object o) {}, and for an object to be sortable, the object must implement this interface, because the sort between two objects, the comparison method called by the call, is the compareTo () method.

Comparator < T > Interface, is an interface, inside the method is compare (o1, o2) it can be o1, o2 sort, in which you can call o1 object compareTo method sort.


Related articles: