Sobes.tech
Junior — Middle

Можете объяснить, что означает интерфейс Comparable в Java и какую роль он играет при сравнении объектов?

sobes.tech AI

Answer from AI

The Comparable interface in Java defines the compareTo() method, which allows objects to be compared to each other for ordering.

It plays a key role in sorting and searching, as it allows defining the natural order of objects. The compareTo() method 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.

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

Here, Person objects are compared by age, which allows, for example, sorting a list of people by age.