Comparable Part-1
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@5a07e868With 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 callscompareTo()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
Carobjects are sorted in descending order of mileage.Using
o.mileAge - this.mileAgesorts theCarobjects by mileage from highest to lowest