// Name:
Bradley Shedd
// Program: LAB#11
// Date: December
1, 2010
// Class: Java1302
// Filename: ArrayQueue.java
// Purpose: This class is an
array-based implementation of
//
the classic FIFO queue interface.
// ****************************************************************
public
class ArrayQueue
implements
QueueADT
{
private
int DEFAULT_SIZE = 5;
private
Object[] elements;
private
int numElements;
private
int front, back;
//---------------------------------------------
// Constructor; creates array of default size.
//---------------------------------------------
public
ArrayQueue()
{
elements =
new
Object[DEFAULT_SIZE];
numElements = 0;
front
= 0;
back = -1;
}
//---------------------------------------------
// Puts item on end of queue.
//---------------------------------------------
public
void enqueue(Object item)
{
if
(isFull())
increaseSize();
elements[( back + 1 ) % DEFAULT_SIZE] = item;
back++;
numElements++;
}
//---------------------------------------------
// Removes and returns object from front of queue.
//---------------------------------------------
public
Object dequeue()
{
if
(isEmpty())
System.err.println("This
queue is empty!");
front++;
numElements--;
return
elements [front-1];
}
//---------------------------------------------
// Returns true if queue is empty.
//---------------------------------------------
public
boolean isEmpty()
{
return
numElements==0;
}
//---------------------------------------------
// Returns true if queue is full, but it never is.
//---------------------------------------------
public
boolean isFull()
{
return
numElements==DEFAULT_SIZE;
}
//---------------------------------------------
// Returns the number of elements in the queue.
//---------------------------------------------
public
int size()
{
return
numElements;
}
private
void increaseSize()
{
Object [] temp =
new
Object [ 2 * elements.length];
for
(
int i = 0; i < elements.length;
++i)
temp [i] = elements [ (i + front)% elements.length];
elements = temp;
front = 0;
back
= DEFAULT_SIZE - 1;
// assumes front and rear start at 0 and -1
DEFAULT_SIZE *= 2;
}
//---------------------------------------------
// Returns a string containing the elements of the queue
// from first to last
//---------------------------------------------
public
String toString()
{
String result =
"\n";
for
(int i = front, count=0; count <
numElements;
i=(i+1)%elements.length,count++)
result = result + elements[i]+
"\n";
return
result;
}
}