Comparable and Comparator for Object Size Contrast

Posted by Rupo on Sat, 15 Jun 2019 01:44:53 +0200

A Summary

1. Background of Comparable and Comparator

Numeric data (byte int short long float double) is naturally comparable and sortable. String implements Comparable interface and can also compare size and sorting. There are many kinds of custom classes, and there is no common index for sorting. Therefore, it is necessary to establish a method of comparison manually in custom classes. For this purpose, java provides two interfaces, Comparable and Comparable. Comparator.

2. Set Sorting

The underlying sorting of Collections.sort() relies on Arrays.sort(), while Arrays.sort() is sorted by bubbling method.

Two Comparable

Objects that need to be compared can implement the Comparable interface and the abstract method, which is used to set the way of comparison. Following is an example to illustrate:

1. Entity class

package com.javase.collections.comparable;

public class Student implements Comparable<Student> {

    private String name;
    private int score;

    public Student() {
        super();
    }

    public Student(String name, int score) {
        super();
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

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

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    @Override
    public int compareTo(Student stu) {
        return this.score - stu.score;// Operating objects subtract parameter objects, ascending and descending order.
    }

}

In the compareTo() method, the attribute score is used as the sorting index, and the "this.score-stu.score" is used. The final results are arranged in ascending order, whereas the descending order is used.

2. Test class

package com.javase.collections.comparable;

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

import org.junit.Test;

public class ComparableTest {

    @Test
    public void testComparable() {
        List<Student> stus = new ArrayList<Student>();
        Student zhangsan = new Student("zhangsan", 100);
        Student lisi = new Student("lisi", 90);
        Student wanger = new Student("wanger", 95);
        stus.add(zhangsan);
        stus.add(lisi);
        stus.add(wanger);
        System.out.println("Before sorting");
        for (Student x : stus) {
            System.out.println(x.getName() + "::" + x.getScore());
        }
        System.out.println("After sorting");
        Collections.sort(stus);
        for (Student x : stus) {
            System.out.println(x.getName() + "::" + x.getScore());
        }
    }

}

Output:

Three Comparator s

If a class does not implement the Comparable interface when it is created, it wants to sort its objects without modifying the source code. It can implement the Comparator comparator interface when calling the sorting method and specify the sorting method. Following is an example to illustrate:

1. Entity class

package com.javase.collections.comparator;

public class Student {
    private String name;
    private int score;

    public Student() {
        super();
    }

    public Student(String name, int score) {
        super();
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

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

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

}

2. Test class

package com.javase.collections.comparator;

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

import org.junit.Test;

public class ComparatorTest {

    @Test
    public void test() {
        List<Student> stus = new ArrayList<Student>();
        Student zhangsan = new Student("zhangsan", 100);
        Student lisi = new Student("lisi", 90);
        Student wanger = new Student("wanger", 95);
        stus.add(zhangsan);
        stus.add(lisi);
        stus.add(wanger);
        System.out.println("Before sorting");
        for (Student x : stus) {
            System.out.println(x.getName() + "::" + x.getScore());
        }
        System.out.println("-----------------------");
        Collections.sort(stus, new Comparator<Student>() {
            @Override
            public int compare(Student stu01, Student stu02) {
                // return stu01.getScore() - stu02.getScore();//Ascending order
                return stu02.getScore() - stu01.getScore();// Descending order
            }
        });

        System.out.println("After sorting");
        for (Student x : stus) {
            System.out.println(x.getName() + "::" + x.getScore());
        }
    }

}

In the comparison (Student stu01, Student stu02) method, the attribute score is used as the ranking index, and the "stu01.score-stu02.score" is adopted. The final results are arranged in ascending order, whereas the descending order.

Output:

 

Reference resources:

http://www.tiantianbianma.com/java-comparable-comparator.html/

Topics: Java Attribute Junit