Talking about the difference between Comparable and Comparator

I usually use the Comparable interface for custom sorting. After a period of time, I found that there is a Comparator interface.

There is some information on the Internet, so I will summarize and take notes.

The basic principle is comparison, the bottom layer is a binary tree

For example, 3,6,5,1,7,4,9

When sorting, put 3 first, and then 6 is bigger than 3. If the trouble is on the right side of 3, and 5 is smaller than 6, put it on the left. An analogy is the line and surface picture

First look at the interface definition of Comparable

package java.lang;
import java.util.*;
public interface Comparable<T> {
    public int compareTo(T o);
}
copy

Comparable sorts the objects of each class that implements it as a whole. This interface needs to be implemented by the class itself

Code example analysis

package com.list.customsort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestSort {
    public static void main(String[] args) {
        List<Person> list = new ArrayList<>();
        list.add(new Person("fd",20));
        list.add(new Person("chy",22));
        list.add(new Person("wgj",21));
        System.out.println(list);
        Collections.sort(list);
        System.out.println(list);
    }
}
class Person implements Comparable<Person>{
    private String name;
    private Integer age;
    public Person(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
    @Override
    public int compareTo(Person o) {
//        return this.getAge().compareTo(o.getAge());
        return this.getName().compareTo(o.getName());//Sort in ascending order by name.  abc
    }
}
copy

It is sorted according to the name attribute of the person Results:

If you don't use the Collections.sort() method, you can directly use the treeSet collection to operate

Set<Person> set = new TreeSet<>();
        set.add(new Person("fd",20));
        set.add(new Person("chy",22));
        set.add(new Person("wgj",21));
        System.out.println(set);
copy

The result is exactly the same as above, and the sorting is also realized according to the name

Why, look at the treeset source code and you will find that it is still the compareto method

So using Collections.sort(list) has the same effect as directly new TreeSet.

Comparator

Comparator is a comparison interface. If we need to control the order of a certain class, and the class itself does not support sorting (that is, it does not implement the Comparable interface), then we can create a "comparator of this class" to sort. device" only needs to implement the Comparator interface. In other words, we can create a new comparator by implementing Comparator, and then sort the classes through this comparator.

Interface definition

package java.util;
public interface Comparator<T> {
    int compare(T o1, T o2);
    boolean equals(Object obj);
}
copy

Code example analysis

package com.list.customsort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class TestSort2 {
    public static void main(String[] args) {
        List<Person2> list = new ArrayList<>();
        list.add(new Person2("fd",20));
        list.add(new Person2("chy",22));
        list.add(new Person2("wgj",21));
        System.out.println(list);
        Collections.sort(list,new Comparator<Person2>() {
            @Override
            public int compare(Person2 o1, Person2 o2) {
                return o1.getAge().compareTo(o2.getAge());
            }
        });
        System.out.println(list);
    }
}
class Person2{
    private String name;
    private Integer age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Person2(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person2 [name=" + name + ", age=" + age + "]";
    }
}
copy

The sort method of the main method can be simplified using lambda

(public static <T> void sort(List<T> list, Comparator<? super T> c) )

Collections.sort(list,(s1,s2)-> Integer.compare(s1.getAge(),s2.getAge()));
copy

At this time, if you use the treeset collection, it will have no effect.

Because it uses the compareTo method at the bottom.

The difference between Comparable and Comparator

Comparable is a sorting interface. If a class implements the Comparable interface, it means "this class supports sorting". The Comparator is a comparator. If we need to control the order of a certain class, we can create a "comparator of this class" to sort.

Comparable is equivalent to "internal comparator", and Comparator is equivalent to "external comparator".

The two methods have their own advantages and disadvantages. It is simple to use Comparable, as long as the object that implements the Comparable interface becomes a comparable object directly, but the source code needs to be modified. The advantage of using Comparator is that you don’t need to modify the source code, but implement a comparator separately. When a custom object needs to be compared, you can compare the size by passing the comparator and the object together, and in the Comparator Users can implement complex and general-purpose logic by themselves, so that they can match some relatively simple objects, which can save a lot of repetitive labor.

ok, in place! ! !

Posted by Possum on Tue, 29 Nov 2022 00:58:40 +1030