Grabbing random object from ArrayList is not random.

Posted by Isai on Stack Overflow See other posts from Stack Overflow or by Isai
Published on 2011-03-06T16:07:04Z Indexed on 2011/03/06 16:10 UTC
Read the original article Hit count: 293

Filed under:
|
|
|

I am creating a method where if you pass in a parameter of type Random, then it will return a random object. Here is basically what I am trying to do:

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

The random list has this the following strings:[2, 2, 2, 1, 1, 1, 1, c, c, c, a, a, a, a]

Then I made a driver with the following code

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

However my outputs are not coming out random. I used the debugger and found out that my choose method generates an integer that is relatively low, so it will always print out either 2's or 1's but never c's or a's. I can't figure out why this is happening and help would be greatly appreciated.

© Stack Overflow or respective owner

Related posts about java

Related posts about list