J.6.2. Method shuffle
Method shuffle randomly orders a List
’s elements. Appendix E presented a card shuffling and dealing simulation that shuffled a deck of cards with a loop. If you have an array of 52 Card
objects, you can shuffle them with method shuffle
as follows:
List< Card > list = Arrays.asList( deck ); // get ListCollections.shuffle( list ); // shuffle deck
The second line above shuffles the array by calling static
method shuffle
of class Collections
. Method shuffle
requires a List
argument, so we must obtain a List
view of the array before we can shuffle it. The Arrays
class’s static
method asList
gets a List
view of the deck
array.
Get Android™ How to Program, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.