Currently I'm using a
Random rand = new Random();
myNumber = rand.nextInt((100-0)+1)+0;
and it's a pseudo-random, because I always get the same sequence of numbers. I remember in c++ you could just use the ctime and use srand to make it unique. How do you do it in java ?
If you require a unique random in Java, use SecureRandom
. This class provides a cryptographically strong random number generator (RNG), meaning it can be used when creating certificates and this class is slow compared to the other solutions.
If you require a predictable random that you can reset, use a Random
, where you call .setSeed(number)
to seed it to make the values predictable from that point.
If you want a pseudo-random that is random every time you start the program, use a normal Random
. A random instance is seed by default by some hash of the current time.
For the best randomness in every solution, it is important to RE-USE the random instance. If this isn't done, most of the output it gives will be similar over the same timespan, and at the case of a thrown away SecureRandom, it will spend a lot of time recreating the new random.