For example, if I have a class:
public class Class
{
public Random r;
public Class()
{r= new Random()}
}
and later create two instances of it:
Class a = new Class();
Class b = new Class();
and call r sequentially, the r for both will give the same values. I've read that this is because the default constructor for Random uses the time to provide "randomness," so I was wondering how I could prevent this. Thanks in advance!
One way to achieve that would be to make r
static
.
static
means that only one Random r
will exist, and it will be shared across all instances of the class.
You code would look like this:
public class Class() { static Random r = new Random(); }
Class a = new Class();
Class b = new Class();
If you're using threading, you can make it [ThreadStatic]
(so that each thread uses its own instance of the Random class)
There's info on how to use [ThreadStatic]
here - I haven't used it myself, but it looks quite cool and nifty, and gets rid of any potential threading-related woes.
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