Java Reference
In-Depth Information
List<String> deck = new ArrayList<String>();
for (String rank : ranks) { // build sorted deck
for (String suit : suits) {
deck.add(rank + " of " + suit);
}
}
Collections.shuffle(deck);
System.out.println("Top card = " + deck.get(0));
The code randomly produces output such as the following, with different outputs
on different runs:
Top card = 10 of Spades
Table 13.1 briefly summarizes the useful static methods in Java's class libraries for
searching, sorting, and shuffling.
Table 13.1
Searching and Sorting in Java's Class Libraries
Method
Description
Returns the index of the given value in
the given array, assuming that the array's
elements are currently in sorted order, or
returns a negative number if the given
value is not found.
Arrays.binarySearch(array, value)
Arranges the given array's elements into
sorted order.
Arrays.sort(array)
Returns the index of the given value in
the given list, assuming that the list's
elements are currently in sorted order, or
returns a negative number if the given
value is not found.
Collections.binarySearch(list, value)
Arranges the given list's elements into a
random order.
Collections.shuffle(list)
Arranges the given list's elements into
sorted order.
Collections.sort(list)
Custom Ordering with Comparators
Sometimes you'll want to search or sort a collection of objects in an ordering that is
different from that of its Comparable implementation. For example, consider the fol-
lowing code, which sorts an array of String s and prints the result:
String[] strings = {"Foxtrot", "alpha", "echo", "golf",
"bravo", "hotel", “Charlie”, "DELTA"};
 
Search WWH ::




Custom Search