I would like a better, more efficient way to get a random index and return it to the main function [duplicate]

Keywords: java random

Question: 

I know this for normal integers, but is there for such a thing as indices?

Random dice = new Random();
int n = dice.nextInt(6);
System.out.println(n);

Answers: 

To generate a random index for someArray you do

int index = new Random().nextInt(someArray.length);

nextInt(n) returns a number between 0 (inclusive) and n (exclusive) which is why someArray.length is given as argument.

What do you mean? Array indices are normal numbers, so you can easily do

String names[] = { "One", "Two", "Three", "Four", "Five", "Six" };
Random Dice = new Random(); 
int n = Dice.nextInt(6); 
System.out.println(names[n]);

Or do you mean a random Iterator class? Google is your friend here, this is the first hit I get.

Another solution would be:

int randomElement = yourArray[Math.random()*yourArray.length];

Math.random() generates a random number between 0 and 1. If you multiply that number by the length of your array, you will get an random index for the array.

For example: If Math.random() generated .2 and your array had a length of 10, you would get an index of 2.