繁体   English   中英

从ArrayList抓取随机对象不是随机的

[英]Grabbing random object from ArrayList is not random

我正在创建一个方法,如果您传入类型为Random的参数,则它将返回一个随机对象。 这基本上是我想要做的:

public T choose(Random r) {
    int randomInt = r.nextInt(randomList.size()); // randomList is just a instance variable
    return randomList.get(randomInt);   
}

随机列表具有以下字符串: [2, 2, 2, 1, 1, 1, 1, c, c, c, a, a, a, a] 2,2,2,1,1,1,1,1 [2, 2, 2, 1, 1, 1, 1, c, c, c, a, a, a, a]

然后我用以下代码制作了一个驱动程序

 for (int i = 0; i < 10; i++) {
        System.out.print(rndList.choose(rnd)); // rnd is initialized as a static Random variable
    }

但是我的输出不是随机的。 我使用了调试器,发现我的select方法生成的整数相对较低,因此它将始终打印出2或1,而不会打印c或a。 我不知道为什么会这样,将不胜感激。

编辑:问题已解决。 我省略了很多细节,但是当我调用size()方法时,我改写了一些东西,该东西有一个错误,该错误返回的数字比我想要的小。 感谢dtech注意到我的愚蠢错误。 谢谢所有试图帮助我的人!

乍看之下,代码似乎没有问题,因此可能只是随机结果。 但是您的“打印并检查”方法非常不可靠。 只需使用以下内容:

final int N = 10000; // test 10.000 times
HashTable<Object, Integer> count = new HashTable(N);
for(int i=0;i < N;i++){
    Object o = rndList.choose(rnd);
    count.put(o, (count.get(o)==null?0:count.get(o))+1);
}
for(Map.Entry<Object, Integer> map : count.entrySet()){
    System.out.println(String.format("%s: %d", map.getKey().toString(), map.getValue()));
}

平均打印如下:2:1429 1:2857 c:2143 a:2857

仅当数字确实不同时,您才应关注。

还要确保使用新的Random()构造函数,而不是新的Random(somenumber)。 如果使用后者,则每次都会获得相同的数字序列。

发送给您随机初始化代码,您每次得到的结果完全一样吗? 您是否正在使用种子创建随机对象?

这是我使用的代码。 您需要提供更多代码,以查看您的代码为什么不起作用。

public class Main<T> {
    private List<T> randomList = new ArrayList<T>();

    public  T choose(Random r) {
        int randomInt = r.nextInt(randomList.size()); // randomList is just a instance variable
        return randomList.get(randomInt);
    }


    public static void main(String... args) throws IOException, InterruptedException, ExecutionException {
        Main<String> rndList = new Main<String>();
        rndList.randomList.addAll(Arrays.asList("2, 2, 2, 1, 1, 1, 1, c, c, c, a, a, a, a".split(", ")));

        Random rnd = new Random();
        for (int i = 0; i < 10; i++) {
               System.out.print(rndList.choose(rnd)); // rnd is initialized as a static Random variable
           }

    }
}

版画

1ca1caa1a2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM