2011-03-06 66 views
0

我正在创建一个方法,如果您传入Random类型的参数,那么它将返回一个随机对象。这基本上就是我想要做的事:从ArrayList中抓取随机对象不是随机的

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 
    } 

但是我的输出不是随机出现的。我使用调试器,发现我的选择方法会生成一个相对较低的整数,所以它总是会输出2或1,但不会输出c或a。我无法弄清楚为什么会发生这种情况,不胜感激。

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

+2

你试过运行它'50'次的例子吗? – 2011-03-06 16:10:57

+2

另外,你是如何构建你的随机数发生器?用Random()或Random(someConstantIntegerValue)'?如果使用后者,请注意每次运行程序时都会得到相同的“随机”序列。 – 2011-03-06 16:14:00

+0

您可以创建一个完整的可运行测试程序吗?看起来你的错误不在你在这里发布的代码之外。 – 2011-03-06 16:17:07

回答

1

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

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 一:2857

只有当数字creatly不同,你应该关心。

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

+0

我将您的方法放在我的驱动程序中,并且我一直得到2在7500左右,1在2500左右,并没有提及a或c。我不知道发生了什么。在我的驱动程序中,我创建了一个静态变量Random,如下所示:static Random rnd = new Random();我不知道发生了什么事! – Isai 2011-03-06 16:31:46

+1

不是你的randomList.size()的错误呢?这些数字似乎来自randomList.size(),返回4,这是List中元素的数量。你不是使用返回Set/List中唯一元素数量的方法吗?你不是使用Set类而不是List类吗? – dtech 2011-03-06 16:36:58

+0

哇你解决了我的问题哈哈。我知道我在代码中遗漏了很多东西,但我正在编写一个地图的抽象,并且我使用了实际上比ArrayList小的地图的大小。 – Isai 2011-03-06 16:43:15

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