3
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?

Bunny Rabbit
  • 8,213
  • 16
  • 66
  • 106
  • 1
    use random on arraylist – Maciej Cygan Oct 13 '13 at 15:41
  • 1
    possible duplicate of [Generating random numbers in a range with Java](http://stackoverflow.com/questions/363681/generating-random-numbers-in-a-range-with-java) Once you have a number in the range `[0..lista.length())`, return `lista.get(myRandomInRange)`. – Sergey Kalinichenko Oct 13 '13 at 15:41

5 Answers5

18

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));
Arnold Galovics
  • 3,246
  • 3
  • 22
  • 33
8

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.

Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
1

The idea is to generate a new random index and use that random index to get a radom number from the array.

For that

  1. Genrate a random number using Math.random() which Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
  2. Adjust the random value to fall between the start index and the end index of the list. We do this by multiplying the double value with the size of the list and converting it to integer, because the list indices are integers.

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 :)

Bunny Rabbit
  • 8,213
  • 16
  • 66
  • 106
0

Use random on number of elements in the list and used that as index.

BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
-1

do this:

Random rn = new Random();
int i = rn.nextInt() % lista.size();
System.out.println(lista.get(i));
Mohammad Adnan
  • 6,527
  • 6
  • 29
  • 47