Java Reference
In-Depth Information
19
// output List elements
20
System.out.printf( "Unsorted array elements:%n%s%n" , list);
21
22
// sort in order using a comparator
23
Collections.sort(list, new TimeComparator());
24
25
// output List elements
26
System.out.printf( "Sorted list elements:%n%s%n" , list);
27
}
28
} // end class Sort3
Unsorted array elements:
[6:24:34 AM, 6:14:58 PM, 6:05:34 AM, 12:14:58 PM, 6:24:22 AM]
Sorted list elements:
[6:05:34 AM, 6:24:22 AM, 6:24:34 AM, 12:14:58 PM, 6:14:58 PM]
Fig. 16.9 | Collections method sort with a custom Comparator object. (Part 2 of 2.)
16.7.2 Method shuffle
Method shuffle randomly orders a List 's elements. Chapter 7 presented a card shuffling
and dealing simulation that shuffled a deck of cards with a loop. Figure 16.10 uses method
shuffle to shuffle a deck of Card objects that might be used in a card-game simulator.
1
// Fig. 16.10: DeckOfCards.java
2
// Card shuffling and dealing with Collections method shuffle.
3
import java.util.List;
4
import java.util.Arrays;
5
import java.util.Collections;
6
7
// class to represent a Card in a deck of cards
8
class Card
9
{
10
public static enum Face { Ace , Deuce , Three , Four , Five , Six ,
11
Seven , Eight , Nine , Ten , Jack , Queen , King };
12
public static enum Suit { Clubs , Diamonds , Hearts , Spades };
13
14
private final Face face;
15
private final Suit suit;
16
17
// constructor
18
public Card(Face face, Suit suit)
19
{
20
this. face = face;
21
this. suit = suit;
22
}
23
24
// return face of the card
25
public Face getFace()
26
{
Fig. 16.10 | Card shuffling and dealing with Collections method shuffle . (Part 1 of 3.)
 
 
Search WWH ::




Custom Search