KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hsqldb > lib > HsqlArrayHeap


1 /* Copyright (c) 2001-2005, The HSQL Development Group
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  * Redistributions of source code must retain the above copyright notice, this
8  * list of conditions and the following disclaimer.
9  *
10  * Redistributions in binary form must reproduce the above copyright notice,
11  * this list of conditions and the following disclaimer in the documentation
12  * and/or other materials provided with the distribution.
13  *
14  * Neither the name of the HSQL Development Group nor the names of its
15  * contributors may be used to endorse or promote products derived from this
16  * software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
22  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */

30
31
32 package org.hsqldb.lib;
33
34 /**
35  * An HsqlHeap implementation backed by an array of objects and an
36  * {@link ObjectComparator ObjectComparator}. This implementation
37  * is non-blocking, dynamically resizing and thread-safe.
38  *
39  * @author boucherb@users
40  * @version 1.7.2
41  * @since 1.7.2
42  */

43 public class HsqlArrayHeap implements HsqlHeap {
44
45 // --------------------------------- members -----------------------------------
46
protected ObjectComparator oc;
47     protected int count;
48     protected Object JavaDoc[] heap;
49
50 // ------------------------------ constructors ---------------------------------
51

52     /**
53      * Creates a new HsqlArrayHeap with the given initial capacity, using
54      * the specified ObjectComparator to maintain the heap invariant.
55      *
56      * @exception IllegalArgumentException if capacity less or equal to zero
57      * or comparator is null
58      */

59     public HsqlArrayHeap(int capacity,
60                          ObjectComparator comparator)
61                          throws IllegalArgumentException JavaDoc {
62
63         if (capacity <= 0) {
64             throw new IllegalArgumentException JavaDoc("" + capacity);
65         }
66
67         if (comparator == null) {
68             throw new IllegalArgumentException JavaDoc("null comparator");
69         }
70
71         heap = new Object JavaDoc[capacity];
72         oc = comparator;
73     }
74
75 // /** Copy constructor (optional) */
76
// public HsqlArrayHeap(HsqlArrayHeap other) {
77
// count = other.count;
78
// oc = other.oc;
79
// heap = new Object[count];
80
// System.arraycopy(other.heap,0, heap, 0, count);
81
// }
82
// -------------------------- interface Implementation -------------------------
83
public synchronized void clear() {
84
85         for (int i = 0; i < count; ++i) {
86             heap[i] = null;
87         }
88
89         count = 0;
90     }
91
92     public synchronized void add(Object JavaDoc o)
93     throws IllegalArgumentException JavaDoc, RuntimeException JavaDoc {
94
95         int ci; // current index
96
int pi; // parent index
97

98         if (o == null) {
99             throw new IllegalArgumentException JavaDoc("null element");
100         }
101
102         if (isFull()) {
103             throw new RuntimeException JavaDoc("full");
104         }
105
106         if (count >= heap.length) {
107             increaseCapacity();
108         }
109
110         ci = count;
111
112         count++;
113
114         do {
115             if (ci <= 0) {
116                 break;
117             }
118
119             pi = (ci - 1) >> 1;
120
121             try {
122                 if (oc.compare(o, heap[pi]) >= 0) {
123                     break;
124                 }
125             } catch (Exception JavaDoc e) {
126                 throw new IllegalArgumentException JavaDoc(e.toString());
127             }
128
129             heap[ci] = heap[pi];
130             ci = pi;
131         } while (true);
132
133         heap[ci] = o;
134     }
135
136     public synchronized boolean isEmpty() {
137         return count == 0;
138     }
139
140     public synchronized boolean isFull() {
141
142         // almost impossible for this to happen
143
return count == Integer.MAX_VALUE;
144     }
145
146     public synchronized Object JavaDoc peek() {
147         return heap[0];
148     }
149
150     public synchronized Object JavaDoc remove() {
151
152         int ci; // current index
153
int li; // left index
154
int ri; // right index
155
int chi; // child index
156
Object JavaDoc co;
157         Object JavaDoc ro;
158
159         if (count == 0) {
160             return null;
161         }
162
163         ci = 0;
164         ro = heap[ci];
165
166         count--;
167
168         if (count == 0) {
169             heap[0] = null;
170
171             return ro;
172         }
173
174         co = heap[count];
175         heap[count] = null;
176
177         do {
178             li = (ci << 1) + 1;
179
180             if (li >= count) {
181                 break;
182             }
183
184             ri = (ci << 1) + 2;
185             chi = (ri >= count || oc.compare(heap[li], heap[ri]) < 0) ? li
186                                                                       : ri;
187
188             if (oc.compare(co, heap[chi]) <= 0) {
189                 break;
190             }
191
192             heap[ci] = heap[chi];
193             ci = chi;
194         } while (true);
195
196         heap[ci] = co;
197
198         return ro;
199     }
200
201     public synchronized int size() {
202         return count;
203     }
204
205 // ------------- standard object and collection methods (optional) -------------
206
// public synchronized Object clone() throws CloneNotSupportedException {
207
// return new HsqlArrayHeap(this);
208
// }
209
//
210
// public synchronized java.util.Enumeration elements() {
211
//
212
// Object[] elements;
213
//
214
// elements = new Object[count];
215
//
216
// System.arraycopy(heap, 0, elements, 0, count);
217
//
218
// return new HsqlEnumeration(elements);
219
// }
220
//
221
// public synchronized boolean equals(Object o) {
222
//
223
// HsqlArrayHeap other;
224
// HsqlArrayHeap thiscopy;
225
// HsqlArrayHeap othercopy;
226
//
227
// if (this == o) {
228
// return true;
229
// }
230
//
231
// if (!(o instanceof HsqlArrayHeap)) {
232
// return false;
233
// }
234
//
235
// other = (HsqlArrayHeap) o;
236
//
237
// if (count != other.size()) {
238
// return false;
239
// }
240
//
241
// // this is a bit "iffy"... non-equal comparators _might_ still
242
// // be _equivalent_ under current element content...
243
//
244
// if (!oc.equals(other.oc)) {
245
// return false;
246
// }
247
//
248
// thiscopy = new HsqlArrayHeap(this);
249
// othercopy = new HsqlArrayHeap(other);
250
//
251
// while(!thiscopy.isEmpty()) {
252
// if (!thiscopy.remove().equals(othercopy.remove())) {
253
// return false;
254
// }
255
// }
256
//
257
// return true;
258
// }
259
//
260
// public synchronized Object[] toArray(Object a[]) {
261
//
262
// if (a == null) {
263
// a = new Object[count];
264
// } else if ( a.length < count) {
265
// a = (Object[]) java.lang.reflect.Array.newInstance(
266
// a.getClass().getComponentType(), count);
267
// }
268
//
269
// System.arraycopy(heap, 0, a, 0, count);
270
//
271
// for (int i = count; i < a.length; i++) {
272
// a[i] = null;
273
// }
274
//
275
// return a;
276
// }
277
//
278
public synchronized String JavaDoc toString() {
279
280         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
281
282         sb.append(super.toString());
283         sb.append(" : size=");
284         sb.append(count);
285         sb.append(' ');
286         sb.append('[');
287
288         for (int i = 0; i < count; i++) {
289             sb.append(heap[i]);
290
291             if (i + 1 < count) {
292                 sb.append(',');
293                 sb.append(' ');
294             }
295         }
296
297         sb.append(']');
298
299         return sb.toString();
300     }
301
302 //
303
// public void trim() {
304
//
305
// Object[] oldheap;
306
//
307
// oldheap = heap;
308
//
309
// heap = new Object[count == 0 ? 16 : count];
310
//
311
// System.arraycopy(oldheap, 0, heap, 0, count);
312
// }
313
// -------------------- internal implementation methods ------------------------
314
private void increaseCapacity() {
315
316         Object JavaDoc[] oldheap;
317
318         // no handling of boundary conditions.
319
// In the highly unlikely event of a rollover,
320
// in theory, an exception will be thrown (negative array index in
321
// array allocation?)
322
oldheap = heap;
323
324         // as per java collections, v.s. JDK 1.1 java util.
325
heap = new Object JavaDoc[3 * heap.length / 2 + 1];
326
327         System.arraycopy(oldheap, 0, heap, 0, count);
328     }
329
330 // ------------------------------- tests ---------------------------------------
331
// public static void main(String[] args) {
332
//
333
// ObjectComparator oc = new ObjectComparator() {
334
//
335
// public int compare(Object a, Object b) {
336
//
337
// if (a == b) {
338
// return 0;
339
// }
340
//
341
// // null==null and smaller than any value
342
// if (a == null) {
343
// if (b == null) {
344
// return 0;
345
// }
346
//
347
// return -1;
348
// }
349
//
350
// if (b == null) {
351
// return 1;
352
// }
353
//
354
// return ((Integer) a).intValue() - ((Integer) b).intValue();
355
// }
356
// };
357
// HsqlHeap ah = new HsqlArrayHeap(6, oc);
358
//
359
// System.out.println("isEmpty() : " + ah.isEmpty());
360
//
361
// int[] ai = new int[] {
362
// 3, 99, 7, 9, -42, 2, 1, 23, -7
363
// };
364
// int least = Integer.MIN_VALUE;
365
//
366
// for (int i = 0; i < ai.length; i++) {
367
// System.out.println("add() : new Integer(" + ai[i] + ")");
368
// ah.add(new Integer(ai[i]));
369
// System.out.println("size() : " + ah.size());
370
// }
371
//
372
// while (ah.size() > 0) {
373
// int current = ((Integer) ah.remove()).intValue();
374
//
375
// if (current < least) {
376
// throw new RuntimeException("bad heap invariant");
377
// }
378
//
379
// least = current;
380
//
381
// System.out.println("remove() : " + current);
382
// System.out.println("size() : " + ah.size());
383
// }
384
//
385
// System.out.println("peak() : " + ah.peek());
386
// System.out.println("isEmpty() : " + ah.isEmpty());
387
// System.out.println("remove() : " + ah.remove());
388
// System.out.println("size() : " + ah.size());
389
// System.out.println("isEmpty() : " + ah.isEmpty());
390
// }
391
}
392
Popular Tags