In: Computer Science
Complete the methods in AQueue and ArrayQueue
The third pasted code is just the interface.
DO NOT CHANGE ANY CODE ONLY ADD TO THE METHODS IN THE TWO CLASSES DESCRIBED
import java.util.EmptyStackException;
import java.util.NoSuchElementException;
/**
* AQueue provides default implementations for several no-brainer methods in the IQueue interface.
* <p>
* Some methods in IQueue are pairs that do the same job, but report failure differently.
* Implement the fail-by-throwing methods here, in this abstract class,
* by calling the paired method and checking the return value, then throwing as appropriate.
* Why is defining these methods here desirable? What are some alternatives?
* <p>
* created by {@code cspfrederick} and {@code garethhalladay} Fall17 <br>
* inspired by Chris Wilcox
*/
public abstract class AQueue<E> implements IQueue<E> {
// The add method is similar to the offer method except for handling failure.
// Instead of returning false, it throws an IllegalStateException.
@Override
public void add(E item){
// code here
}
// The remove method is similar to the poll method except for handling failure.
// Instead of returning null, it throws a NoSuchElementException.
@Override
public E remove(){
return null;
}
// The element method is similar to the peek method except for handling failure.
// Instead of returning null, it throws a NoSuchElementException.
@Override
public E element(){
return null;
}
// This method should utilize the size method to return the correct result.
@Override
public boolean isEmpty() {
return false;
}
}
------------------------------------------------------------------------------------------------------------------------
import java.util.concurrent.ArrayBlockingQueue;
/**
* ArrayQueue is a FIFO (First In First Out) data structure that stores its elements
* in an array (or something like it, like an {@link java.util.ArrayList}).
* <p>
* Can we use an {@link java.util.ArrayList} to directly represent a queue? A FIFO needs to push on one end,
* and pop from the other. The tail of an {@link java.util.ArrayList} can support pop and push efficiently,
* but the front supports neither efficiently.
* <p>
* Instead, we use an array for storage, and we represent the head and tail of the queue
* with indices into that array. When one of the indices would fall off the end of the array,
* it just goes back to the start of the array. That is why this pattern is called a "circular"
* array. Read more about that <a href=../queue.html>here</a>.
* <p>
* We can think of the head and tail indices "chasing" each other around the circular
* storage. When you add an item, the tail moves. When you take an item, the head moves.
* If the head catches the tail, the queue is empty. If the tail catches the head, the queue is full.
* <p>
* That's a lot to take in, but it's easier to code than it sounds. Notice that the member variables
* "removed" and "added" are counters recording the <i>total</i> operation count. To see where the head and
* tail of the queue are, just compute:
* {@code (removed % elements.length)} or {@code (added % elements.length)}
* <p>
* by {@code cspfrederick} and {@code garethhalladay} Fall17 <br>
* inspired by Chris Wilcox
* @param <E> the type of elements held in this collection
*/
public class ArrayQueue<E> extends AQueue<E> implements IQueue<E>{
/**
* the underlying array for the queue
*/
protected E[] elements;
/**
* the total elements added (set back to zero if clear is called)
*/
protected int added = 0;
/**
* the total elements removed (set back to zero if clear is called)
*/
protected int removed = 0;
/**
* Creates a new queue backed by an array of length {@code maxSize}.
* Use {@link #newArray(int)} to create the elements array.
* @param maxSize the capacity of the queue
* @see #newArray(int)
*/
public ArrayQueue(int maxSize) {
newArray(maxSize);
}
/**
* A helper method to create a new array of the generic type.
* Read the information provided on <a href=../generics.html>generics</a>.
* It walks you through the behavior of this small method.
* @param size the size of the new array
* @return an new instance of an array of type E
*/
protected E[] newArray(int size) {
@SuppressWarnings("unchecked")
E[] arr = (E[]) new Object[size];
return arr;
}
/**
* Adds an element to the queue. If the queue is full, return false,
* otherwise add to the next available position in the queue.
* <p>
* The index of the next available position can be found by calculating
* the remainder of the total number of elements added by the length of the array.
* <p>
* Don't forget to increment the added field!
* @param e the element to add
* @return true if the element can be added, false otherwise
* @see #added
*/
@Override
public boolean offer(E e) {
if(isEmpty()) {
return false;
}
else {
for(int i = 0; i < size(); i++) {
}
}
return true;
}
/**
* Removes the oldest element (the head) from the queue, and returns it.
* If the queue is empty, return null.
* <p>
* The index of the oldest element can be determined by calculating the remainder
* of the total elements removed by the length of the array.
* <p>
* Don't forget to increment the removed field!
* <p>
* @return the oldest element in the queue, or null if the queue is empty
* @see #removed
*/
@Override
public E poll() {
return null;
}
/**
* Returns the oldest element in the queue (the element we would remove next),
* but does not remove it.
* If the queue is empty, return null.
* <p>
* The index of the oldest element can be determined by calculating the remainder
* of the total elements removed by the length of the array.
* @return the oldest element in the array, or null if the queue is empty
*/
@Override
public E peek() {
return null;
}
/**
* @return the difference between the total items added and removed
*/
@Override
public int size() {
return -1;
}
/**
* Clears the queue.
* <p>
* Reset the count for added and removed. Also, either set all slots in
* the backing array to null, or reallocate a fresh array.
* <p>
* Why is this second step desirable? Why not just reset added and removed and call it done?
* @see #newArray(int)
*/
@Override
public void clear() {
// code here
}
@Override
public boolean contains(Object o) {
return false;
}
public static void main(String[] args) {
IQueue<Integer> q = new ArrayQueue<>(10);
q.add(1);
q.offer(2);
q.offer(3);
System.out.println(q.contains(3));
System.out.println(q.poll());
System.out.println(q.size());
// final testing uncomment the following line to get comprehensive testing.
final int hundred_thousand = 100000;
final int million = 1000000;
/*
QueueTestProgram.printFailedTests(hundred_thousand,
ArrayBlockingQueue::new,
ArrayQueue::new);
*/
}
}
----------------------------------------------------------------
import java.util.NoSuchElementException;
/**
* created by {@code cspfrederick} and {@code garethhalladay} Fall17 <br>
* inspired by Chris Wilcox
*/
public interface IQueue<E> {
/**
* Inserts the specified element into this queue,
* returning true upon success.
* <p>
* This method throws an IllegalStateException if no space is available to hold the new item.
* @param item the item to add
* @throws IllegalStateException if the queue is full
*/
void add(E item);
/**
* Inserts the specified element into this queue if it is possible to do so
* immediately without violating capacity restrictions.
* @param e the element to add
* @return true if the element was added, false if the queue was full
*/
boolean offer(E e);
/**
* Retrieves and removes the head of this queue.
* @return the head of this queue, or null if this queue is empty
*/
E poll();
/**
* Retrieves and removes the head of this queue.
* This method differs from poll only in that it throws an exception
* if this queue is empty.
* @return the head of this queue
* @throws NoSuchElementException if this queue is empty
*/
E remove();
/**
* Retrieves, but does not remove, the head of this queue.
* @return the head of this queue, or null if this queue is empty
*/
E peek();
/**
* Retrieves, but does not remove, the head of this queue.
* This method differs from peek only in that it throws an
* exception if this queue is empty.
* @return the head of this queue
* @throws NoSuchElementException if this queue is empty
*/
E element();
/**
* Returns true if this queue contains no elements.
* @return true if this queue is empty, false otherwise
*/
boolean isEmpty();
/**
* Returns the number of elements in this queue.
* @return the number of elements in the queue
*/
int size();
/**
* Removes all of the elements from this queue.
* The queue will be empty after this call returns.
*/
void clear();
/**
* Returns a string representation of this queue.
* The string representation consists of a list of the
* queue's elements in the order they are returned by its iterator,
* enclosed in square brackets ("[]"). Adjacent elements are separated
* by the characters ", " (comma and space). Elements are converted to
* strings as by String.valueOf(Object).
* @return a string representation of this queue
*/
@Override
String toString();
/**
* Returns true if this queue contains the specified element. More formally,
* returns true if and only if this queue contains at least one element e
* such that o.equals(e).
* @param o object to be checked for containment in this queue
* @return true if this queue contains the specified element, false otherwise
*/
boolean contains(Object o);
}
program code to copy
ArrayQueue.java
import java.util.concurrent.ArrayBlockingQueue;
public class ArrayQueue<E> extends AQueue<E> implements IQueue<E>
{
/**
* the underlying array for the queue
*/
protected E[] elements;
/**
* the total elements added (set back to zero if clear is called)
*/
protected int added = 0;
/**
* the total elements removed (set back to zero if clear is called)
*/
protected int removed = 0;
/**
* Creates a new queue backed by an array of length {@code maxSize}.
* Use {@link #newArray(int)} to create the elements array.
* @param maxSize the capacity of the queue
* @see #newArray(int)
*/
public ArrayQueue(int maxSize)
{
elements = newArray(maxSize);
}
/**
* A helper method to create a new array of the generic type.
* Read the information provided on <a href=../generics.html>generics</a>.
* It walks you through the behavior of this small method.
* @param size the size of the new array
* @return an new instance of an array of type E
*/
protected E[] newArray(int size)
{
@SuppressWarnings("unchecked")
E[] arr = (E[]) new Object[size];
return arr;
}
/**
* Adds an element to the queue. If the queue is full, return false,
* otherwise add to the next available position in the queue.
* <p>
* The index of the next available position can be found by calculating
* the remainder of the total number of elements added by the length of the array.
* <p>
* Don't forget to increment the added field!
* @param e the element to add
* @return true if the element can be added, false otherwise
* @see #added
*/
@Override
public boolean offer(E e)
{
if (this.size() == elements.length) {return false;}
int tail = (added % elements.length);
elements[tail] = e;
added++;
return true;
}
/**
* Removes the oldest element (the head) from the queue, and returns it.
* If the queue is empty, return null.
* <p>
* The index of the oldest element can be determined by calculating the remainder
* of the total elements removed by the length of the array.
* <p>
* Don't forget to increment the removed field!
* <p>
* @return the oldest element in the queue, or null if the queue is empty
* @see #removed
*/
@Override
public E poll()
{
if(this.isEmpty())
{
return null;
}
int head =(removed % elements.length);
E theEl = elements[head];
elements[head] = null;
removed++;
return theEl;
}
/**
* Returns the oldest element in the queue (the element we would remove next),
* but does not remove it.
* If the queue is empty, return null.
* <p>
* The index of the oldest element can be determined by calculating the remainder
* of the total elements removed by the length of the array.
* @return the oldest element in the array, or null if the queue is empty
*/
@Override
public E peek()
{
if(this.isEmpty())
{
return null;
}
int head =(removed % elements.length);
E theEl = elements[head];
return theEl;
}
/**
* @return the difference between the total items added and removed
*/
@Override
public int size()
{
return added - removed;
}
/**
* Clears the queue.
* <p>
* Reset the count for added and removed. Also, either set all slots in
* the backing array to null, or reallocate a fresh array.
* <p>
* Why is this second step desirable? Why not just reset added and removed and call it done?
* @see #newArray(int)
*/
@Override
public void clear()
{
added = 0;
removed = 0;
elements = newArray(elements.length);
}
@Override
public boolean contains(Object o)
{
for(E el: elements)
{
if (o.equals(el))
{
return true;
}
}
return false;
}
public static void main(String[] args)
{
IQueue<Integer> q = new ArrayQueue<>(10);
q.add(1);
q.offer(2);
q.offer(3);
System.out.println(q.contains(3));
System.out.println(q.poll());
System.out.println(q.size());
// final testing uncomment the following line to get comprehensive testing.
final int hundred_thousand = 100000;
final int million = 1000000;
/* QueueTestProgram.printFailedTests(hundred_thousand,
ArrayBlockingQueue::new,
ArrayQueue::new);*/
}
}
================================================================================================
AQueue.java
import java.util.NoSuchElementException;
public abstract class AQueue<E> implements IQueue<E>
{
// The add method is similar to the offer method except for handling failure.
// Instead of returning false, it throws an IllegalStateException.
@Override
public void add(E item)
{
//codehere
boolean result = offer(item);
if(!result) throw new IllegalStateException();
}
// The remove method is similar to the poll method except for handling failure.
// Instead of returning null, it throws a NoSuchElementException.
@Override
public E remove()
{
E el = poll();
if (el == null) throw new NoSuchElementException();
return el;
}
// The element method is similar to the peek method except for handling failure.
// Instead of returning null, it throws a NoSuchElementException.
@Override
public E element()
{
if (peek() == null) throw new NoSuchElementException();
return peek();
}
// This method should utilize the size method to return the correct result.
@Override
public boolean isEmpty()
{
if (this.size() == 0)
{
return true;
}
return false;
}
}
========================================================================================
IQueue.java
import java.util.NoSuchElementException;
public interface IQueue<E>
{
/**
* Inserts the specified element into this queue,
* returning true upon success.
* <p>
* This method throws an IllegalStateException if no space is available to hold the new item.
* @param item the item to add
* @throws IllegalStateException if the queue is full
*/
void add(E item);
/**
* Inserts the specified element into this queue if it is possible to do so
* immediately without violating capacity restrictions.
* @param e the element to add
* @return true if the element was added, false if the queue was full
*/
boolean offer(E e);
/**
* Retrieves and removes the head of this queue.
* @return the head of this queue, or null if this queue is empty
*/
E poll();
/**
* Retrieves and removes the head of this queue.
* This method differs from poll only in that it throws an exception
* if this queue is empty.
* @return the head of this queue
* @throws NoSuchElementException if this queue is empty
*/
E remove();
/**
* Retrieves, but does not remove, the head of this queue.
* @return the head of this queue, or null if this queue is empty
*/
E peek();
/**
* Retrieves, but does not remove, the head of this queue.
* This method differs from peek only in that it throws an
* exception if this queue is empty.
* @return the head of this queue
* @throws NoSuchElementException if this queue is empty
*/
E element();
/**
* Returns true if this queue contains no elements.
* @return true if this queue is empty, false otherwise
*/
boolean isEmpty();
/**
* Returns the number of elements in this queue.
* @return the number of elements in the queue
*/
int size();
/**
* Removes all of the elements from this queue.
* The queue will be empty after this call returns.
*/
void clear();
/**
* Returns a string representation of this queue.
* The string representation consists of a list of the
* queue's elements in the order they are returned by its iterator,
* enclosed in square brackets ("[]"). Adjacent elements are separated
* by the characters ", " (comma and space). Elements are converted to
* strings as by String.valueOf(Object).
* @return a string representation of this queue
*/
@Override
String toString();
/**
* Returns true if this queue contains the specified element. More formally,
* returns true if and only if this queue contains at least one element e
* such that o.equals(e).
* @param o object to be checked for containment in this queue
* @return true if this queue contains the specified element, false otherwise
*/
boolean contains(Object o);
}
sample output