Comparator vs Comparable in java

Comparator vs Comparable in java

Comparable Interface:

The `Comparable` interface is used to establish the natural ordering of objects within a class. By implementing `Comparable`, a class defines how its instances should be compared to each other.

Comparator vs Comparable in java

Explanation:

  • The `Comparable` interface is found in the `java.lang` package.
  • It contains a single method, `compareTo()`, which compares the current object with another object of the same type.
  • The `compareTo()` method returns:
  • Negative integer if the current object is less than the other object.
  • Zero if the current object is equal to the other object.
  • Positive integer if the current object is greater than the other object.

Example:

Suppose we have a class `Person` representing individuals, and we want to sort instances of `Person` based on their age.

Syntax
```java
import java.util.*;

class Person implements Comparable<Person> {
    private String name;
    private int age;

    // Constructor and other methods

    @Override
    public int compareTo(Person other) {
        return this.age - other.age;
    }

    // Getter and setter methods
}
```

Comparator Interface:

The `Comparator` interface is used to define custom ordering of objects that may not have a natural ordering. It allows sorting objects based on criteria external to the objects themselves.

Explanation:

  • The `Comparator` interface is also found in the `java.util` package.
  • It contains a single method, `compare()`, which compares two objects of the same type.
  • The `compare()` method returns:
  • Negative integer if the first object is less than the second object.
  • Zero if the first object is equal to the second object.
  • Positive integer if the first object is greater than the second object.

Example:

Suppose we have a class `Student` representing students, and we want to sort instances of `Student` based on their names.

Syntax
```java
import java.util.*;

class Student {
    private String name;
    private int id;

    // Constructor and other methods

    // Getter and setter methods

    // Comparator for sorting by name
    public static Comparator<Student> NameComparator = new Comparator<Student>() {
        @Override
        public int compare(Student s1, Student s2) {
            return s1.getName().compareTo(s2.getName());
        }
    };
}
```

Comparable Usage
```java
public class ComparableExample {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 25));
        people.add(new Person("Bob", 20));
        people.add(new Person("Charlie", 30));

        Collections.sort(people); // Sorts by age
        System.out.println("Sorted by age: " + people);
    }
}
```

Comparator Usage
```java
public class ComparatorExample {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("Alice", 101));
        students.add(new Student("Bob", 102));
        students.add(new Student("Charlie", 103));

        Collections.sort(students, Student.NameComparator); // Sorts by name
        System.out.println("Sorted by name: " + students);
    }
}
```

In summary, `Comparable` is used to define the natural ordering of objects within a class, while `Comparator` is used to define custom ordering of objects externally. Both interfaces allow for flexible and customizable sorting of objects in Java.