Java Reference
In-Depth Information
using the y -coordinate to break ties. The following code is an example Comparator
that compares Point objects in this way:
1 import java.awt.*;
2 import java.util.*;
3
4 // compares Point objects by x-coordinate and then by y-coordinate
5 public class PointComparator implements Comparator<Point> {
6 public int compare(Point p1, Point p2) {
7 int dx = p1.x - p2.x;
8 if (dx == 0) {
9 int dy = p1.y - p2.y;
10 return dy;
11 } else {
12
return dx;
13 }
14 }
15 }
It's important to understand that we are creating a separate class as our comparator;
we are not modifying the Point class itself. This is one of the main benefits of com-
parators: you don't need to modify the class being ordered. The following code uses
the PointComparator to sort an array of four Point objects:
Point[] points = {
new Point(4, -2),
new Point(3, 9),
new Point(-1, 15),
new Point(3, 7)
};
Arrays.sort(points, new PointComparator());
This code sorts the points into the following order: (-1, 15), (3, 7), (3, 9), (4, -2).
This comparator also allows you to use Point objects in the “tree” collections that
depend on ordering, TreeSet and TreeMap . Both of these collections have constructors
that accept a comparator as a parameter and use it to order their elements internally.
If you have a group of objects with a natural ordering and you want to sort them in
reverse order, you can call the method Collections.reverseOrder to receive a
Comparator that inverts the objects' natural ordering. For example, the following code
would sort the array of String s that was used earlier in reverse alphabetical order:
Arrays.sort(strings, Collections.reverseOrder());
For types that do not have a natural ordering, you can ask for the reverse of a
Comparator 's order by calling Collections.reverseOrder and passing the
 
Search WWH ::




Custom Search