Write a Java program to implement Queue using ArrayDeque class
- The program starts by importing the required classes from the java.util package, including ArrayDeque and other utilities.
- Next, we define a class called Array_Deque.
- Inside the Array_Deque class, we have the main method, which serves as the entry point of the program.
- Within the main method, we declare a variable named queue_list, which is of type Queue<String>. This line creates a queue using the Queue interface, and we use the ArrayDeque class to implement the Queue interface. An ArrayDeque is a resizable-array implementation of the Deque interface, which is an extended version of the Queue interface. It can act as both a queue and a stack.
- We then add elements to the queue using the add method. In this example, we add seven strings to the queue: "Yellow", "Green", "Pink", "Black", "Blue", "White", and "Red". The add method adds elements to the end of the queue.
- We create an iterator named itr using the iterator() method of the queue_list.
- We use the iterator to traverse the elements of the queue and print them. The hasNext() method of the iterator checks if there are more elements to iterate over, and the next() method returns the next element in the iteration.
- The System.out.print statement is used to display the elements of the queue on the same line.
Source Code
import java.util.*;
public class Array_Deque
{
public static void main(String[] args)
{
Queue <String> queue_list = new ArrayDeque <>();
queue_list.add("Yellow");
queue_list.add("Green");
queue_list.add("Pink");
queue_list.add("Black");
queue_list.add("Blue");
queue_list.add("White");
queue_list.add("Red");
Iterator itr = queue_list.iterator();
System.out.print("Queue Elements : ");
while (itr.hasNext())
{
System.out.print(itr.next() + " ");
}
}
}
Output
Queue Elements : Yellow Green Pink Black Blue White Red