Class Random
’s methods actually generate pseudorandom numbers based on complex mathematical calculations—the sequence of numbers appears to be random. The calculation that produces the numbers uses the time of day as a seed value to change the sequence’s starting point. Each new Random
object seeds itself with a value based on the computer system’s clock at the time the object is created, enabling each execution of a program to produce a different sequence of random numbers.
When debugging an application, it’s often useful to repeat the exact same sequence of pseudorandom numbers during each execution of the program. This repeatability enables you to prove that your application is working for a specific sequence of random numbers before you test it with different sequences of random numbers. When repeatability is important, you can create a Random
object as follows:
Random randomNumbers = new Random( seedValue );
The seedValue
argument (of type long
) seeds the random-number calculation. If the same seedValue
is used every time, the Random
object produces the same sequence of numbers. You can set a Random
object’s seed at any time during program execution by calling the object’s set
method, as in
randomNumbers.set( seedValue );