frosty
frosty

Reputation: 317

How to randomly choose one of many objects to be added to an array list?

Say I have 4 objects and I am looking to populate an arraylist of 100 elements with these four objects. Basically each time we add an elements to the arraylist, there is a 1 in 4 chance each element will be chosen. I thought of one way to do it but I think there is a better, more "pretty" & effective way

just rough pseudo-code to help explain

for(int i = 0; i != 100; i++){
    Random generator = new Random();
    int i = generator.nextInt(4); // this will give us 0,1,2,or 3
        if(i ==0){
            arraylist.add(object1(param1, param2));
        }
    // etc.. continues with 3 other else if statments and objects 

ideas? All the other objects I have also share the same interface, if that can help us

Upvotes: 0

Views: 1938

Answers (1)

Mike Laren
Mike Laren

Reputation: 8188

Start with an array containing the four objects:

Object[] objects = new Object[] {
  object1(param1, param2),
  object2(param1),
  object3(param1, param2, param3, param4),
  object4(param1, param2)
}

Then adjust your code:

Random generator = new Random();
for(int i = 0; i < 100; i++){
  int j = generator.nextInt(4); // this will give us 0,1,2,or 3
  arraylist.add(objects[j]);
  // etc.. continues with 3 other else if statments and objects
}

Notice that you don't have to create a new generator on every iteration - you can create it just once and reuse the same instance.

Upvotes: 1

Related Questions