Java Reference
In-Depth Information
public static <T> void sort(List<T> list, Comparator<? super T> c)
sorts the
given
List
according to the ordering of the given
Comparator
. All elements in
list
must be mutually comparable.
Notice that in the fi rst
sort
method the generic
T
is declared as
<T extends
Comparable<? super T>>
, meaning the list object passed in must contain elements that
implement the
Comparable
interface (because of extends
Comparable
) or whose parent class
implements
Comparable
(based on
<? super T>
).
The second
sort
method does not have this restriction because the sorting is based on a
Comparator
, which is a separate object.
We discuss the difference between
Comparable
sorting and
Comparator
sorting next,
starting with a discussion on the
Comparable sort
method.
Comparable Sorting
Let's look at an example of the fi rst
sort
method shown previously that uses the natural
ordering of objects. Recall that the natural ordering refers to the behavior of the
compareTo
method in the
Comparable
interface, so the elements being sorted must implement the
Comparable
interface. The following program sorts a list of
Character
objects in their
natural order. Study the following program and see if you can determine its result:
1. import java.util.*;
2.
3. public class CharacterSorter {
4. public static void main(String [] args) {
5. char [] chars = args[0].toCharArray();
6. List<Character> list = new ArrayList<Character>();
7. for(char c : chars) {
8. list.add(c);
9. }
10. Collections.sort(list);
11. for(Character c : list) {
12. System.out.print(c + “ “);
13. }
14. }
15. }
The
CharacterSorter
program sorts an
ArrayList
of
Character
objects. Here is the
sequence of events of the program:
1.
Line 5 converts the first command-line argument into a
char
array.
2.
Line 6 creates a new
ArrayList<Character>
, and the
for-each
loop on line 7 adds
each
char
in
chars
to the list. Because of autoboxing, each
char
is wrapped in a
Character
object.
Search WWH ::
Custom Search