Java Collection How to - Create a Stack and Queue using ArrayDeque








Question

We would like to know how to create a Stack and Queue using ArrayDeque.

Answer

/*w ww.j  a v  a  2  s. com*/


   
import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
  public static void main(String args[]) {
    Deque<String> stack = new ArrayDeque<String>();
    Deque<String> queue = new ArrayDeque<String>();

    stack.push("A");
    stack.push("B");
    stack.push("C");
    stack.push("D");

    while (!stack.isEmpty())
      System.out.print(stack.pop() + " ");

    queue.add("A");
    queue.add("B");
    queue.add("C");
    queue.add("D");
    while (!queue.isEmpty())
      System.out.print(queue.remove() + " ");
  }
}

The code above generates the following result.