Consider a new kind of queue that allows only a single copy of an object in the
ID: 3566388 • Letter: C
Question
Consider a new kind of queue that allows only a single copy of an object in the queue. If an object is added to the queue, but it is already there, leave the queue unchanged. This queue has another operation moveToBack that takes an object in the queue and moves it to the back. If an object is not in the queue, the operation adds it at the back of the queue.
Create an interface NoDuplicatesQueueInterface that extends QueueInterface and save as NoDuplicatesQueueInterfaceYourLastName.java. Then write an array-based implementation of NoDuplicatesQueue and save as NoDuplicatesQueueYourLastName.java. Finally, write a program that adequately demonstrates your new class and save asDriverYourLastName.java.
Explanation / Answer
import java.util.*;
public interface NoDupQueueInterface<T> extends QueueInterface<T>
{
private T[] queue = new T[DEFAULT_CAPACITY];
private int front = 0;
private int back = 0;
private static final int DEFAULT_CAPACITY = 20;
public NoDupQueueInterface()
{
this(DEFAULT_CAPACITY);
}
public NoDupQueueInterface(int initialCapacity)
{
@SuppressWarnings("unchecked")
T[] tempQueue = (T[]) new Object[initialCapacity + 1];
queue = tempQueue;
front = 0;
back = initialCapacity;
}
public boolean duplicateTest(T newEntry)
{
if (size == queue.length)
throw new IllegalStateException();
else
{
for(int i=0; i<queue.length; i++)
{
if(queue[i] == newEntry)
{
System.out.println("Im not doing anything, youre already in line " + newEntry + "!");
return true;
}//end if
else
{
System.out.println("Youre not in line yet...I will add you at the back!");
return false;
}//end else
}//end for
}//end else
}//end duplicateTest
public void enqueue(T nonDupEntry)
{
boolean dupTest = duplicateTest(nonDupEntry);
if(dupTest==true)
{
// Add to rear
size ++;
queue[back] = nonDupEntry;
back ++;
// If at end of array, wrap around
if (back == queue.length)
back = 0;
}//end if
else
System.out.println("Sorry that number is already in line");
}//end enqueue
}//end class
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.