Newer Version Available

This content describes an older version of this product. View Latest

Comparator Interface

Implement different sort orders with the Comparator interface’s compare() method, and pass the Comparator as a parameter to List.sort(). Your implementation must explicitly handle null inputs in the compare() method to avoid a null pointer exception.

Namespace

System

Comparator Methods

The following are methods for Comparator.

compare(var1, var2)

Compares the two arguments and returns a negative integer, zero, or a positive integer depending on whether the first argument is less than, equal to, or greater than the second argument.

Signature

public Integer compare(T var1, T var2)

Parameters

var1
Type: T
T - The type determined by the parameterized type of the Comparator. For example, if the class implements Comparator<Account> then var1 and var2 are of type Account .
var2
Type: T
T - The type determined by the parameterized type of the Comparator. For example, if the class implements Comparator<Account> then var1 and var2 are of type Account .

Return Value

Type: Integer

Comparator Example Implementation

Use the Comparator interface to impose different kinds of sorting.

This example implements two different ways of sorting employees.

The following example tests the implementation: