import java.util.*; import java.lang.*; // A bounded (fixed size) queue of objects. // The queue is FILO, so objects are removed in the order // they were inserted. public class BoundedQueue { // Extra checking done on preconditions: private static final boolean _PRECHECK = Boolean.getBoolean("PreCheck"); private final Object _rep[]; // Representation of queue as a fixed-size array private int _front = 0; // Extraction point private int _back = -1; // Insertion point private final int _size; // Size of _rep private int _count = 0; // Number of objects stored in _rep // Constructs a bounded queue of given positive size. // Requires a size >= 0. public BoundedQueue(int size) { if (_PRECHECK) if (size < 0) throw new InternalError("Negative size"); _size = size; _rep = new Object[_size]; _back = _size - 1; } // Tells if queue is empty. public boolean isEmpty() { return _count==0; } // Tells if queue is full. public boolean isFull() { return _count == _size; } // Returns number of objects in queue. public int getCount() { return _count; } // Puts a new object into the queue. // Requires: e is non-null and queue is not full. public void push(Object e) { if (_PRECHECK) { if (e==null) throw new InternalError("Null object"); if (isFull()) throw new InternalError("Full queue"); } _back = (_back + 1) % _size; _rep[_back] = e; ++_count; } // Removes and returns an object from the queue. // Requires: Queue is not empty. public Object pop() { if (_PRECHECK) if (isEmpty()) throw new InternalError("pop on empty queue"); Object result = null; result = _rep[_front]; _rep[_front] = null; _front = (_front + 1) % _size; --_count; return result; } // Test driver: public static void main(String argv[]) { BoundedQueue queue = new BoundedQueue(10); for (int i=0; !queue.isFull(); ++i) { queue.push(new Integer(i)); System.out.println("put: "+i); } while (!queue.isEmpty()) { System.out.println("get: "+queue.pop()); } } }