Java random.nextDouble在for块中创建相同的序列

Java random.nextDouble在for块中创建相同的序列,java,random,Java,Random,我有下面的代码来创建一个从0到给定数量的随机数字序列 ArrayList<Integer> places = new ArrayList<Integer>(); for (int cnt = 0; cnt < NUMBER; cnt++) { int place = (int)(random.nextDouble()*places.size()); places.add(place , new Integer(cnt)); } ArrayList

我有下面的代码来创建一个从0到给定数量的随机数字序列

ArrayList<Integer> places = new ArrayList<Integer>();
for (int cnt = 0; cnt < NUMBER; cnt++) {
    int place = (int)(random.nextDouble()*places.size());
    places.add(place , new Integer(cnt));
}
ArrayList places=new ArrayList();
对于(int-cnt=0;cnt
我在一个方法中使用了这段代码,然后为了统计的目的,我运行了大约1000次这个方法。 我的问题是,创建的系列在所有1000次中都是相同的。
每次运行该序列时都是不同的,但所有for值都是相同的。
我该怎么办?是否有一个方法,比如sRAND()在C++中?< /p> < p>如果你试图生成一个数组,代码“代码> 0”,那么你的算法就有缺陷了…数字1以随机顺序排列。考虑:

Random rnd = new Random(System.currentTimeMillis());
...
ArrayList<Integer> places = new ArrayList<Integer>(NUMBER);
for (int i = 0; i < NUMBER; ++i) {
  places.add(i);
}
Collections.shuffle(places, rnd);
Random rnd=new Random(System.currentTimeMillis());
...
ArrayList places=新的ArrayList(编号);
对于(int i=0;i
如果您试图生成一个包含数字的数组,则您的算法似乎有缺陷。
0。。。数字1以随机顺序排列。考虑:

Random rnd = new Random(System.currentTimeMillis());
...
ArrayList<Integer> places = new ArrayList<Integer>(NUMBER);
for (int i = 0; i < NUMBER; ++i) {
  places.add(i);
}
Collections.shuffle(places, rnd);
Random rnd=new Random(System.currentTimeMillis());
...
ArrayList places=新的ArrayList(编号);
对于(int i=0;i
使用您使用的是Math.random()。它将返回一个从0.0到1.0的双精度值。因此,可以用以下内容替换for循环中的两行:

places.add((int)(Math.random() * places.size()),cnt);
//you don't have to do "new   Integer(cnt)" because of Java's auto-boxing feature
使用Math.random()。它将返回一个从0.0到1.0的双精度值。因此,可以用以下内容替换for循环中的两行:

places.add((int)(Math.random() * places.size()),cnt);
//you don't have to do "new   Integer(cnt)" because of Java's auto-boxing feature

如何创建
Random
对象?您的示例不完整。这个问题不清楚,您是希望保证所有内容都有不同的值,还是每次都保证相同的“随机”值?显示如何创建
random
实例。“每次运行序列都不同,但所有for值都相同。”这意味着什么?如何播种该随机数?如何创建
random
对象?您的示例不完整。这个问题不清楚,您是希望保证所有内容都有不同的值,还是每次都保证相同的“随机”值?还显示如何创建
随机
实例。“每次运行序列时都不同,但所有for值都相同。”这意味着什么?如何播种该随机数?