how to generate random number from array

23,606
import java.util.Random;

...

Random random = new Random();
System.out.println(n[random.nextInt(n.length)]);
Share:
23,606
Jessy
Author by

Jessy

Updated on July 09, 2022

Comments

  • Jessy
    Jessy almost 2 years

    How to generate random number from an array? and not from a range.

    int n [] = {1,7,3,5,8,10,33,12,18}
    
  • Jessy
    Jessy about 14 years
    Thank you :-) ...you are brilliant!
  • Rich
    Rich about 14 years
    Note that you should cache the Random instance in a field instead of creating a new instance each time you need a random number.