WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Collections · Advanced · question 43 of 100

How does the Comparable interface work in Java Collections, and how do you implement it?

📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

The Comparable interface is used to provide a natural ordering of objects. It defines a single method compareTo() which compares the current object with the specified object and returns an integer value based on their relative order.

The compareTo() method returns a negative integer if the current object is less than the specified object, zero if they are equal, and a positive integer if the current object is greater than the specified object.

To use the Comparable interface, a class must implement it and provide its own implementation of the compareTo() method. For example, let’s consider a Person class with name and age fields:

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

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public int compareTo(Person other) {
        return this.name.compareTo(other.getName());
    }
}

In this example, we are implementing the Comparable interface and providing a custom implementation of the compareTo() method. We are using the compareTo() method of the String class to compare the name fields of two Person objects.

Now, we can use this implementation to sort a collection of Person objects:

List<Person> persons = new ArrayList<>();
persons.add(new Person("John", 30));
persons.add(new Person("Mary", 25));
persons.add(new Person("Peter", 35));

Collections.sort(persons);

for (Person person : persons) {
    System.out.println(person.getName() + " " + person.getAge());
}

In this example, we are using the Collections.sort() method to sort a list of Person objects based on their names, which are compared using the compareTo() method implemented in the Person class.

In summary, the Comparable interface is used to provide a natural ordering of objects, and its compareTo() method must be implemented to define how objects are compared. By implementing the Comparable interface, we can sort collections of objects based on their natural order.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview — then scores it.
📞 Practice Java Collections — free 15 min
📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

All 100 Java Collections questions · All topics