Deque

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.

Methods

First Element (Head)Last Element (Tail)
Throws ExceptionSpecial ValueThrows ExceptionSpecial Value
InsertaddFirst(e)offerFirst(e)addLast(e)offerLast(e)
InsertremoveFirst()pollFirst()removeLast()pollLast()
InsertgetFirst()peekFirst()getLast()peekLast()

 

Compare Methods (Queue Vs. Deque)

Queue MethodEquivalent Deque Method
add(e)addLast(e)
offer(e)offerLast(e)
remove()removeFirst()
poll()pollFirst()
element()getFirst()
peek()peekFirst()
Stack MethodEquivalent Deque Method
push(e)addFirst(e)
pop()removeFirst()
peek()peekFirst()
Declaration:

Programming Example

Output

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

Summary

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 *