Posted on: January 18, 2025 Posted by: rahulgite Comments: 0

Comparable

  1. Definition:
    • Comparable is an interface in Java that is used to define the natural ordering of objects.
    • The class that needs to define the ordering implements the Comparable interface and overrides the compareTo() method.
  2. Key Features:
    • Affects the natural ordering of objects.
    • Only one compareTo() method is allowed per class.
  3. Method:
    • int compareTo(T o)
      • Returns a negative value if this object is less than the specified object.
      • Returns zero if this object is equal to the specified object.
      • Returns a positive value if this object is greater than the specified object.
  4. Use Case:
    • Use Comparable when a single, default ordering of objects is sufficient.
  5. Example:
class Student implements Comparable<Student> {
    private String name;
    private int age;

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

    @Override
    public int compareTo(Student other) {
        return this.age - other.age; // Natural ordering by age
    }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
            new Student("Alice", 22),
            new Student("Bob", 20),
            new Student("Charlie", 23)
        );

        Collections.sort(students);
        System.out.println(students); // Sorted by age
    }
}

//Output : [Bob (20), Alice (22), Charlie (23)]


Comparator

  1. Definition:
    • Comparator is an interface in Java used to define custom orderings for objects.
    • The class defining the ordering does not need to modify the compared class.
  2. Key Features:
    • Allows multiple comparison strategies.
    • Can be used to compare objects that do not implement Comparable.
  3. Method:
    • int compare(T o1, T o2)
      • Returns a negative value if o1 is less than o2.
      • Returns zero if o1 is equal to o2.
      • Returns a positive value if o1 is greater than o2.
  4. Use Case:
    • Use Comparator when multiple sorting strategies are required or when the class does not implement Comparable.
  5. Example:
class Student {
    private String name;
    private int age;

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

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
            new Student("Alice", 22),
            new Student("Bob", 20),
            new Student("Charlie", 23)
        );

        // Sort by name using Comparator
        students.sort(Comparator.comparing(student -> student.name));

        System.out.println("Sorted by name: " + students);

        // Sort by age using Comparator
        students.sort(Comparator.comparingInt(student -> student.age));

        System.out.println("Sorted by age: " + students);
    }
}

//Output 
Sorted by name: [Alice (22), Bob (20), Charlie (23)]
Sorted by age: [Bob (20), Alice (22), Charlie (23)]


Key Differences

AspectComparableComparator
Sorting SequenceProvides a single sorting sequence based on one element (e.g., id, name).Provides multiple sorting sequences based on multiple elements (e.g., id, name, price).
Class ModificationAffects the original class; the class must implement Comparable.Does not modify the original class; comparison logic can be in a separate class.
MethodUses compareTo() method for sorting.Uses compare() method for sorting.
PackagePresent in java.lang.Present in java.util.
Sorting MechanismCan be sorted using Collections.sort(List) directly.Requires Collections.sort(List, Comparator) for custom sorting logic.

Summary

  • Use Comparable when a class has a single, natural ordering.
  • Use Comparator when multiple custom orderings are required or when the compared class cannot be modified.

Leave a Comment