Java Reference
In-Depth Information
Figure 21.1. The
sort()
method can sort any list, using a method that you supply to
perform the comparison step of the algorithm.
The static
sort()
method accepts a list and an instance of
Comparator
. The
Comparator
interface requires its implementer to supply the comparison step of the sorting algorithm.
The
compare()
method must return a number less than, equal to, or greater than 0. These
values correspond to the idea that, in a sense that you define, object
o1
is less than, equal to,
or greater than object
o2
. For example, you might implement
compare()
to compare
the sharpness of two rocks or the apogee of two rockets.
The following class sorts a collection of rockets by their apogees:
package com.oozinoz.applications;
import java.util.*;
import com.oozinoz.units.*;
import com.oozinoz.fireworks.*;
public class ShowComparator implements UnitConstants
{
public static void main(String[] args)
{
Rocket r1 = new Rocket(
"Mach-it", 22.95, (Length) METER.times(1000));