Java Reference
In-Depth Information
a different order. Line 18 calls Collections 's method sort to order the List in descend-
ing order. The static Collections method reverseOrder returns a Comparator object
that orders the collection's elements in reverse order.
1
// Fig. 16.7: Sort2.java
2
// Using a Comparator object with method sort.
3
import java.util.List;
4
import java.util.Arrays;
5
import java.util.Collections;
6
7
public class Sort2
8
{
9
public static void main(String[] args)
10
{
11
String[] suits = { "Hearts" , "Diamonds" , "Clubs" , "Spades" };
12
13
// Create and display a list containing the suits array elements
14
List<String> list = Arrays.asList(suits); // create List
15
System.out.printf( "Unsorted array elements: %s%n" , list);
16
17
// sort in descending order using a comparator
Collections.sort(list, Collections.reverseOrder());
18
19
System.out.printf( "Sorted list elements: %s%n" , list);
20
}
21
} // end class Sort2
Unsorted array elements: [Hearts, Diamonds, Clubs, Spades]
Sorted list elements: [Spades, Hearts, Diamonds, Clubs]
Fig. 16.7 | Collections method sort with a Comparator object.
Sorting with a Comparator
Figure 16.8 creates a custom Comparator class, named TimeComparator , that implements
interface Comparator to compare two Time2 objects. Class Time2 , declared in Fig. 8.5, rep-
resents times with hours, minutes and seconds.
1
// Fig. 16.8: TimeComparator.java
2
// Custom Comparator class that compares two Time2 objects.
3
import java.util.Comparator;
4
5
public class TimeComparator implements
Comparator<Time2>
6
{
7
@Override
8
public int compare(
Time2 time1 Time2 time2
,
)
9
{
10
int hourDifference = time1.getHour() - time2.getHour();
11
12
if (hourDifference != 0 ) // test the hour first
13
return hourCompare;
Fig. 16.8 | Custom Comparator class that compares two Time2 objects. (Part 1 of 2.)
 
Search WWH ::




Custom Search