I have the following method:
public LinkedList<Object> init(int counter) {
LinkedList<Object> list = new LinkedList<Object>();
double decision, value, key;
int max1 = 700;
int max2 = 1000;
for (int i = 0; i < counter; i++) {
decision= Math.random();
if (decision<= 0.2) {
key = Math.random() * 1.5;
value= Math.random() * max1 ;
list.add(new A(value, key));
} else {
value= Math.random() * max2 ;
list.add(new B(value));
}
}
return list;
}
The problem I get is this: if I call this method using
init(100);
and then check the size of the resulting list, it is not always 100. Instead, the number of elements in the list varies depending on the values i choose for max1 and max2. If I choose max2 = 1000000 for example, I end up with a list of about 15 elements. I suspect this has something to do with how Math.random() works, but have no idea how it happens. Is the problem about threading?
In case someone wants to try this, here are templates for classes A and B (the workings of which don’t play into this):
public class A {
public A(double value, double key) {}
}
public class B {
public B(double value) {}
}
No,
Math.random()does not run any threads in the background.In fact, your function is perfectly fine. I’ve tested it extensively and it does exactly what one would expect. It always returns exactly
counterelements.I therefore have to conclude that your problem lies elsewhere, i.e. outside the code that you’re showing us.