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.
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.
See Also
The following are methods for Comparable.
-
Returns an Integer value that is the result of the comparison.
Returns an Integer value that is the result of the comparison.
public Integer compareTo(Object objectToCompareTo)
-
objectToCompareTo:
Type: Object
Type: Integer
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.
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.