Here you can find the source of randomElement(Collection
Parameter | Description |
---|---|
in | - choices - non-null non-empty |
public static <T> T randomElement(Collection<T> in)
//package com.java2s; //License from project: Apache License import java.util.*; import java.util.List; public class Main { public static final Random gRandomizer = new Random(System.currentTimeMillis()); /**{ method/*from w w w .ja v a 2 s .c o m*/ @name randomElement @function - choose an element of an array at random @param in - choices - non-null non-empty @return - one choice }*/ public static <T> T randomElement(Collection<T> in) { int size = in.size(); if (size == 0) return (null); int item = 0; if (size > 1) item = randomInt(size); List<T> TheList = new ArrayList<T>(in); T ret = TheList.get(item); TheList = null; return (ret); } /**{ method @name randomElement @function - choose an element of an array at random @param in - choices - non-null non-empty @return - one choice }*/ public static <T> T randomElement(T[] in) { if (in.length == 1) return (in[0]); return (in[randomInt(in.length)]); } /**{ method @name randomElement @function - choose an element of an array at random @param in - choices - non-null non-empty @return - one choice }*/ public static double randomElement(double[] in) { if (in.length == 1) return (in[0]); return (in[randomInt(in.length)]); } /**{ method @name randomElement @function - choose an element of an array at random @param in - choices - non-null non-empty @return - one choice }*/ public static char randomElement(char[] in) { if (in.length == 1) return (in[0]); return (in[randomInt(in.length)]); } /**{ method @name randomElement @function - choose an element of an array at random @param in - choices - non-null non-empty @return - one choice }*/ public static int randomElement(int[] in) { if (in.length == 1) return (in[0]); return (in[randomInt(in.length)]); } /**{ method @name randomElement @function - choose an element of an array at random @param in - choices - non-null non-empty @return - one choice }*/ public static int randomInt(int in) { if (in <= 1) { if (in == 1) return (0); throw new IllegalArgumentException("randomInt must take a number > 1"); } int test = gRandomizer.nextInt(in); if (test < 0) test = -test; return (test); } }