Newer Version Available
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
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:
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.