If you are going to receive a random element several times, you want your random number generator to be initialized only once.
import java.util.Random; public class RandArray { private int[] items = new int[]{1,2,3}; private Random rand = new Random(); public int getRandArrayElement(){ return items[rand.nextInt(items.length)]; } }
If you select random array elements that should be unpredictable, you should use java.security.SecureRandom , not Random. This ensures that if someone knows the last few choices, they will not have the advantage of guessing the next one.
If you want to select a random number from an Object array using generics, you can define a way for this (Source Avinash R in Random element from an array of strings ):
import java.util.Random; public class RandArray { private static Random rand = new Random(); private static <T> T randomFrom(T... items) { return items[rand.nextInt(items.length)]; } }
Stephen Ostermiller Apr 02 '16 at 10:33 2016-04-02 10:33
source share