Newer Version Available
Comparable Interface
Adds sorting support for Lists that contain non-primitive
types, that is, Lists of user-defined types.
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:
1global class Employee implements Comparable {
Next, your class must provide an implementation for the following
method:
1global Integer compareTo(Object compareTo) {
2 // Your code here
3}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 is an example implementation of 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.
1global class Employee implements Comparable {
2
3 public Long id;
4 public String name;
5 public String phone;
6
7 // Constructor
8 public Employee(Long i, String n, String p) {
9 id = i;
10 name = n;
11 phone = p;
12 }
13
14 // Implement the compareTo() method
15 global Integer compareTo(Object compareTo) {
16 Employee compareToEmp = (Employee)compareTo;
17 if (id == compareToEmp.id) return 0;
18 if (id > compareToEmp.id) return 1;
19 return -1;
20 }
21}This example tests the sort order of a list of Employee objects.
1@isTest
2private class EmployeeSortingTest {
3 static testmethod void test1() {
4 List<Employee> empList = new List<Employee>();
5 empList.add(new Employee(101,'Joe Smith', '4155551212'));
6 empList.add(new Employee(101,'J. Smith', '4155551212'));
7 empList.add(new Employee(25,'Caragh Smith', '4155551000'));
8 empList.add(new Employee(105,'Mario Ruiz', '4155551099'));
9
10 // Sort using the custom compareTo() method
11 empList.sort();
12
13 // Write list contents to the debug log
14 System.debug(empList);
15
16 // Verify list sort order.
17 System.assertEquals('Caragh Smith', empList[0].Name);
18 System.assertEquals('Joe Smith', empList[1].Name);
19 System.assertEquals('J. Smith', empList[2].Name);
20 System.assertEquals('Mario Ruiz', empList[3].Name);
21 }
22}