KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > jmx > remote > internal > ArrayQueue


1 /*
2  * @(#)ArrayQueue.java 1.6 05/08/31
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package com.sun.jmx.remote.internal;
9
10 import java.util.AbstractList JavaDoc;
11 import java.util.Iterator JavaDoc;
12
13 public class ArrayQueue<T> extends AbstractList JavaDoc<T> {
14     public ArrayQueue(int capacity) {
15     this.capacity = capacity + 1;
16     this.queue = (T[]) new Object JavaDoc[capacity + 1];
17     this.head = 0;
18     this.tail = 0;
19     }
20
21     public void resize(int newcapacity) {
22     int size = size();
23     if (newcapacity < size)
24         throw new IndexOutOfBoundsException JavaDoc("Resizing would lose data");
25     newcapacity++;
26     if (newcapacity == this.capacity)
27         return;
28     T[] newqueue = (T[]) new Object JavaDoc[newcapacity];
29     for (int i = 0; i < size; i++)
30         newqueue[i] = get(i);
31     this.capacity = newcapacity;
32     this.queue = newqueue;
33     this.head = 0;
34     this.tail = size;
35     }
36
37     public boolean add(T o) {
38     queue[tail] = o;
39     int newtail = (tail + 1) % capacity;
40     if (newtail == head)
41         throw new IndexOutOfBoundsException JavaDoc("Queue full");
42     tail = newtail;
43     return true; // we did add something
44
}
45
46     public T remove(int i) {
47     if (i != 0)
48         throw new IllegalArgumentException JavaDoc("Can only remove head of queue");
49     if (head == tail)
50         throw new IndexOutOfBoundsException JavaDoc("Queue empty");
51     T removed = queue[head];
52     queue[head] = null;
53     head = (head + 1) % capacity;
54     return removed;
55     }
56
57     public T get(int i) {
58     int size = size();
59     if (i < 0 || i >= size) {
60         final String JavaDoc msg = "Index " + i + ", queue size " + size;
61         throw new IndexOutOfBoundsException JavaDoc(msg);
62     }
63     int index = (head + i) % capacity;
64     return queue[index];
65     }
66
67     public int size() {
68     // Can't use % here because it's not mod: -3 % 2 is -1, not +1.
69
int diff = tail - head;
70     if (diff < 0)
71         diff += capacity;
72     return diff;
73     }
74
75     private int capacity;
76     private T[] queue;
77     private int head;
78     private int tail;
79 }
80
Popular Tags