After learning about linked list implementations of a queue I was asked to try a resizing array implementation. I'm looking for constructive criticism.
import java.util.NoSuchElementException;
/**
* ResizingQueue - Resizing Array Implementation.
*
* @author Rocky
* @version 2016-05-31
*/
public class ResizingQueue<Item> {
private Item[] queue;
private int size;
private int index;
public ResizingQueue() {
queue = (Item[]) new Object[1];
size = 0;
index = 0;
}
/**
* Returns the size of the queue
*
* @return Integer representing the number of items in the queue
*/
public int size() {
return this.size;
}
/**
* Returns whether or not the queue is empty
*
* @return True if the queue is empty
*/
public boolean isEmpty(){
return size == 0;
}
/**
* Adds an item onto the end of the queue. If the size of the queue reaches
* the length of the array, the length of the array is doubled.
*
* @param item Item to be added. Must not be null
* @throws NullPointerException if the parameter item is null
*/
public void enqueue(Item item) {
if (item == null) {
throw new NullPointerException("Item must not be null");
}
if (size == queue.length) {
resize(2 * queue.length);
}
queue[size + index] = item;
size++;
}
/**
* Removes and returns the item at the front of the queue. If the size of
* the queue reaches 25% of the length of the array, the length of the array
* is halved.
*
* @return Item at the front of the queue
* @throws NoSuchElementException if dequeue() is called while the queue is
* empty
*/
public Item dequeue() {
if (isEmpty()) {
throw new NoSuchElementException("There is nothing in the queue");
}
if (size < queue.length / 4) {
resize(queue.length / 2);
index = 0;
}
Item item = queue[index];
queue[index++] = null;
size--;
return item;
}
/**
* Resizes the array when capacity reaches 100% or 25%
*
* @param capacity New capacity for the array
*/
private void resize(int capacity) {
Item[] copy = (Item[]) new Object[capacity];
for (int i = 0; i < size; i++) {
copy[i] = queue[i + index];
}
queue = copy;
}
}