tags:

views:

50

answers:

2

I have this code:

Random r = new Random();
while (mStack[step].hasNext()) {
int rand = r.nextInt(length);
 for (int i = rand; i < length+rand; i++) {
  //use of i and rand                 
 }
}

and all this in a recursive call.

Will this seed a new Random for each while iteration, different for each recursive call?

Or I have to use

while (mStack[step].hasNext()) {
 Random r = new Random();
int rand = r.nextInt(length);
 for (int i = rand; i < length+rand; i++) {
  //use of i and rand                 
 }
}

Please advice

+1  A: 

You need to use the lower example. The example at the top will re-initialize with each call of the containing method. The second will do so for each item in the stack, meaning for each iteration in the loop.

sblundy
+4  A: 

Constant re-seeding isn't beneficial. Create a single instance of Random, and pass it on the stack as a parameter to the recursive method.

The no-arg Random constructor in Java 6 uses the sum of a instance counter and the current System.nanoTime() value as a seed. Of course, no re-seeding is performed by nextInt().

erickson