Java Reference
In-Depth Information
For example, you can sort an array of integers or String s, but you can't easily sort
an array of Point objects or Color objects because those classes don't implement
the Comparable interface.
To sort a list you can use the Collections.sort method, discussed briefly in
Chapter 10, which accepts a list such as an ArrayList as a parameter and puts its
elements into sorted order. The following code produces the same output as the pre-
ceding array code:
// demonstrate the Collections.sort method
List<String> list = new ArrayList<String>();
list.add("c");
list.add("b");
list.add("g");
list.add("h");
list.add("d");
list.add("f");
list.add("e");
list.add("a");
Collections.sort(list);
System.out.println(list);
When the Arrays.sort method is used with primitive data, it uses an algorithm
called quicksort. Collections.sort and Arrays.sort use a different algorithm,
called merge sort, when they deal with object data. We'll discuss the implementation
of merge sort in detail later in this chapter.
Shuffling
The task of shuffling data, or rearranging the elements into a random order, is per-
haps the opposite of sorting. Why would one want to do this?
One application for shuffling is a card game program. You might have a card deck
stored as a list of Card objects. If the cards are in a predictable order, the game will
be boring. You'd like to shuffle the deck of cards, rearranging them into a random
ordering each time. This is a case in which chaos is preferable to order.
Another application is a situation in which you want a random permutation of a
list of numbers. You can acquire a random permutation of the numbers from 1
through 5, for example, by storing those numbers into a list and shuffling the list.
The Collections class has a method called shuffle that accepts a list as its
parameter and rearranges its elements randomly. The following example creates a
deck of card strings, shuffles it, and examines the card at the top of the deck:
String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9",
"10", "Jack", "Queen", "King", "Ace"};
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
 
Search WWH ::




Custom Search