Java Reference
In-Depth Information
• long nextLong() returns the next pseudorandom, uniformly distributed
longintegervalueinthisrandomnumbergenerator'ssequence.Because Ran-
dom usesaseedwithonly48bits,thismethodwillnotreturnallpossible64-bit
long integer values.
The java.util.Collections class declares a pair of shuffle() methods
for shuffling the contents of a list. In contrast, the Arrays class does not declare a
shuffle() methodforshufflingthecontentsofanarray. Listing6-11 addressesthis
omission.
Listing 6-11. Shuffling an array of integers
import java.util.Random;
class Shuffler
{
public static void main(String[] args)
{
Random r = new Random();
int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int i = 0; i < array.length; i++)
{
int n = r.nextInt(array.length);
// swap array[i] with array[n]
int temp = array[i];
array[i] = array[n];
array[n] = temp;
}
for (int i = 0; i < array.length; i++)
System.out.print(array[i]+" ");
System.out.println();
}
}
Listing 6-11 presents a simple recipe for shuffling an array of integers—this recipe
could be generalized. For each array entry from the start of the array to the end of the
array, this entry is swapped with another entry whose index is chosen by int nex-
tInt(int n) .
 
Search WWH ::




Custom Search