Skip to main content

Command Palette

Search for a command to run...

Comparable Part-1

Updated
β€’5 min read

Comparable :

When we work with objects in Java, sometimes we want to sort them.

For example :

  • Sort employees by salary

  • Sort students by marks

Java does not know how to compare custom objects automatically.
This is where Comparable comes in.

What is Comparable?

Comparable is an interface present in the java.lang package.

public interface Comparable<T> {
    int compareTo(T o);
}

If a class implements Comparable, it means objects of that class can be compared with each other.

Why Comparable is Needed?

Java can easily sort primitive values like:

  • int

  • double

  • String

But for user-defined classes, Java needs rules to decide:

  • Which object comes first

  • Which object comes later

Comparable provides natural ordering for objects.

Return values of compareTo() :

  • Negative value β†’ current object is smaller

  • Zero β†’ both objects are equal

  • Positive value β†’ current object is bigger

When Should Use Comparable?

Use Comparable when:

  • Only one sorting logic is required

  • Sorting is a default behaviour of the class

  • Example: Employee sorted by ID, Student by roll number

Sorting Car Objects By MileAge :

public class Car implements Comparable<Car>{
    String brand;
    String color;
    int mileAge;
    int numOfSeaters;

    public Car(String brand, String color, int mileAge, int numOfSeaters) {
        this.brand = brand;
        this.color = color;
        this.mileAge = mileAge;
        this.numOfSeaters = numOfSeaters;
    }
    @Override
    public int compareTo(Car o) {

        return this.mileAge-o.mileAge; // natural order (assinding order)
    }

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", Color='" + color + '\'' +
                ", mileAge=" + mileAge +
                ", numOfSeaters=" + numOfSeaters +
                '}';
    }
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class SortWithMileAge {

    public static void main(String[] args) {
        List<Car> cars= new ArrayList<Car>();
        cars.add(new Car("BMW", "RED",100,5));
        cars.add(new Car("MARUTI", "BLUE",80,3));
        cars.add(new Car("AUDI", "GREEN",60,7));
        cars.add(new Car("Toyota", "WHITE",120,4));
        Collections.sort(cars);
        cars.forEach(System.out::println);
    }
}

Key Points :

  • Car implements Comparable<Car>

    This tells Java:

    β€œCar objects can be compared with each other.”

    Without this, Collection.sort() will throw an error.

  • This constructor initialises each car with:

    • Brand

    • Color

    • Mileage

    • Number of seaters

  • Without toString() output would look like:

      Car@5a07e868
    

    With it, output is human-readable

  • compareTo() method compares car objects using their mileage to determine the sorting order.

  • Inside the main() Car objects are added to the list in an unsorted (random) order.

  • Collection.sort(cars)

    • Picks two car objects

    • Calls compaeTo()

    • Decides order

    • Repeats until list is sorted

  • cars.forEach(System.out::println) This line iterates over the list and prints each Car object using the toString() method.

Initial List (Before Sorting)

Cars are added to the list in this order:

Index 0 β†’ BMW (mileAge = 100) Index 1 β†’ MARUTI (mileAge = 80) Index 2 β†’ AUDI (mileAge = 60) Index 3 β†’ Toyota (mileAge = 120)

Visual representation:

[ BMW(100) | MARUTI(80) | AUDI(60) | Toyota(120) ]

Sorting Trigger

Collections.sort(cars);
Java now starts comparing objects using:
this.mileAge - o.mileAge

πŸ” Step-by-Step Debugging (compareTo Calls)


πŸ”Ή Step 1: Compare Car1 & Car2

BMW vs MARUTI

100 - 80 = 20  (positive)

βœ” BMW is greater β†’ MARUTI comes first

[ MARUTI(80) | BMW(100) | AUDI(60) | Toyota(120) ]

πŸ”Ή Step 2: Compare BMW & AUDI

BMW vs AUDI

100 - 60 = 40  (positive)

βœ” BMW is greater β†’ AUDI moves before BMW

[ MARUTI(80) | AUDI(60) | BMW(100) | Toyota(120) ]

πŸ”Ή Step 3: Compare BMW & Toyota

BMW vs Toyota

100 - 120 = -20  (negative)

βœ” BMW is smaller β†’ no change

[ MARUTI(80) | AUDI(60) | BMW(100) | Toyota(120) ]

