Sobes.tech
Junior — Middle

What is the main purpose of the Comparable interface in Java and when is its use justified?

sobes.tech AI

Answer from AI

The Comparable interface in Java defines the natural order of objects of a class that implements this interface. Its main method is compareTo(T o), which compares the current object with another and returns:

  • a negative number if the current object is less than the other,
  • zero if the objects are equal,
  • a positive number if the current object is greater than the other.

Using Comparable is justified when you need to determine the sorting order of objects of the same class, for example, for sorting lists with Collections.sort() or when using data structures that require comparison (e.g., TreeSet).

Example:

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

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

    @Override
    public int compareTo(Person other) {
        return Integer.compare(this.age, other.age); // sorting by age
    }
}

In this example, Person objects will be ordered by age.