Sub topic 13
Implementing system interfaces: Comparable
This chapter assumes you can write an Apex class with fields and methods, that you know what an interface is and how implements works, and that you are comfortable with List and casting. It covers one system interface, Comparable, and shows how it controls the order of custom objects.
What a system interface is
A system interface is an interface that Salesforce defines and that platform code calls for you. You write the class, declare implements, and supply the required methods. The platform then calls your methods at the right moment.
Comparable is one of these. Its only method is compareTo(Object other). The List.sort() method calls it to decide which of two elements comes first.
Without Comparable, List.sort() cannot order a list of your own objects. At runtime, it throws a System.InvalidParameterValueException if the elements are custom class instances that don't implement the interface.
The compareTo contract
compareTo returns an Integer. The sign of the result is what matters:
| Return value | Meaning |
|---|---|
| Negative number | This object sorts before `other` |
| Zero | The two objects are equal for sorting |
| Positive number | This object sorts after `other` |
The parameter type is Object, because Comparable is not generic. You must cast it to your class before reading its fields.
A worked example
This Employee class sorts by salary, from lowest to highest.
public class Employee implements Comparable {
public String name;
public Decimal salary;
public Employee(String name, Decimal salary) {
this.name = name;
this.salary = salary;
}
public Integer compareTo(Object other) {
Employee o = (Employee) other;
if (salary == o.salary) {
return 0;
}
return salary > o.salary ? 1 : -1;
}
}
// Usage
List<Employee> staff = new List<Employee>{
new Employee('Ana', 5000),
new Employee('Bo', 3000)
};
staff.sort();
System.debug(staff[0].name); // BoThe method is public, because interface methods are implemented as public. The class declares implements Comparable, so the compiler checks that compareTo exists with the right signature.
How the sort uses your code
You never call compareTo yourself. The sort does it, possibly many times, so keep the method fast and free of side effects.
Common errors
- Casting the wrong type.
(Employee) otherthrows aSystem.TypeExceptionif the list holds mixed types. Keep lists of sortable objects uniform. - Null handling. If
otherisnull, readingo.salarythrows aSystem.NullPointerException. Check fornullif your list can contain nulls. - Inconsistent results. If
a.compareTo(b)is positive, thenb.compareTo(a)should be negative. Breaking this gives unpredictable order. - Reversed order. To sort from highest to lowest, flip the signs. Don't sort and then reverse by hand.
- Comparing
Decimalwith-. Subtracting two decimals gives aDecimal, not anInteger. Return1,-1, or0explicitly, as the example does.
Design note
Implementing Comparable gives each class one natural order. If you need several orderings, such as by name in one place and by salary in another, Apex also provides the System.Comparator interface, whose compare method lives in a separate class. Use Comparable when one order is obvious and Comparator when callers need to choose.
Exercise
A class Invoice has an Decimal amount field and implements Comparable. Write the body of compareTo so that invoices.sort() orders invoices from the largest amount to the smallest.
Show answer
Cast the argument and flip the comparison: Integer compareTo(Object other) { Invoice o = (Invoice) other; if (amount == o.amount) { return 0; } return amount > o.amount ? -1 : 1; } A larger amount returns -1, so it sorts earlier in the list.