TIL: Comparable Interface

adamsteradam·2022년 9월 28일

public interface Comparable<T>

This interface imposes a total ordering on the objects of each class that implements it.

Comparable interface is used to order the objects of the user-defined class.
It has only one method named compareTo(Object). This method provides a single sorting sequence.

List of objects that implement this interface can be sorted automatically by Collections.sort(and Arrays.sort).
Can be also used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

Comparator: A comparison function, which imposes a total ordering on some collection of objects.

public int compareTo(Object obj)
(compare the current object with the specified object.)

  • if(current obj > specified obj) returns positive integer
  • if(current obj < specified obj) returns negative integer
  • if(current obj == specified obj) returns zero.

When to use?

Sorting for:
1. String objects
2. Wrapper class objects
3. User-defined class objects

Comparable Example

class Student implements Comparable<Student>{  
  int rollno;  
  String name;  
  int age;  
  Student(int rollno,String name,int age){  
  public int compareTo(Student st){  
      return 0;  
    else if(age>st.age)  
      return 1;  
      return -1;  
import java.util.*;  
public class TestSort{  
  public static void main(String args[]){  
  ArrayList<Student> al=new ArrayList<Student>();  
  al.add(new Student(3,"Adam",23));  
  al.add(new Student(2,"Jae",27));  
  al.add(new Student(1,"Su",21));  

    for(Student st:al){  
    System.out.println(st.rollno+" "+st.name+" "+st.age);  
1 Su 21
3 Adam 23
2 Jae 27

Depending on the sort order (reverse or forward), change the condition for comparing age statement. (ex: if(age > st.age) return 1)

0개의 댓글