X391: ArrayQueueToString

or the question below, assume the following implementation of LinkedQueue:


public class ArrayQueue<T> implements QueueInterface<T> {
    private T[] contents;
    private int frontIndex;

    private int backIndex;
    private static final int DEFAULT_CAPACITY = 50;

    public ArrayQueue() {
        this(DEFAULT_CAPACITY);
    }

    @SuppressWarnings("unchecked")
    public ArrayQueue(int initialCapacity) {
        // The new array contains null entries
        contents = (T[])new Object[initialCapacity + 1];
        frontIndex = 0;
        backIndex = contents.length - 1;
    }


    @Override
    public void enqueue(T newEntry) {
        // this method has been implemented correctly but is hidden from view
    }

    @Override
    public T dequeue() {
        // this method has been implemented correctly but is hidden from view
        return null;
    }

    @Override
    public T getFront() {
        if (isEmpty()) {
            throw new EmptyQueueException();
        }

        return contents[frontIndex];
    }


    @Override
    public boolean isEmpty() {

        return (((backIndex + 1) % contents.length) == frontIndex);
    }


    @Override
    public void clear() {
        while (!isEmpty()) {
            dequeue();
        }

    }

}

For this method you will be finishing implementing a toString method that prints out the order of the queue from the way a user might interact with it.

So for example

//creating an array queue with a capacity of 5.
// note this will make a contents array of size 6
  ArrayQueue<String> aq1 = new ArrayQueue<String>(5);

  // filling up all 5 slots
  aq1.enqueue("a");
  aq1.enqueue("b");
  aq1.enqueue("c");
  aq1.enqueue("d");
  aq1.enqueue("e");

  // dequeue two things
  aq1.dequeue();
  aq1.dequeue();

  // add in 3 more things

  aq1.enqueue("f");
  aq1.enqueue("g");
  aq1.enqueue("h");

The contents array in the ArrayQueue class will now look like:

["g", "h", "c", "d", "e", "f"]

but for the user the start of the queue is still "c" and the end is still "h". Thus the toString method should return out the characters in the following order:

"[c d e f g h]"

Below, the start of the toString method has been implemented, finish it up by writing in what the for loops should be looping over.

Your Answer:

Reset

Practice a different Java exercise

Feedback

Your feedback will appear here when you check your answer.