package queues; import java.util.Enumeration; /** * A queue implemented using arrays. * * Version 1. * * @author Alan L. Cox * @since 03/15/01 */ public class ArrayVers1Queue implements IQueue { private int _firstEmptyObject = 0; private Object[] _objects = new Object[1]; /** * @param object the object to enqueue */ public void enqueue(Object object) { if (_firstEmptyObject == _objects.length) { int j; Object[] newObjects = new Object[2*_objects.length]; for (j = 0; j < _objects.length; j++) newObjects[j] = _objects[j]; _objects = newObjects; } _objects[_firstEmptyObject] = object; _firstEmptyObject++; } /** * @return the dequeued object */ public Object dequeue() { if (_firstEmptyObject == 0) throw new java.util.NoSuchElementException("The queue is empty."); Object object = _objects[0]; _firstEmptyObject--; // Java note: i's scope is limited to the for loop and its body. for (int i = 0; i < _firstEmptyObject; i++) _objects[i] = _objects[i + 1]; return object; } /** * @return an Enumeration of the queue. */ public Enumeration enumeration() { return new Enumeration() { private int _nextObject = 0; public boolean hasMoreElements() { return _nextObject < _firstEmptyObject; } public Object nextElement() { return _objects[_nextObject++]; } }; } }