Menu
Topics Index
...
`

ArrayDeque Class - Java Example Program


ArrayDeque Class
import java.util.*;        

class ArrayDequeDemo
{
    public static void main(String arg[])
    {
        ArrayDeque<Integer> adq = new ArrayDeque<Integer>();
        //Use an ArrayDeque like a queue
        adq.add(1);
        adq.add(2);
        adq.add(3);
        adq.add(4);
        //adq.add(null); LINE A
        System.out.print("Elements of queue: ");
        while(adq.peek()!=null)
        System.out.print(adq.pop()+"\t");
        System.out.println();
        System.out.print(" Elements of stack: ");
        //Use an ArrayDeque like a stack
        adq.push(1);
        adq.push(2);
        adq.push(3);
        adq.push(4);
        while(adq.peek()!=null)
        System.out.print(adq.pop()+"\t");
    
    }
}
OUTPUT

Elements of queue: 1    2    3    4    
Elements of stack: 4    3    2    1

DESCRIPTION

The first part of the program demonstrates ArrayDeque by using it to create a queue.Hence it follows "first in first out" order in displaying the elements of the queue.

The second part of the program demonstrates ArrayDeque by using it to create a stack.Hence it follows "last in first out" order in displaying the elements of the stack.

THINGS TO TRY
  • Uncomment LINE A to see java.lang.NullPointerException since ArrayDequeu doesn't permit null elements.
  • Place the below code in the above program.
    System.out.println(adq.pop());
    System.out.println(adq);
    The above code removes the first element from adq so the output will be
    1
    [2, 3, 4]

© meritcampus 2019

All Rights Reserved.

Open In App