How do I generate a random array of numbers?

Using java.util.Random class we can create random data such as boolean, integer, floats, double. First you’ll need to create an instance of the Random class. This class have some next***() methods that can randomly create the data.

package org.kodejava.example.util;

import java.util.Arrays;
import java.util.Random;

public class RandomDemo {
    public static void main(String[] args) {
        Random r = new Random();

        // generate some random boolean values
        boolean[] booleans = new boolean[10];
        for (int i = 0; i < booleans.length; i++) {
            booleans[i] = r.nextBoolean();
        }
        System.out.println(Arrays.toString(booleans));

        // generate a uniformly distributed int random numbers
        int[] integers = new int[10];
        for (int i = 0; i < integers.length; i++) {
            integers[i] = r.nextInt();
        }
        System.out.println(Arrays.toString(integers));

        // generate a uniformly distributed float random numbers
        float[] floats = new float[10];
        for (int i = 0; i < floats.length; i++) {
            floats[i] = r.nextFloat();
        }
        System.out.println(Arrays.toString(floats));

        // generate a Gaussian normally distributed random numbers
        double[] doubles = new double[10];
        for (int i = 0; i < doubles.length; i++) {
            doubles[i] = r.nextGaussian();
        }
        System.out.println(Arrays.toString(doubles));
    }
}

The result of the code snippet above are:

[true, false, false, true, true, true, true, false, false, true]
[880569018, 584161271, 1188257744, 1810736813, 2065540711, 2129338546, 1939490062, 1865141839, -1660461645, 211673120]
[0.097299635, 0.44844186, 0.5900976, 0.43893605, 0.8813426, 0.71923894, 0.7685699, 0.19013077, 0.8173217, 0.3595813]
[-0.037493646212294, 1.756568052729634, 0.8849071468575704, -0.27909848975272716, 1.7014373967099943, 0.7562137933093157, -1.2515831815175729, 0.8055530429393517, -0.10414001279168857, 1.347637572163826]

For an example to create random number using the Math.random() method see How do I create random number?.

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA. Support me by donating >> here <<.

Leave a Reply