ArrayList<Integer> lista = new ArrayList<Integer>();
lista.add(159);
lista.add(170);
lista.add(256);
For example, I got these 3 numbers in my arraylist and I want to randomly get one of them. How is that possible?
ArrayList<Integer> lista = new ArrayList<Integer>();
lista.add(159);
lista.add(170);
lista.add(256);
For example, I got these 3 numbers in my arraylist and I want to randomly get one of them. How is that possible?
One way to do this to use the Random class:
ArrayList<Integer> lista = new ArrayList<Integer>();
lista.add(159);
lista.add(170);
lista.add(256);
Random r = new Random();
System.out.println(lista.get(r.nextInt(lista.size())));
Or use shuffle:
ArrayList<Integer> lista = new ArrayList<Integer>();
lista.add(159);
lista.add(170);
lista.add(256);
Collections.shuffle(lista);
System.out.println(lista.get(0));
You can make use of Random
to generate an int
to be used as a random index.
Random rand = new Random();
Integer randomInt = lista.get(rand.nextInt(lista.size()));
Here, rand.nextInt(lista.size())
would generate a random index between 0
and size - 1
.
Reference :
Random#nextInt(int)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
The idea is to generate a new random index and use that random index to get a radom number from the array.
For that
Math.random()
which Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. This gives us the following code.
int randomIndex = (int)(Math.random() * lista.size());
System.out.println(lista.get(randomIndex));
Please note that the random number generated here are not truely random and are generated using a psuedorandom generator, which suffices for most of the everyday uses.
You can read more about PRNG here if you are curious :)
do this:
Random rn = new Random();
int i = rn.nextInt() % lista.size();
System.out.println(lista.get(i));