Sub topic 13
Implementing system interfaces: Comparable
This chapter assumes you can write an Apex class, declare an interface, and use implements, as covered in the earlier chapters. It also assumes you know that List is an ordered collection. The goal is to use one system interface, Comparable, to control how List.sort() orders your own objects. The same pattern applies to other system interfaces.
What a system interface is
A system interface is an interface that Salesforce defines and the platform calls for you. You write the class, implement the methods, and the platform decides when to call them. You never call those methods yourself in normal use.
| Interface | You implement | The platform calls it when |
|---|---|---|
| `Comparable` | `compareTo(Object)` | `List.sort()` orders your objects |
| `Schedulable` | `execute(SchedulableContext)` | A scheduled job fires |
| `Queueable` | `execute(QueueableContext)` | `System.enqueueJob()` runs your job |
| `Database.Batchable<SObject>` | `start`, `execute`, `finish` | A batch job runs |
The rules are the same for all of them. The class declares implements InterfaceName, and each method must match the interface signature exactly. Each method must also be public or global, because interface methods cannot be private.
The Comparable contract
Comparable declares one method:
Integer compareTo(Object objectToCompareTo)The method compares the current object (this) with another object and returns an Integer that tells the sort which one comes first.
| Return value | Meaning |
|---|---|
| Negative number | `this` sorts before the other object |
| Zero | The two objects are equal for sorting purposes |
| Positive number | `this` sorts after the other object |
Only the sign matters. Returning -1, 0, and 1 is the usual convention.
The parameter type is Object, not your class. Apex needs one fixed signature that works for every class, so you must cast the argument to your own type inside the method.
A complete example
This version of Employee improves on the short one in the chapter plan. It handles a missing salary and breaks ties by name, so the same input always produces the same order.
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) {
if (other == null) {
return 1;
}
Employee o = (Employee) other;
// A null salary sorts before any real salary
if (salary == null && o.salary == null) {
return name.compareTo(o.name);
}
if (salary == null) {
return -1;
}
if (o.salary == null) {
return 1;
}
if (salary < o.salary) {
return -1;
}
if (salary > o.salary) {
return 1;
}
// Same salary: order by name
return name.compareTo(o.name);
}
}
// Usage
List<Employee> staff = new List<Employee>{
new Employee('Ana', 5000),
new Employee('Cy', 3000),
new Employee('Bo', 3000),
new Employee('Di', null)
};
staff.sort();
for (Employee e : staff) {
System.debug(e.name + ' ' + e.salary);
}
// Di null
// Bo 3000
// Cy 3000
// Ana 5000String.compareTo is a built-in method that follows the same negative, zero, positive convention, so it works well as a tie-breaker.
What happens during a sort
List.sort() does not know anything about Employee. It checks that the elements implement Comparable, then calls compareTo on pairs of elements until the list is in order.
Three details follow from this.
sort()changes the list in place and returns nothing.- The sort runs in ascending order. For a different order, change the sign logic or the fields you compare.
- You do not know how many times
compareTois called. Keep it fast and free of side effects, with no queries and no DML.
Sorting SObjects with a wrapper class
You cannot add implements Comparable to Opportunity or any other SObject. Standard sort() on a list of SObjects orders by a fixed set of rules you do not control. To sort by your own rule, wrap the record in a class that implements Comparable.
public class OpportunityWrapper implements Comparable {
public Opportunity record;
public OpportunityWrapper(Opportunity record) {
this.record = record;
}
// Largest amount first
public Integer compareTo(Object other) {
OpportunityWrapper o = (OpportunityWrapper) other;
Decimal mine = record.Amount == null ? 0 : record.Amount;
Decimal theirs = o.record.Amount == null ? 0 : o.record.Amount;
if (mine > theirs) {
return -1;
}
if (mine < theirs) {
return 1;
}
return 0;
}
}
// Usage
List<OpportunityWrapper> wrapped = new List<OpportunityWrapper>();
for (Opportunity opp : [SELECT Name, Amount FROM Opportunity LIMIT 200]) {
wrapped.add(new OpportunityWrapper(opp));
}
wrapped.sort();Here the signs are reversed on purpose. Returning -1 when this has the larger amount puts large amounts first. This is the simplest way to get descending order.
Common errors
| Problem | Cause | Fix |
|---|---|---|
| Compile error on the class | The method is not `public`, or its signature differs from `Integer compareTo(Object)` | Use exactly `public Integer compareTo(Object other)` |
| Runtime error when sorting | The class does not implement `Comparable`, or the list holds a mix of types | Implement the interface on every element type |
| `System.TypeException` inside `compareTo` | The cast `(Employee) other` fails because the other object is a different type | Check with `instanceof` if mixed lists are possible |
| `NullPointerException` | A field used in the comparison is `null`, or `other` is `null` | Decide where nulls sort and test for them first |
| Order changes between runs | Equal items are not tie-broken, so their relative order is not guaranteed | Add a secondary comparison such as name or Id |
Keeping compareTo consistent
A correct compareTo follows three rules.
- Antisymmetric. If
a.compareTo(b)is positive,b.compareTo(a)must be negative. - Transitive. If
asorts beforebandbsorts beforec, thenamust sort beforec. - Stable on equal data. The same two objects must always give the same result.
Violating these rules does not always raise an error. The sort may produce a list that looks sorted but is wrong in places, which is harder to debug than a crash.
When Comparable is the right choice
Comparable fits when a class has one natural ordering that you want in many places. If the same objects need different orderings in different features, a single compareTo forces awkward switching. In that case, wrap the objects as in the example above. Newer API versions also provide a System.Comparator interface, where the ordering lives in a separate class passed to sort(). Check your org's release notes before relying on it.
Exercise
A teammate writes public Integer compareTo(Employee other) in a class that declares implements Comparable. The class does not compile. What is wrong, and what is the fix?
Show answer
The interface requires the signature Integer compareTo(Object other). A method that takes Employee does not match it, so the class does not implement the interface. Change the parameter type to Object and cast inside the method: Employee o = (Employee) other;.
Exercise
You want List<Employee> sorted by salary from highest to lowest, with ties broken by name from A to Z. Which return values do you change in the salary comparison, and what stays the same?
Show answer
Reverse the salary logic: return 1 when salary < o.salary and -1 when salary > o.salary, so higher salaries sort first. Leave the final return name.compareTo(o.name); unchanged, because it already gives A to Z for equal salaries.
Exercise
Why can't you make Opportunity implement Comparable, and what do you do instead?
Show answer
Standard and custom SObject types are defined by the platform, so you cannot add implements to them. Create a wrapper class that holds the record, implements Comparable, and compares the fields you care about. Sort a list of wrappers, then read the records from them.