In this chapter you will learn:
- What is Deque in Java?
- Declaration of Deque
- 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 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() |
Declaration:
Dequed=new LinkedList ();
Programming Example
import java.util.*; class DeQue_Example { public static void main(String[] args) { Dequed=new LinkedList (); d.addLast("Tail1"); d.addLast("Tail2"); d.addFirst("Head1"); d.addFirst("Head2"); //Print Deque using Iterator Iterator itr=d.iterator(); while(itr.hasNext()) { System.out.print(itr.next() + " "); } System.out.println("\nPeek Last Value : "+d.peekLast()); System.out.println("Remove Last Value : "+d.pollLast()); //Adding new value to last d.addLast("Hello"); System.out.println("printing : "+d); } }
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]
_
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.