I'm writing a class constructor with a decimal field, that is need to be initialized by a random value. Just one little field and I need to create new Random
object. In the first place it looks cumbersome, and in the second there is can arise a lot of equal values, in case of creating a lot of objects in one time slice (new Random()
is euqal to new Random(System.currentTimeMillis())
, and equal timeMillis entails equal random values).
What is the best way to avoid this?
new Random() is euqal to new Random(System.currentTimeMillis())
No, it's not. In recent JDKs, it's new Random(seedUniquifier() ^ System.nanoTime());
where seedUniquifier() is based on running a linear congruential generator on a static AtomicLong
. So it's actually perfectly safe to create Random
objects as needed.
Of course, you can always have a private static Random
field and use that in the constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With