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

时间:2011-03-06 16:07:05

标签: java list random arraylist

我正在创建一个方法,如果你传入一个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]

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

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

然而,我的输出并非随机出现。我使用了调试器并发现我的choose方法生成一个相对较低的整数,所以它总是打印出2或1,但从不打印或打印。我无法弄清楚为什么会这样,非常感谢帮助。

编辑:问题解决了。我遗漏了很多细节,但是当我调用size()方法时,这是我覆盖的东西,它有一个错误,它会返回一个比我想要的更小的数字。感谢dtech注意到我的愚蠢错误。感谢所有试图帮助我的人!

3 个答案:

答案 0 :(得分:4)

乍一看,代码似乎没有任何问题,所以它可能只是一个随机的结果。但是你的“打印和检查”方法非常不可靠。只需使用这样的东西:

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)。如果你使用后者,你每次都会得到相同的数字序列。

答案 1 :(得分:1)

发送随机初始化代码,每次都得到完全相同的结果吗?你使用种子来创建Random对象吗?

答案 2 :(得分:1)

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

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