java object sorting (Comparable and Comparator)

1. Introduction to Comparable

Comparable is the sorting interface. If a class implements the Comparable interface, it means that the class supports sorting. Lists or arrays of objects of classes that implement the Comparable interface can be automatically sorted by Collections.sort or Arrays.sort . Additionally, objects implementing this interface can be used as keys in sorted maps or as sets in sorted sets without specifying a comparator. The interface is defined as follows:

public class Field implements Comparable<Field> {

    private String name;
    private int age;

    public Field(String name,int age){
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int compareTo(Field o) {
        //先比较age
        if(this.age > o.age){
            return this.age - o.age;
        }
        if(this.age < o.age){
            return this.age - o.age;
        }
        //再根据name进行比较
        if(this.name.compareTo(o.name) > 0){
            return 1;
        }
        if(this.name.compareTo(o.name) < 0){
            return -1;
        }

        return 0;
    }
}

test class

public class ComparableTest {

    public static void main(String[] args){
        Field field1 = new Field("field1",18);
        Field field2 = new Field("field2",18);
        Field field3 = new Field("field3",23);
        Field field4 = new Field("field4",16);

        List<Field> list = Lists.newArrayList();
        list.add(field1);
        list.add(field2);
        list.add(field3);
        list.add(field4);
        //排序
        Collections.sort(list);

        for(Field field : list){
            System.out.println(field.getName()+" =="+field.getAge());
        }
    }
}

output result

Enter image description

2. Introduction to Comparator

Comparator is a comparison interface. If we need to control the order of a 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, this "comparison" "Comparator" only needs to implement the Comparator interface . That is to say, we can create a new comparator by implementing Comparator, and then sort by this comparator. The interface is defined as follows:

public class Person {

    private String name;
    private int age;

    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

The Person class above does not implement the Comparable interface. How to compare the size? We can create a new class and let it implement the Comparator interface to construct a "comparator".

If a class wants to implement the Comparator interface: it must implement the compare(T o1, T 02) function , but it may not implement the equals(Object obj) function.

int compare(T o1,T o2) is "compare the size of o1 and o2". Returns "negative", meaning "o1 is less than o2" ; returns "zero", meaning "o1 is equal to o2" ; returns "positive", meaning "o1 is greater than o2" .

We create a new class and let it implement the Comparator interface to construct a "comparator".

public class PersonComparator implements Comparator<Person> {

    @Override
    public int compare(Person t1, Person t2) {
        //先比较age
        if(t1.getAge() > t2.getAge()){
            return t1.getAge() - t2.getAge();
        }
        if(t1.getAge() < t2.getAge()){
            return t1.getAge() - t2.getAge();
        }
        //再根据name进行比较
        if(t1.getName().compareTo(t2.getName()) > 0){
            return 1;
        }
        if(t1.getName().compareTo(t2.getName()) < 0){
            return -1;
        }
        return 0;
    }

}

test class

public class ComparableTest {

    public static void main(String[] args){
        Person person1 = new Person("person1",18);
        Person person2 = new Person("person2",18);
        Person person3 = new Person("person3",23);
        Person person4 = new Person("person4",16);

        List<Person> list = Lists.newArrayList();
        list.add(person1);
        list.add(person2);
        list.add(person3);
        list.add(person4);
        //排序
        Collections.sort(list,new PersonComparator());

        for(Person person : list){
            System.out.println(person.getName()+" =="+person.getAge());
        }
    }
}

Program running result Enter image description

3. Comparison of Comparable and Comparator The two methods have their own advantages and disadvantages. Using Comparable is simple. As long as the object that implements the Comparable interface directly becomes a comparable object, it needs to modify the source code. The advantage of using Comparator is that there is no need to modify the source code, but to implement a comparator. When a custom object needs to be compared, the comparator and the object can be passed together to compare the size, and in the Comparator Users can implement complex and general logic to match some simpler objects, which can save a lot of repetitive work .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326004222&siteId=291194637