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

Android 不負責任系列 - Jetpack 組件、MVVM 架構,簡稱 AAC、整潔架構(Clean Architecture) 的領域層(Domain Layer) UseCase 介紹

Android 不負責任系列 - Jetpack 組件、MVVM 架構,簡稱 AAC、整潔架構(Clean Architecture) 的領域層(Domain Layer) UseCase 介紹

BootStrap5 第二章 - 排版(格線系統 )

BootStrap5 第二章 - 排版(格線系統 )

D20_數字位數加總、判斷等比數列

D20_數字位數加總、判斷等比數列


Comments