Source of BoundedQueue.java


  1: public class BoundedQueue {
  2: 
  3:     protected Object rep[];
  4:     protected int front = 0;
  5:     protected int back = -1;
  6:     protected int size = 0;
  7:     protected int count = 0;
  8: 
  9:     public BoundedQueue(int size) {
 10:         if (size > 0) {
 11:             this.size = size;
 12:             rep = new Object[size];
 13:             back = size - 1;
 14:         }
 15:     }
 16: 
 17:     public boolean isEmpty() {
 18:         return (count == 0);
 19:     }
 20: 
 21:     public boolean isFull() {
 22:         return (count == size);
 23:     }
 24: 
 25:     public int getCount() {
 26:         return count;
 27:     }
 28: 
 29:     public void put(Object e) {
 30:         if (e != null && !isFull()) {
 31:             back++;
 32:             if (back >= size)
 33:                 back = 0;
 34:             rep[back] = e;
 35:             count++;
 36:         }
 37:     }
 38: 
 39:     public Object get() {
 40:         Object result = null;
 41:         if (!isEmpty()) {
 42:             result = rep[front];
 43:             rep[front] = null;
 44:             front++;
 45:             if (front >= size)
 46:                 front = 0;
 47:             count--;
 48:         }
 49:         return result;
 50:     }
 51: 
 52:     public static void main(String args[]) {
 53:         BoundedQueue queue = new BoundedQueue(10);
 54:         for (int i = 0; !queue.isFull(); i++) {
 55:             queue.put(new Integer(i));
 56:             System.out.println("put: " + i);
 57:         }
 58:         while (!queue.isEmpty()) {
 59:             System.out.println("get: " + queue.get());
 60:         }
 61:     }
 62: }