Random
The Random class is a generator of pseudorandom numbers.
Random defines the following constructors:
Random( )
- creates a number generator that uses the current time as the starting, or seed, value.
Random(long seed)
- specify a seed value manually.
A seed defines the starting point for the random sequence. If you use the same seed to initialize another Random object, you will get the same random sequence. If you want to generate different sequences, specify different seed values.
Using the current time to seed a Random object reduces the possibility of getting repeated sequences.
The public methods defined by Random are:
boolean nextBoolean( )
- Returns the next boolean random number.
void nextBytes(byte vals[ ])
- Fills vals with randomly generated values.
double nextDouble( )
- Returns the next double random number.
float nextFloat( )
- Returns the next float random number.
double nextGaussian( )
- Returns the next Gaussian random number.
int nextInt( )
- Returns the next int random number.
int nextInt(int n)
- Returns the next int random number within the range zero to n.
long nextLong( )
- Returns the next long random number.
void setSeed(long newSeed)
- Sets the seed value (that is, the starting point for the random number generator) to that specified by newSeed.
Random Boolean values are available from nextBoolean( ). Random bytes can be obtained by calling nextBytes( ). Integers can be extracted via the nextInt( ) method. Long integers can be obtained with nextLong( ). The nextFloat( ) and nextDouble( ) methods return a uniformly distributed float and double, respectively, between 0.0 and 1.0. nextGaussian( ) returns a double value centered at 0.0 with a standard deviation of 1.0.
The following code shuffles an array of integers.
import java.util.Random;
public class Main {
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);
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();
}
}
Output:
4 1 5 7 8 2 3 9 0 6
The next example creates Random class from an Integer using new Random(int intValue).
import java.util.Random;
public class MainClass {
public static void main(String args[]) {
Random generator = new Random(100);
System.out.println("First generator:");
for(int i = 0; i < 10; i++)
System.out.println(generator.nextInt());
}
}
Output:
First generator:
-1193959466
-1139614796
837415749
-1220615319
-1429538713
118249332
-951589224
1301674577
-1638067850
-1279751870