Sobes.tech
Middle

What is the Comparable interface and how is it used?

sobes.tech AI

Answer from AI

The Comparable interface in Java is used to define the natural ordering of objects of a class. It contains the method compareTo(T o), which compares the current object with the object o and returns:

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

This allows sorting collections of objects, for example, using Collections.sort().

Example of usage:

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
    }
}

// Usage:
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
Collections.sort(people); // will sort by age