Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(In Java) Design a class named Queue for storing integers. Like a stack, a queue

ID: 3569502 • Letter: #

Question

(In Java) Design a class named Queue for storing integers. Like a stack, a queue holds elements. In a stack, the elements are retrieved in a last-in first-out fashion. In a queue, the elements are retrieved in a first-in first-out fashion. The class contains:

- An int [ ] data field named elements that stores the int values in the queue.

- A data field named size that stores the number of elements in the queue.

- A constructor that creates a Queue object with default capacity 8.

- The method enqueue(int v) that adds v into the queue.

- The method dequeue() that removes and returns the element from the queue.

- The method empty() that returns true if the queue is empty.

- The method getSize() that returns the size of the queue.

The array size will be doubled once the number of the elements exceeds the size. For this, write a private method to double the arrays size once the queue size exceeds its default size of 8 elements. Also, after an element is removed from the beginning of the array, you need to shift all elements in the array one position to the left. For this, write a private method to accomplish this task.

Explanation / Answer

public class Queue{
   int elements[];
   int size;
   Queue(){
       elements = new int[8];
       size = 0;
   }
   void enqueue(int v){
       elements[size++] = v;
       if(size == elements.length){
           doubleSize();
       }
   }
   int dequeue(){
       int temp = -1;
       if(empty()) System.out.println("Queue is empty");
       else{
           temp = elements[0];
           shiftLeft();
           size--;
       }
       return temp;
   }
   boolean empty(){
       if(size == 0) return true;
       else return false;
   }
   int getSize(){
       return size;
   }
   private void doubleSize(){
       int temp[] = elements;
       elements = new int[size * 2];
       for(int i = 0; i < temp.length; i++){
           elements[i] = temp[i];
       }
   }
   private void shiftLeft(){
       for(int i = 0; i < size - 1; i++){
           elements[i] = elements[i + 1];
       }
   }
}