I'm trying to get a a list of random number and put it in queue without any repetition of the random number.
int number = 40;
for (int j = 0; j<number; j++)
{
int pick = random.nextInt(number);
myQueue.add(Integer.toString(pick));
}
System.out.println("the queue size: "+myQueue.size());
Iterator it = myQueue.iterator();
while(it.hasNext()){
String iteratorValue = (String)it.next();
System.out.println("queue next value: "+iteratorValue);
}
with the above code, I got some repetition of the random number
anyone know how to do it??
Create a Set and add you numbers to it as you generate them. The each time you generate a new number check if the Set already contains that value. Continue generating new numbers and checking the set until you find one that is not already there.
Something along these lines... (Note that
Set.add(...)
returns false if the value is already in the Set, so the do-while loop continues until a unique number is generated.)Though as mentioned in by A. R. S., you don't seem to be looking for a random unique number, but rather a randomly shuffled list of all numbers between 0 and 40. If that is the case, use his/her solution as it is a better way to achieve that goal.
How about this:
"Adding unique random numbers" in some range is equivalent to adding all of the numbers in the range and then shuffling the result.
If there is a small range of the random numbers, then you can simply generate list with available values and use
Collections.shuffle
on the list.