vendredi 8 mai 2015

Java's random number generator -- is creating a new random object for each random number *functionally* incorrect?

Is there any chance of the following bit of code ever printing something to the console?

while (true) {
    long t1 = System.nanoTime();
    long t2 = System.nanoTime();
    if (t1 == t2)
        System.out.println(t1 == t2);
}

And what about:

Random r1 = new Random();
Random r2 = new Random();

having r1 and r2 having the same seed?

Other way of asking the same question is: is the following bit of code correct?

// generate k random integers
int[] random_numbers = new int[k];
for (int i = 0; i < k; ++i) {
  Random r = new Random();
  random_numbers[i] = r.nextInt();
}




Aucun commentaire:

Enregistrer un commentaire