1

I have an arraylist full of different types of an object. (i.e an objects that extend a superobject)

an example is:

{object1, object1, object2, object3}

Now what I need to do is effectively pull a random object out of the array list. If it matches a set of criteria it will then run a method of this object. Otherwise it will run again till it finds an object till it does.

Now the reason why I can't just go over the objects from start to finish is because I need to provide some form of distribution.

How would I go about this? I know how to iterate over an array list, but Randomly inspecting an object in an array is out of my scope.

chostwales
  • 89
  • 2
  • 9
  • 1
    `Collections.shuffle` probably? See this [question](http://stackoverflow.com/questions/1519736/random-shuffling-of-an-array) –  Nov 19 '14 at 20:52

3 Answers3

0

Instead of picking random elements, shuffle the array once and then iterate over the result:

Collections.shuffle(objects);    
for (Object o : objects) {
  // you are now accessing objects in random order
}
LeffeBrune
  • 3,441
  • 1
  • 23
  • 36
0

This is quite easy using the Random class. Since I don't know what object you are working with, I'll show you an example where you want to randomly search a list of integers until you find one that is less than 10.

ArrayList<int> list = new ArrayList<int>();
Random random = new Random();

do{
int randomlyChosenInt = list.get(random.nextInt(list.Size()));
while(int >= 10);
Stromata
  • 245
  • 4
  • 9
0

One way is to shuffle with Collections.shuffle(), then iterate.

Another way is to pick a random element, swap it with the last one, remove it from list and then check. The advantage is that you don't have to swap N time like shuffle does - you only swap until you found a satisfactory element.