Deque in Java with Programming Example

DequeIn this chapter you will learn:

  1. What is Deque in Java?
  2. Declaration of Deque
  3. Programming Example
What is Deque in Java?

Keyword Deque stands for “Double Ended Queue” which allows insertion and removal of both sides. You can add and remove element both sides as head and tail. However Deque has not size limit but using interface you can restrict its size limit. There are some special methods which allow element’s insertion and removal in both sides. Deque can also be used as Stack. It can behave like LIFO and FIFO both.


First Element (Head) Last Element (Tail)
Throws Exception Special Value Throws Exception Special Value
Insert addFirst(e) offerFirst(e) addLast(e) offerLast(e)
Insert removeFirst() pollFirst() removeLast() pollLast()
Insert getFirst() peekFirst() getLast() peekLast()


Compare Methods (Queue Vs. Deque)

Queue Method Equivalent Deque Method
add(e) addLast(e)
offer(e) offerLast(e)
remove() removeFirst()
poll() pollFirst()
element() getFirst()
peek() peekFirst()
Stack Method Equivalent Deque Method
push(e) addFirst(e)
pop() removeFirst()
peek() peekFirst()
Deque d=new LinkedList();

Programming Example

import java.util.*;
class DeQue_Example
  public static void main(String[] args)
    Deque d=new LinkedList();
    //Print Deque using Iterator
    Iterator itr=d.iterator();
      System.out.print( + " ");
    System.out.println("\nPeek Last Value : "+d.peekLast());
    System.out.println("Remove Last Value : "+d.pollLast());
    //Adding new value to last
    System.out.println("printing : "+d);


D:\JavaProgram>java DeQue_ExampleHead2 Head1 Tail1 Tail2
Peek Last Value : Tail2
Remove Last Value : Tail2
printing : [Head2, Head1, Tail1, Hello]


In this program you can clearly see that Deque allows insertion and removal of elements both sides. It has some special methods that allows programmer to use deque as stack. In the next chapter you will learn about ArrayDeque Class.

Leave a Reply

Your email address will not be published. Required fields are marked *