1 7 8 package com.sun.jmx.remote.internal; 9 10 import java.util.AbstractList ; 11 import java.util.Iterator ; 12 13 public class ArrayQueue<T> extends AbstractList <T> { 14 public ArrayQueue(int capacity) { 15 this.capacity = capacity + 1; 16 this.queue = (T[]) new Object [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 ("Resizing would lose data"); 25 newcapacity++; 26 if (newcapacity == this.capacity) 27 return; 28 T[] newqueue = (T[]) new Object [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 ("Queue full"); 42 tail = newtail; 43 return true; } 45 46 public T remove(int i) { 47 if (i != 0) 48 throw new IllegalArgumentException ("Can only remove head of queue"); 49 if (head == tail) 50 throw new IndexOutOfBoundsException ("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 msg = "Index " + i + ", queue size " + size; 61 throw new IndexOutOfBoundsException (msg); 62 } 63 int index = (head + i) % capacity; 64 return queue[index]; 65 } 66 67 public int size() { 68 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 |