我有以下类(class):
public class MyClass
{
private Random rand;
private HashSet<Pair<Integer, Integer>> set;
public MyClass()
{
rand = new Random(Double.doubleToLongBits(Math.random()));
set = new HashSet<Pair<Integer, Integer>>();
}
public void doSomething(int len)
{
set.clear();
for (int i = 0; i < 1000; i++)
{
int index = rand.nextInt(len - 1) + 1;
int min = 1 - index;
int max = len - index - 1;
int j = rand.nextInt(max - min + 1) + min;
if (j != 0)
{
set.add(new Pair<Integer, Integer>(index, j));
}
}
}
}
Pair
是一个自定义类,我可以在其中存储两个整数。问题是,每次我调用 doSomething()
时,HashSet
总是包含相同的值。
这怎么可能?我该如何解决这个问题?
编辑:
最佳答案
来自documentation :
An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 3, Section 3.2.1.)
If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.
关于java - HashSet 中的随机数始终相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20474294/