Java Reference
In-Depth Information
Software Engineering Observation 16.5
The collections framework methods are polymorphic. That is, each can operate on objects
that implement specific interfaces, regardless of the underlying implementations.
16.7.1 Method sort
Method sort sorts the elements of a List , which must implement the Comparable inter-
face . The order is determined by the natural order of the elements' type as implemented
by a compareTo method. For example, the natural order for numeric values is ascending
order, and the natural order for Strings is based on their lexicographical ordering
(Section 14.3). Method compareTo is declared in interface Comparable and is sometimes
called the natural comparison method . The sort call may specify as a second argument a
Comparator object that determines an alternative ordering of the elements.
Sorting in Ascending Order
Figure 16.6 uses Collections method sort to order the elements of a List in ascending
order (line 17). Method sort performs an iterative merge sort (we demonstrated a recur-
sive merge sort in Section 19.8). Line 14 creates list as a List of String s. Lines 15 and
18 each use an implicit call to the list 's toString method to output the list contents in
the format shown in the output.
1
// Fig. 16.6: Sort1.java
2
// Collections method sort.
3
import java.util.List;
4
import java.util.Arrays;
5
import java.util.Collections;
6
7
public class Sort1
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);
15
System.out.printf( "Unsorted array elements: %s%n" , list);
16
17
Collections.sort(list); // sort ArrayList
18
System.out.printf( "Sorted array elements: %s%n" , list);
19
}
20
} // end class Sort1
Unsorted array elements: [Hearts, Diamonds, Clubs, Spades]
Sorted array elements: [Clubs, Diamonds, Hearts, Spades]
Fig. 16.6 | Collections method sort .
Sorting in Descending Order
Figure 16.7 sorts the same list of strings used in Fig. 16.6 in descending order. The example
introduces the Comparator interface, which is used for sorting a Collection 's elements in
 
 
Search WWH ::




Custom Search