Question

In: Computer Science

Complete the methods in AQueue and ArrayQueue The third pasted code is just the interface. DO...

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);

}

Solutions

Expert Solution

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


Related Solutions

3. Which statement about methods in an interface is true? A.)All methods in an interface must...
3. Which statement about methods in an interface is true? A.)All methods in an interface must be explicitly declared as private or public. B.)All methods in an interface are automatically public. C.)All methods in an interface are automatically private. D.)All methods in an interface are automatically static.
//Complete the incomplete methods in the java code //You will need to create a driver to...
//Complete the incomplete methods in the java code //You will need to create a driver to test this. public class ManagedArray { private int[] managedIntegerArray; //this is the array that we are managing private int maximumSize; //this will hold the size of the array private int currentSize = 0; //this will keep track of what positions in the array have been used private final int DEFAULT_SIZE = 10; //the default size of the array public ManagedArray()//default constructor initializes array to...
Assignment Content Resource: ****************************CODE PASTED BELOW******************************* For this assignment, you will develop Java™ code that relies...
Assignment Content Resource: ****************************CODE PASTED BELOW******************************* For this assignment, you will develop Java™ code that relies on localization to format currencies and dates. In NetBeans, copy the linked code to a file named "Startercode.java". Read through the code carefully and replace all occurrences of "___?___" with Java™ code. Note: Refer to "Working with Dates and Times" in Ch. 5, "Dates, Strings, and Localization," in OCP: Oracle® Certified Professional Java® SE 8 Programmer II Study Guide for help. Run and debug...
Invalid entry code in python my code is pasted below. The last elif statement, I'm trying...
Invalid entry code in python my code is pasted below. The last elif statement, I'm trying to get the program to print "invalid entry" if the entry for user_input is invalid. The first user prompt should only allow for numbers 1-10 and "exit" and "quit" import math user_prompt = """Enter number of operation that you want to execute <type exit or quit to end program>: 1 sin(x) 2 cos(x) 3 tan(x) 4 asin(x) 5 acos(x) 6 atan(x) 7 ln(x) 8...
package labs; Complete the following code /* * Purpose: Look at LinkedList, overloaded methods and *...
package labs; Complete the following code /* * Purpose: Look at LinkedList, overloaded methods and * write a simple method to check if the LinkedList actually contains any loops/cycles in it. */ public class LinkedList<E> { private static class Node<E> { E data; Node<E> next; public Node(E d) { data=d; next=null; } } private Node<E> head; private Node<E> tail; /* * data of type E, first gets put into a Node * and then the Node gets added onto the...
JAVA Add static methods largest and smallest to the Measurable interface. The methods should return the...
JAVA Add static methods largest and smallest to the Measurable interface. The methods should return the object with the largest or smallest measure from an array of Measurable objects.
# Mini-Exercise 4: Classes practice # Complete the three methods that say 'your code here' in...
# Mini-Exercise 4: Classes practice # Complete the three methods that say 'your code here' in the classes below class Character: ''' This class represents a character in a game. ''' def __init__(self, name, health=100): '''(str, int) -> Character Construct a character with the name and health provided. If health is not provided, a default health of 100 is used. ''' self.name = name self.health = health def __str__(self): '''() -> str Return a string representation of this character. '''...
I have to complete all //to do comments for the following code: /** * A ShoppingBasket...
I have to complete all //to do comments for the following code: /** * A ShoppingBasket holds zero or more Products and can provide information * about the Products. One can add Products to a ShoppingBasket during its * lifetime, reset the ShoppingBasket, create a copy which contains Products of * at least a certain value, and make various queries to the ShoppingBasket. * (Thus, the number of Products that will be stored by a ShoppingBasket object * is not...
create an interface called Visible that has two methods called makeVisiible, makeInvisible. both methods take no...
create an interface called Visible that has two methods called makeVisiible, makeInvisible. both methods take no parameters and should return a boolean result. HTML EditorKeyboard Shortcuts 12pt Paragraph 0 words Flag this Question Question 58 pts The following classes have been created with the given behaviors: public class Leo extends Don { public void method1() { System.out.print("Leo 1 "); } public void method3() { System.out.print("Leo 3 "); } public String toString() { return "Leo 1 "; } } class Mike...
Give the entire code for Minimum spanning tree using Boruvka's algorithm in java (not copy-pasted from...
Give the entire code for Minimum spanning tree using Boruvka's algorithm in java (not copy-pasted from any other website)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT