Is there a difference between:

Random gen = new Random(); //цикл {massive[i]=gen.nextInt(1000);} 

and

 //цикл massive[i]=(int)(Math.random()*1000); 

? And when is it better to use? I understand that because of the cast, the second method will be noticeably slower.

    1 answer 1

    The first option looks more aesthetically pleasing and there is no type conversion. And if in general, both methods are equivalent. If you look at the implementation of Math.random (), we see the following:

      private static final class RandomNumberGeneratorHolder { static final Random randomNumberGenerator = new Random(); } public static double random() { return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble(); } 
    • Only now reproduce the result will not work. And with Random you can. And if there are a lot of threads, then Math.random definitely does not need to be used. - pavel
    • Interestingly, why Math.random can not be used in a multi-threaded environment, and you can Random? They are not thread-safe. Apply for this safe version - LocalThreadRandom - Artem Konovalov