← Back to Chapters

Comparable vs Comparator

⚖️ Comparable vs Comparator

? Quick Overview

In Advance Java, Comparable and Comparator are used to define custom sorting logic for objects. They help Java collections like Collections.sort() and TreeSet decide how objects should be ordered.

? Key Concepts

  • Comparable defines natural ordering inside the class itself
  • Comparator defines external ordering outside the class
  • Both are part of java.util package
  • Used mainly with Collections and sorting algorithms

? Syntax / Theory

  • ComparablecompareTo(Object o)
  • Comparatorcompare(Object o1, Object o2)
  • Comparable supports only one sorting logic
  • Comparator supports multiple sorting strategies

? Code Example — Comparable

? View Code Example
// Student class implementing Comparable
class Student implements Comparable {
int id;
String name;

Student(int id, String name) {
this.id = id;
this.name = name;
}

public int compareTo(Student s) {
// Sort students by id in ascending order
return this.id - s.id;
}
}

? Code Example — Comparator

? View Code Example
// Comparator to sort students by name
import java.util.Comparator;

class NameComparator implements Comparator {
public int compare(Student s1, Student s2) {
// Compare student names alphabetically
return s1.name.compareTo(s2.name);
}
}

? Sorting Simulator

Click the buttons to see how the list changes based on logic.

 

? Live Output / Explanation

What Happens?

  • Using Comparable sorts students by id
  • Using Comparator sorts students by name
  • Comparator does not modify the Student class

✅ Tips & Best Practices

  • Use Comparable when there is a single natural order
  • Use Comparator for flexible or multiple sorting rules
  • Avoid complex logic inside compareTo()
  • Prefer Comparator in real-world applications

? Try It Yourself

  • Create a Comparator to sort students by name length
  • Sort in descending order using Comparator
  • Use Lambda expression with Comparator