Java: Can (new Random()).nextInt(5) always return the same number? -


Sometimes this piece of code always gives the same number (and sometimes it works fine): < / P>

  (new random ()). NextInt (5)  

I doubt where the problem is - it probably always creates a new rand with the same seed, then what would be the best solution:

    < Li> Use Math.random () * 5 (It seems that it is used internally by using a static version) to create a fixed war for random (Random) and instead use it
  • Does

Or something else? I do not need some fantasy, which seems random.

In addition to this it would be useful if someone can tell why the original code sometimes works and sometimes it does not happen.

Thank you.

javadoc.util.Random for Java is obvious:

If two instances of random are created with the same seed, and if the same order of call method is done for each, they will generate and return the same series of numbers.

The default constructor is also clear:

creates a new random number generator. This creator has set the value of the random number generator's seed to be different from any other inventor of this constructor.

In other words, no guarantee.

If you want a more random algorithm, use java.security.SecureRandom.


Comments

Popular posts from this blog

c++ - Linux and clipboard -

What is expire header and how to achive them in ASP.NET and PHP? -

sql server - How can I determine which of my SQL 2005 statistics are unused? -