KickJava   Java API By Example, From Geeks To Geeks.

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


1 package com.ubermq.kernel.chooser;
2
3 import com.ubermq.kernel.*;
4 import java.util.*;
5
6 /**
7  * Chooses an object from the
8  * given ordered Collection. This implementation only
9  * works on a single Collection at a time. If
10  * the <code>choose</code> method is called with
11  * differing collections, an <code>IllegalStateException</code>
12  * will be thrown.
13  */

14 abstract class AbstractOrderedChooser
15     implements Chooser
16 {
17     int size;
18     List myList;
19
20     AbstractOrderedChooser()
21     {
22         reset();
23     }
24
25     public void reset()
26     {
27         size = 0;
28         myList = null;
29     }
30
31     /**
32      * Chooses the next object in
33      * the collection, wrapping to the beginning
34      * of the collection if necessary. The
35      * collection must be an instance of <code>List</code>,
36      * because the sequential nature of this algorithm
37      * requires an ordered collection.<P>
38      *
39      * The initial call may return any of the
40      * items in the Collection, not just the first.<P>
41      *
42      * @param objects a List of objects
43      * @return an Object r, such that <code>objects.contains(r)</code> is true.
44      * @throws IllegalStateException if the chooser can
45      * only operate on a single Collection object, and
46      * the Collection does not match that of the previous
47      * caller.
48      */

49     public Object JavaDoc choose(Collection objects)
50     {
51         if (!(objects instanceof List))
52             throw new IllegalArgumentException JavaDoc("Collection must implement List.");
53
54         // check our state. set my collection if empty.
55
if (myList == null)
56         {
57             myList = (List)objects;
58             size = myList.size();
59         }
60
61         // ok return the item.
62
if (myList == objects)
63         {
64             return choose();
65         }
66         else
67         {
68             throw new IllegalStateException JavaDoc();
69         }
70     }
71
72     /**
73      * Chooses an object from the collection.
74      */

75     abstract Object JavaDoc choose();
76 }
77
Popular Tags