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

Implement a generic class Queue(T) that maintains a collection of items of gener

ID: 670389 • Letter: I

Question

Implement a generic class Queue(T) that maintains a collection of items of generic type T in FIFO order. Use the class ArrayList in the Java API to implement Queue. Your Queue class must provide the following instance methods: enqueue: that adds a new item to the back of the queue. dequeue: that removes an item from the front of the queue. inQueue?: that returns true if a given item is in the queue, or false otherwise. isEmpty?: that returns true if the queue is empty, or false otherwise. Write a testQueue class with a main() method that tests all operations of the Queue class above. Override the toString() method of the class Object, and use it to display all the items in the queue after each method is called.

Explanation / Answer

package mani;

import java.util.Scanner;

public class testQueue {
public static <T> void main(String[] args){
   System.out.println("Enter the elements into queue");
   Queue<T> q=new Queue<T>();
   Scanner s=new Scanner(System.in);
   String str;
   for(int i=0;i<4;i++){
       System.out.print("enter "+(i+1)+" element: ");
       str=s.next();
      
   q.enqueue((T) str);
   }
   System.out.println("Queue items after enqueue: "+q.toString());
   System.out.println("First dequeue: "+q.dequeue());
   System.out.println("Second dequeue: "+q.dequeue());
   System.out.println("Queue items after two dequeues: "+q.toString());
   System.out.println("Is queue empty after dequeus: "+q.isEmpty());
   System.out.print("Enter an item to check if it is present in the queue: ");
   str=s.next();
   System.out.println("Is "+str+" present in the queue: "+q.inQueue((T)str));
}

}

package mani;

import java.util.ArrayList;

public class Queue<T>{
   ArrayList<T> q=new ArrayList<T>();
   public void enqueue(T item){
       q.add(item);
   }
   public T dequeue(){
       T item;
       if(!isEmpty()){
       item=q.remove(0);
       return item;
       }else{
           System.out.println("Queue is empty");
           return null;
       }
   }
   public boolean inQueue(T item){
       return q.contains(item);
   }
   public boolean isEmpty(){
       return q.isEmpty();
   }
   public String toString(){
       return q.toString();
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote