【发布时间】:2013-12-09 15:28:22
【问题描述】:
我有以下课程:
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 总是包含相同的值。
这怎么可能?我该如何解决这个问题?
编辑:
【问题讨论】:
-
equals和hashCode类的Pair方法是什么? -
你是创建了新的 MyClass 实例,还是使用旧的?
-
@Gladiator 我只使用了 MyClass 的一个实例,所以旧的...
-
为什么不直接使用 new Random()
-
您将什么 int 值作为参数传递给 doSomething() 调用?