Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.

Comparable Interface

Adds sorting support for Lists that contain non-primitive types, that is, Lists of user-defined types. Your implementation must explicitly handle null inputs in the compareTo() method to avoid a null pointer exception.

Namespace

System

Usage

To add List sorting support for your Apex class, you must implement the Comparable interface with its compareTo method in your class.

To implement the Comparable interface, you must first declare a class with the implements keyword as follows:
Next, your class must provide an implementation for the following method:

The implemented method must be declared as global or public.

Comparable Methods

The following are methods for Comparable.

compareTo(objectToCompareTo)

Returns an Integer value that is the result of the comparison.

Signature

public Integer compareTo(Object objectToCompareTo)

Parameters

  • objectToCompareTo:

    Type: Object

Return Value

Type: Integer

Usage

The implementation of this method returns the following values:

  • 0 if this instance and objectToCompareTo are equal
  • > 0 if this instance is greater than objectToCompareTo
  • < 0 if this instance is less than objectToCompareTo

If this object instance and objectToCompareTo are incompatible, a System.TypeException is thrown.

Comparable Example Implementation

This example implements the Comparable interface. The compareTo method in this example compares the employee of this class instance with the employee passed in the argument. The method returns an Integer value based on the comparison of the employee IDs.
This example tests the sort order of a list of Employee objects.