Can you sort a list of custom objects using Collections.sort() without providing a Comparator?

A list of custom objects can be sorted using Collections.sort() without supplying a Comparator only when the custom class implements the Comparable interface. Comparable defines the natural ordering of objects through the compareTo() method, allowing Java to determine how objects should be arranged during sorting.

Key Points:

• Collections.sort() relies on the natural ordering defined by the Comparable interface. • The custom class must override the compareTo() method to specify sorting logic. • If Comparable is not implemented and no Comparator is provided, sorting will fail at runtime. • Comparable is generally used for a default sorting order, while Comparator is used for multiple or custom sorting strategies. • Natural ordering should be consistent and meaningful for the object being sorted.

Example:

Suppose you have a list of Employee objects and want them sorted by employee ID by default. Implementing Comparable inside the Employee class allows Collections.sort() to sort the list automatically without requiring a separate Comparator.

Code Example:

import java.util.*;

class Employee implements Comparable<Employee> {

    private int id;
    private String name;

    public Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public int compareTo(Employee other) {
        return Integer.compare(this.id, other.id);
    }

    @Override
    public String toString() {
        return id + " - " + name;
    }
}

public class Main {
    public static void main(String[] args) {

        List<Employee> employees = new ArrayList<>();

        employees.add(new Employee(103, "John"));
        employees.add(new Employee(101, "Alice"));
        employees.add(new Employee(102, "Bob"));

        Collections.sort(employees);

        System.out.println(employees);
    }
}

Interview Tip:

A concise interview answer is: "Yes, Collections.sort() can sort custom objects without a Comparator if the class implements Comparable and provides the compareTo() method. This method defines the object's natural ordering. Otherwise, sorting will result in a runtime exception."