1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.util;
21
22 import java.util.Iterator;
23 import java.util.LinkedList;
24 import java.util.ListIterator;
25
26 /***
27 * A list of {@link Object} objects that is sorted descending by priority.
28 *
29 * <p>This class is thread safe.
30 */
31 public class PriorityQueue
32 {
33
34
35
36
37
38 protected LinkedList queue = new LinkedList();
39
40
41
42 public PriorityQueue()
43 {
44 }
45
46
47
48 private synchronized void add(Item e)
49 {
50 boolean inserted = false;
51 for (ListIterator i = queue.listIterator();
52 i.hasNext() && !inserted;) {
53 if (e.priority > ((Item)i.next()).priority) {
54 i.previous();
55 i.add(e);
56 inserted = true;
57 }
58 }
59
60 if (!inserted) {
61 queue.add(e);
62 }
63 }
64
65 /***
66 * Adds <code>o</code>.
67 */
68 public synchronized void add(Object o, int priority)
69 {
70 Item e = new Item(o, priority);
71 add(e);
72 }
73
74 /***
75 * Adds <code>o</code> if not already in queue.
76 */
77 public synchronized boolean addUnique(Object o, int priority)
78 {
79 Item e = new Item(o, priority);
80 if (queue.contains(e)) {
81 return false;
82 }
83 else {
84 add(e);
85 return true;
86 }
87 }
88
89 public synchronized void clear()
90 {
91 queue.clear();
92 }
93
94
95
96
97
98
99
100
101
102
103
104 public synchronized boolean isEmpty()
105 {
106 return queue.isEmpty();
107 }
108
109 public synchronized Iterator iterator()
110 {
111 return new PriorityQueueIterator(queue.iterator());
112 }
113
114 /***
115 * Returns the item with the highest priority without removing it.
116 */
117 public synchronized Object peek()
118 {
119 return ((Item)queue.getFirst()).o;
120 }
121
122 /***
123 * Removes and returns the item with the highest priority.
124 */
125 public synchronized Object pop()
126 {
127 if (queue.size() == 0) {
128 return null;
129 }
130 return ((Item)queue.removeFirst()).o;
131 }
132
133 public synchronized boolean remove(Object o)
134 {
135 return queue.remove(new Item(o));
136 }
137
138 public synchronized int size()
139 {
140 return queue.size();
141 }
142
143
144
145
146
147
148
149
150
151
152
153 private class Item
154 {
155 public Object o;
156 public int priority;
157
158 public Item(Object o, int priority)
159 {
160 this.o = o;
161 this.priority = priority;
162 }
163
164 public Item(Object o)
165 {
166 this.o = o;
167 }
168
169 public boolean equals(Object object)
170 {
171 if (object instanceof Item) {
172 return o.equals(((Item)object).o);
173 }
174
175 return false;
176 }
177
178 }
179
180 private class PriorityQueueIterator implements Iterator {
181
182 Iterator iterator;
183
184 PriorityQueueIterator(Iterator iterator)
185 {
186 this.iterator = iterator;
187 }
188
189 public boolean hasNext()
190 {
191 return iterator.hasNext();
192 }
193
194 public Object next()
195 {
196 return ((Item)iterator.next()).o;
197 }
198
199 public void remove()
200 {
201 iterator.remove();
202 }
203
204 }
205
206 }