Question: Complete if (isFull (), public T getFront(), public boolean isEmpty(), public void clear(). The code for isFull and isEmpty uses the condition of a full

Complete if (isFull (), public T getFront(), public boolean isEmpty(), public void clear().

The code for isFull and isEmpty uses the condition of a full queue is:

frontIndex ==(backIndex+2)%capcacity.

The same consideration yields the condition for an empty queue:

frontIndex ==(backIndex+1)%capcacity.

Here is the code:

public class ArrayQueue implements QueueInterface{

private T[] queuearr;

private int frontIndex;

private int backIndex;

private int capacity;

private static final int DEFAULT_CAPACITY = 10;

@SuppressWarnings ("unchecked")

public ArrayQueue (int capacity) {

T[] temp = (T[]) new Object [capacity];

queuearr = temp;

this.capacity = capacity;

frontIndex = 0;

backIndex = capacity - 1;

}

public ArrayQueue () {

this(DEFAULT_CAPACITY);

}

@Override

public void enqueue(T newEntry) {

backIndex = (backIndex + 1) % capacity;

queuearr [ backIndex] = newEntry;

if (isFull ())

// Need to fix

ensureCapacity();

}

private void ensureCapacity() {

T[] oldQueue = queuearr;

T[] temparray = (T[]) new Object[2*capacity];

int index;

for (index = 0; index < capacity; index ++){

temparray[index] = oldQueue[(frontIndex + index)%capacity ];

oldQueue[(frontIndex + index)%capacity]= null;

}

frontIndex = 0;

backIndex = capacity - 2;

capacity *= 2;

queuearr = temparray;

}

@Override

public T dequeue() {

if (isEmpty ())

throw new EmptyQueueException ();

T front = queuearr [ frontIndex] ;

queuearr [ frontIndex] = null; // mark for garbage

//collection

frontIndex = (frontIndex +1) % capacity;

if (isEmpty () ) {

frontIndex = 0;

if (capacity > DEFAULT_CAPACITY )

capacity = DEFAULT_CAPACITY;

queuearr = (T[]) new Object[capacity];

backIndex = capacity - 1;

}

return front;

}

@Override

public T getFront() {

// TODO Auto-generated method stub

}

@Override

public boolean isEmpty() {

// TODO Auto-generated method stub

return false;

}

@Override

public void clear() {

// TODO Auto-generated method stub

}

public static void main(String[] args) {

ArrayQueue squeue = new ArrayQueue<>();

if(!squeue.isEmpty())

System.out.println(squeue.getFront());

squeue.enqueue ("A");

System.out.println(squeue.getFront());

squeue.enqueue("B");

squeue.enqueue("C");

squeue.enqueue("D");

while(!squeue.isEmpty())

System.out.print(squeue.dequeue() + " ");

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!