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??
How about this:
List<String> list = new ArrayList<String>(number);
for (int i = 0; i < number; i++)
list.add(Integer.toString(i));
Collections.shuffle(list);
myQueue.addAll(list);
"Adding unique random numbers" in some range is equivalent to adding all of the numbers in the range and then shuffling the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With