我有以下方法:
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;
}
我遇到的问题是:如果我调用这个方法使用
init(100);
然后检查结果列表的大小,它并不总是100
。相反,列表中的元素数量取决于我为 max1
和 max2
选择的值。例如,如果我选择 max2 = 1000000
,我最终会得到一个包含大约 15 个元素的列表。我怀疑这与 Math.random()
的工作方式有关,但不知道它是如何发生的。是关于线程的问题吗?
如果有人想尝试这个,这里有类 A
和 B
的模板(它们的工作原理与此无关):
public class A {
public A(double value, double key) {}
}
public class B {
public B(double value) {}
}
最佳答案
I suspected Math.random() might be running a thread in the background; I did not create any additional threads myself.
不,Math.random()
不在后台运行任何线程。
事实上,您的功能完全没问题。我已经对它进行了广泛的测试,它完全符合人们的期望。它始终准确返回 counter
个元素。
因此,我必须得出结论,您的问题出在其他地方,即在您向我们展示的代码之外。
关于Java - 对 Math.random() 的多次调用搞乱了循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13992851/