java - HashSet 中的随机数始终相同

标签 java random hashset

我有以下类(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 总是包含相同的值。

这怎么可能?我该如何解决这个问题?

编辑:

这是我的配对:https://stackoverflow.com/a/677248/1395740

最佳答案

来自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/

相关文章:

Java,Vector不添加字符输入

java - 如何获取系统信息语言环境 - Locale.getDefault()

python - 有没有办法让 numpy 数组中的数字随机为正或负?

java - 当它是 HashMap 的值时添加到 HashSet

java - 为什么添加 4 个对象后 HashSet 大小为 3?

java - Neo4J 和 Spring 返回空关系

Java 方法和泛型

python - 如何在Python中随机打印列表中的元素?

mysql - 将准备好的语句的结果存储为 mysql 中的表?

java - 迭代集合