Java Random Int random(int... array)

Here you can find the source of random(int... array)

Description

Returns a randomly selected element from the specified int array, as defined by Math#random() .

License

Open Source License

Parameter

Parameter Description
array The array to be selecting a random element from.

Return

The randomly selected element.

Declaration

public static int random(int... array) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//from w  w  w .ja  v a  2s. c o  m
     * Returns a randomly selected element from the specified {@code int} array, as defined by
     * {@link Math#random()}.
     * 
     * @param array
     *            The array to be selecting a random element from.
     * @return The randomly selected element.
     */
    public static int random(int... array) {
        switch (array.length) {
        case 0:
            return 0;
        case 1:
            return array[0];
        default:
            int selection = (int) (Math.random() * array.length);
            return array[selection];
        }
    }

    /**
     * Returns a randomly selected element from the specified array, as defined by
     * {@link Math#random()}.
     * 
     * @param array
     *            The array to be selecting a random element from.
     * @return The randomly selected element.
     */
    @SafeVarargs
    public static <T> T random(T... array) {
        switch (array.length) {
        case 0:
            return null;
        case 1:
            return array[0];
        default:
            int selection = (int) (Math.random() * array.length);
            return array[selection];
        }
    }
}

Related

  1. random(int numSamples)
  2. random(int range)
  3. random(int start, int end)
  4. random(int theRange)
  5. random(int x)
  6. random_range(int x1, int x2)
  7. randomActorId(int max)
  8. randomAlphaNum(int length)
  9. randomAlphanumeric(int count)