Java Random randomElement(T[] items)

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

Description

choose a random element from an array

License

Apache License

Parameter

Parameter Description
items non-null array

Return

possibly null value - null only if the array is empty

Declaration

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

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.*;

public class Main {
    public static final Random RND = new Random();

    /**/* w  ww.j a va2s .  c  o  m*/
     * choose a random element from an array
     * @param items non-null array
     * @return possibly null value - null only if the array is empty
     */
    public static <T> T randomElement(T[] items) {
        switch (items.length) {
        case 0:
            return null;
        case 1:
            return items[0];
        default:
            return items[RND.nextInt(items.length)];
        }
    }
}

Related

  1. randomCSeq()
  2. randomData(Random random, int length)
  3. randomDigit()
  4. randomDoubleArray(int size)
  5. randomElement(List list, Random random)
  6. randomElementFromArray(T[] source)
  7. randomEntre1eh100()
  8. randomEnum(Class clazz)
  9. randomEvent(float theChance, float theRange)