Java Random Element randomElement(T[] array)

Here you can find the source of randomElement(T[] array)

Description

Picks a random element out of any array type.

License

Open Source License

Parameter

Parameter Description
array the array to pick the element from.

Return

the element chosen.

Declaration

public static <T> T randomElement(T[] array) 

Method Source Code

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

import java.util.List;
import java.util.Random;

public class Main {
    /** Random instance, used to generate pseudo-random primitive types. */
    public static final Random RANDOM = new Random(System.currentTimeMillis());

    /**/* www.  j  av  a  2s  . c  o m*/
     * Picks a random element out of any array type.
     * 
     * @param array
     *            the array to pick the element from.
     * @return the element chosen.
     */
    public static <T> T randomElement(T[] array) {
        return array[(int) (RANDOM.nextDouble() * array.length)];
    }

    /**
     * Picks a random element out of any list type.
     * 
     * @param list
     *            the list to pick the element from.
     * @return the element chosen.
     */
    public static <T> T randomElement(List<T> list) {
        return list.get((int) (RANDOM.nextDouble() * list.size()));
    }
}

Related

  1. randomElement(E[] array)
  2. randomElement(final Set set)
  3. randomElement(int[] anArray)
  4. randomElement(List list)
  5. randomElement(T... values)
  6. randomElementOf(final List list)
  7. randomElementOf(String[] array)
  8. randomEles(List list, int count)