πŸ”Ή Step 4: Compare MARUTI & AUDI

MARUTI vs AUDI

80 - 60 = 20  (positive)

βœ” MARUTI is greater β†’ AUDI moves ahead

[ AUDI(60) | MARUTI(80) | BMW(100) | Toyota(120) ]

πŸ”Ή Step 5: Compare MARUTI & BMW

MARUTI vs BMW

80 - 100 = -20  (negative)

βœ” Correct order β†’ no change


πŸ”Ή Step 6: Compare BMW & Toyota

BMW vs Toyota

100 - 120 = -20  (negative)

βœ” Correct order β†’ no change


βœ… Final Sorted List (Ascending Mileage)

[ AUDI(60) | MARUTI(80) | BMW(100) | Toyota(120) ]

πŸ“Š Sorting Flow Diagram

Unsorted List
------------------------------------------------
BMW(100) β†’ MARUTI(80) β†’ AUDI(60) β†’ Toyota(120)

compareTo() calls
        ↓
Swapping based on mileAge
        ↓
Sorted List
------------------------------------------------
AUDI(60) β†’ MARUTI(80) β†’ BMW(100) β†’ Toyota(120)

βœ… Output :

Car{brand='AUDI', Color='GREEN', mileAge=60, numOfSeaters=7}
Car{brand='MARUTI', Color='BLUE', mileAge=80, numOfSeaters=3}
Car{brand='BMW', Color='RED', mileAge=100, numOfSeaters=5}
Car{brand='Toyota', Color='WHITE', mileAge=120, numOfSeaters=4}

🧠 Key Debugging Notes

  • Collections.sort() automatically calls compareTo()

  • Objects are compared pair by pair

  • Sorting stops when no more swaps are needed

  • You never call compareTo() manually


One-Line Summary

Java repeatedly calls compareTo() on Car objects until all cars are arranged in ascending mileage order.

Sort With Descending Order :

public class Car implements Comparable<Car>{
    String brand;
    String color;
    int mileAge;
    int numOfSeaters;

    public Car(String brand, String color, int mileAge, int numOfSeaters) {
        this.brand = brand;
        this.color = color;
        this.mileAge = mileAge;
        this.numOfSeaters = numOfSeaters;
    }
    @Override
    public int compareTo(Car o) {

        return o.mileAge-this.mileAge;  //(descending  order)
    }

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", Color='" + color + '\'' +
                ", mileAge=" + mileAge +
                ", numOfSeaters=" + numOfSeaters +
                '}';
    }
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class SortWithMileAge{

    public static void main(String[] args) {
        List<Car> cars= new ArrayList<Car>();
        cars.add(new Car("BMW", "RED",100,5));
        cars.add(new Car("MARUTI", "BLUE",80,3));
        cars.add(new Car("AUDI", "GREEN",60,7));
        cars.add(new Car("Toyota", "WHITE",120,4));
        Collections.sort(cars);
        cars.forEach(System.out::println);
    }
}

Output :

Car{brand='Toyota', Color='WHITE', mileAge=120, numOfSeaters=4}
Car{brand='BMW', Color='RED', mileAge=100, numOfSeaters=5}
Car{brand='MARUTI', Color='BLUE', mileAge=80, numOfSeaters=3}
Car{brand='AUDI', Color='GREEN', mileAge=60, numOfSeaters=7}
o.mileAge-this.mileAge;

o.mileAge - this.mileAge

In this expression, we subtract the mileage of the current Car object from the mileage of the other Car object.

By reversing the subtraction order, cars with higher mileage values come before cars with lower mileage values.

As a result, the Car objects are sorted in descending order of mileage.

Using o.mileAge - this.mileAge sorts the Car objects by mileage from highest to lowest

Sorting Car Objects By Color Using Comparable in Java

Sorting

Part 2 of 3

Sorting helps us arrange data in a particular order, like ascending or descending, which makes searching and analysing data easier. In Java, sorting can be done in multiple ways: using arrays, lists, or collections.

Up next

Comparable Part-2

Earlier, we learned how to sort the Car class by mileAge.In this article, we will focus on sorting cars by their color, helping us understand how Comparable works with String values. If you haven’t read it yet, you can check it out here:πŸ‘‰ Sorting C...