1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.onemind.commons.java.datastructure;
22
23 import java.util.*;
24 /***
25 * Represent a list of counters with a queue per counter objectYou can queue and dequeue to a counter identified by a counter object.
26 * NOTE: This class is not thread-safe
27 * @author TiongHiang Lee (thlee@onemindsoft.org)
28 * @version $Id: CounterQueue.java,v 1.3 2005/04/26 17:41:24 thlee Exp $ $Name: $
29 */
30 public class CounterQueue
31 {
32
33 /*** the counters * */
34 private HashMap _counters = new HashMap();
35
36 /***
37 * {@inheritDoc}
38 */
39 public CounterQueue()
40 {
41 }
42
43 /***
44 * Get the list for the counter object
45 * @param o the counter object
46 * @return the list, or null if there's none
47 */
48 private List _getList(Object o)
49 {
50 if (_counters.containsKey(o))
51 {
52 return (List) _counters.get(o);
53 } else
54 {
55 return null;
56 }
57 }
58
59 /***
60 * Get the (unmodifiable) queue of the counter object
61 * @param o the counter object
62 * @return the queue
63 */
64 public List getQueue(Object o)
65 {
66 if (_counters.containsKey(o))
67 {
68 return Collections.unmodifiableList((List) _counters.get(o));
69 } else
70 {
71 return Collections.EMPTY_LIST;
72 }
73 }
74
75 /***
76 * Clear the queue of the counter object
77 * @param o the counter object
78 * @return the queue for the counter object
79 */
80 public List clearQueue(Object o)
81 {
82 Object queue = _counters.remove(o);
83 if (queue != null)
84 {
85 return (List) queue;
86 } else
87 {
88 return Collections.EMPTY_LIST;
89 }
90 }
91
92 /***
93 * Add an queuer to the queue of the counter object. A queue will be created if there's none for the counter object
94 * @param o the counter object
95 * @param queuer the queue
96 * @return true
97 */
98 public boolean addToQueue(Object o, Object queuer)
99 {
100 List l = _getList(o);
101 if (l == null)
102 {
103 l = new ArrayList();
104 _counters.put(o, l);
105 }
106 return l.add(queuer);
107 }
108
109 /***
110 * Remove the next queuer in the queue. Null if queue is empty
111 * @param counter the counter
112 * @return the next queuer in the counter, or null if queue is empty
113 */
114 public Object removeNextFromQueue(Object counter)
115 {
116 List l = _getList(counter);
117 if (l == null || l.size() == 0)
118 {
119 return null;
120 } else
121 {
122 return l.remove(0);
123 }
124 }
125
126 /***
127 * Remove the queuer from the queue of the counter object. If there's no queue for the counter object, it will do nothing and
128 * return false.
129 * @param o the counter object
130 * @param queuer the queuer
131 * @return true if list contains the element
132 */
133 public boolean removeFromQueue(Object o, Object queuer)
134 {
135 List l = _getList(o);
136 if (l != null)
137 {
138 return l.remove(queuer);
139 } else
140 {
141 return false;
142 }
143 }
144 }