Java Random getRandomElement(T[] items)

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

Description

choose a random element

License

Apache License

Parameter

Parameter Description
items list

Return

some element - null

Declaration

public static <T> T getRandomElement(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();

    /**//from   w  w w  .  j a  va2 s .co m
     * choose a random element
     *
     * @param items list
     * @return some element - null
     */
    public static <T> T getRandomElement(T[] items) {
        if (items == null)
            return null;
        int len = items.length;
        switch (len) {
        case 0:
            return null;
        case 1:
            return items[0];
        default:
            return items[RND.nextInt(len)];
        }
    }
}

Related

  1. getRandom()
  2. getRandom(Collection collection)
  3. getRandom(int i)
  4. getRandom(int min, int max)
  5. getRandomDigits(Random r, int l, int radix)
  6. getRandomFileName()
  7. getRandomFloat()
  8. getRandomFloatArray()
  9. getRandomObject()