1>Design a class named Queue for storingintegers. Like a stack, a queue holds elements. In a stack, the elements areretrieved 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 fieldnamed elements that stores the int values in the queue.
■ A data field named size that stores the number of elements inthe queue.
■ A constructor that createsa Queue object with defaultcapacity 8 .
■ The method enqueue(int v) that adds v into the queue.
■ The method dequeue() that removes and returns theelement from the queue.
■ The method empty() that returns true if the queue isempty.
■ The method getSize() that returns the size of the queue.
Implement the class with the initial arraysize set to 8. The array size will be doubled once the number of the elementsexceeds the size. After an element is removed from the beginning of thearray,you need to shift all elements in the array one position the left. Writea test program that adds 20 numbers from 1 to 20 into the queue and removesthese numbers and displays them.
import java.util.Arrays;
public class Queue {
int[] elements;
int size;
public Queue() {
this.elements = new int[8];
this.size = 0;
}
public void enqueue(int v) {
if(!(this.size <= this.elements.length))
doubleSize();
this.size++;
elements[this.size-1] = v;
}
public int dequeue() {
if(!this.empty()) {
this.size--;
int ret=this.elements[0];
shiftElements();
return ret;
}
return -1;
}
public boolean empty() {
if(this.size==0)
return true;
else
return false;
}
public int getSize() {
return this.size;
}
private void doubleSize() {
int[] test=new int[this.elements.length*2];
for(int i=0;i<test.length;i++) {
if(i<this.elements.length)
test[i]=this.elements[i];
else
test[i]=0;
}
this.elements=test;
}
private void shiftElements() {
for(int i=0;i<=size;i++) {
if(i<this.elements.length)
this.elements[i]=this.elements[i+1];
else
this.elements[i]=0;
}
}
public static void main(String[] args) {
Queue q=new Queue();
System.out.println("Initial queue's size: "+q.getSize());
q.enqueue(1);
q.enqueue(2);
System.out.println("Queue size after adding 2 elements: "+q.getSize());
System.out.println("Elements: "+Arrays.toString(q.elements));
System.out.println("Dequing: "+q.dequeue());
System.out.println("Size after dequeue: "+q.getSize());
System.out.println("Elements after dequeue: "+Arrays.toString(q.elements));
}
}