Java Reference
In-Depth Information
can use a constant Comparator in the String class called CASE_INSENSITIVE_ORDER .
The following code uses it to sort an array of mixed-case strings:
// sort Strings using case-insensitive Comparator
String[] strings = {"Foxtrot", "alpha", "echo", "golf",
"bravo", "hotel", "Charlie", "DELTA"};
Arrays.sort(strings, String.CASE_INSENSITIVE_ORDER);
System.out.println(Arrays.toString(strings));
This code produces the following output:
[alpha, bravo, Charlie, DELTA, echo, Foxtrot, golf, hotel]
Now let's write a Comparator that orders strings by their lengths. Our compare
method should return a negative number if the first string is shorter than the second, 0
if they are equal in length, and a positive number if the first string is longer than the
second. Recall from Chapter 10 that a compareTo method examining integer data
can often simply subtract one number from the other and return the result. The fol-
lowing compare method is also based on this idea:
1 import java.util.*;
2
3 // compares String objects by length
4 public class LengthComparator implements Comparator<String> {
5 public int compare(String s1, String s2) {
6 return s1.length() - s2.length();
7 }
8 }
Now that we've written a length comparator, we can pass one when we sort an
array or list of String objects:
// sort array of strings by length using Comparator
Arrays.sort(strings, new LengthComparator());
System.out.println(Arrays.toString(strings));
Here's the output when we run this code on the String array from earlier in this
section:
[echo, golf, alpha, bravo, hotel, DELTA, Foxtrot, Charlie]
Notice that the strings appear in order of increasing length.
Sometimes you'll want to search or sort a collection of objects that don't imple-
ment the Comparable interface. For example, the Point class doesn't implement
Comparable , but you might want to sort an array of Point objects by x -coordinate,
Search WWH ::




Custom Search