KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ubermq > kernel > chooser > RandomChooser


1 package com.ubermq.kernel.chooser;
2
3 import com.ubermq.kernel.*;
4 import java.util.*;
5
6 /**
7  * Chooses an object at random. This
8  * is a stateless, immutable Chooser
9  * implementation.
10  */

11 public class RandomChooser
12     implements Chooser
13 {
14     private static final Random r = new Random();
15
16     public void reset()
17     {
18     }
19
20     /**
21      * Chooses a single object contained in the
22      * given <code>Collection</code> at random,
23      * and returns it. <P>
24      *
25      * This chooser can operate on multiple
26      * Collection instances independently.
27      *
28      * @param objects a List of objects
29      * @return an Object r, such that <code>objects.contains(r)</code> is true.
30      */

31     public Object JavaDoc choose(Collection objects)
32     {
33         int index = r.nextInt(objects.size());
34
35         if (objects instanceof List) {
36             return ((List)objects).get(index);
37         } else {
38             Iterator iter = objects.iterator();
39             for (int i = 0; i < index; i++)
40             {
41                 iter.next();
42             }
43             return iter.next();
44         }
45     }
46
47 }
48
Popular Tags