Java Comparator vs Comparable


Posted by Rich on 2022-06-23

Both are interface in Java.

Comparable

A comparable object is capable of comparing itself with another object. Comparable implements in the class that you want to sort.

public class Student implements Comparable<Student> {
    private String name;
    private int id;
    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
    @Override
    public int compareTo(Student s) {
        return this.name.compareTo(s.name);
    }
  }

We implement the Comparable interface, so we have to override the compareTo method.
The thing I was confused it's that in the compareTo method, we use another compareTo method. But the method we define takes in Student object as an input, but here it takes String.
It turns out that it's another compareTo method from the String class.

Comparator

We can only sort the instances using one condition if we use the comparable interface. That's why we need comparator if we have multiple conditions.

public class Student {
    private String name;
    private int id;
    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
  } 
public class SortStudentById implements Comparator<Student> {
        public int compare(Student s1, Student s2) {
        return s1.id - s2.id;
        // if it return a negative number it will move the first element forward.
        //return 0 means no changes in order.
        // return 1 means move the first element backward.
    }
 }









Related Posts

綜合示範:抓取資料並顯示

綜合示範:抓取資料並顯示

Is the End of Data Analysis Near? The Impact of Code Interpreter, the New Feature of GPT-4

Is the End of Data Analysis Near? The Impact of Code Interpreter, the New Feature of GPT-4

原型與繼承(1) - 建構式函式 & 閉包

原型與繼承(1) - 建構式函式 & 閉包


Comments