compareTo method only implements a sort ordering for an ascending
sort using a strict comparison. Frequently it is desirable to override a class-defined sort order or even to sort
items that do not implement a compareTo method. To change the sorting criteria,
use the sortWith method. The sortWith
method takes a single argument, which is a Comparator object that implements a compare
method. The compare method performs comparisons between pairs of items. Different
comparators can be customized for different comparison purposes. For example, the Rexx language provides a
DescendingComparator class that will sort items into descending order:
::CLASS 'DescendingComparator' MIXINCLASS Comparator
::METHOD compare
use strict arg left, right
return -left~compareTo(right)
compareTo method. Our previous example
myArray = .array~of("Zoe", "Fred", "Xavier", "Andy")
myArray~sortWith(.DescendingComparator~new)
do name over myArray
say name
end
compare method that knows how to compare pairs of items in some particular
manner. For example, to sort our Employee class by name instead of the default employee id, we can use the following
simple comparator class:
::CLASS EmployeeNameSorter MIXINCLASS Comparator
::METHOD compare
use strict arg left, right
return left~name~compareTo(right~name) -- do the comparison using the names