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