Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package queueopgaver;
- import java.util.NoSuchElementException;
- /**
- * An implementation of a queue as a array.
- */
- public class ArrayQueue implements QueueI {
- private Object[] elements;
- private int currentSize;
- private int head;
- private int tail;
- /**
- * Constructs an empty queue.
- */
- public ArrayQueue() {
- final int INITIAL_SIZE = 10;
- elements = new Object[INITIAL_SIZE];
- currentSize = 0;
- head = 0;
- tail = 0;
- }
- /**
- * Checks whether this queue is empty.
- *
- * @return true if this queue is empty
- */
- @Override
- public boolean isEmpty() {
- return currentSize == 0;
- }
- /**
- * Adds an element to the tail of this queue.
- *
- * @param newElement the element to add
- */
- @Override
- public void enqueue(Object newElement) {
- growIfNecessary();
- currentSize++;
- elements[tail] = newElement;
- tail = tail + 1;
- }
- /**
- * Removes an element from the head of this queue.
- *
- * @return the removed element
- */
- @Override
- public Object dequeue() {
- if (currentSize == 0) {
- throw new NoSuchElementException();
- }
- Object removed = elements[head];
- head = head + 1;
- currentSize--;
- return removed;
- }
- /**
- * Grows the element array if the current size equals the capacity.
- */
- public void growIfNecessary() {
- if (currentSize == elements.length) {
- Object[] newElements = new Object[2 * elements.length];
- for (int i = 0; i < elements.length; i++) {
- newElements[i] = elements[head + i];
- }
- elements = newElements;
- head = 0;
- tail = currentSize;
- }
- }
- /**
- * Returns the head of this queue. The queue is unchanged.
- *
- * @return the head element
- */
- @Override
- public Object getFront() {
- if (head < 0) {
- throw new NoSuchElementException();
- }
- return elements[head];
- }
- /**
- * The number of elements on the queue.
- *
- * @return the number of elements in the queue
- */
- @Override
- public int size() {
- return currentSize;
- }
- }
Add Comment
Please, Sign In to add comment