Deque Interface Tutorial in Java Collection

The Deque Interface is a linear collection and is part of the Java Collection Framework. The Deque Interface in java collection is an “double-ended queue” which means that Deque supports insertion and removal at both end points of the queue. The Deque Interface supports both FIFO (First-In-First-Out) and LIFO ( Last-In-First-Out) implementations.

Methods in Deque Interface

MethodDescription
boolean add(object)return true when insert the specified element into deque
boolean offer(object)inserts the specified element into deque
Object remove()retrieves and removes the head of deque
Object poll()retrieve deque element & removes the head of deque or returns null if this deque is empty.
Object element()only retrieve deque element
Object peek()only retrieve deque element and returns the head of this deque or null if this deque is empty

The Deque Interface provides the methods to insert elements, remove elements and examine the elements and are classified into 3 parts

Operation First Element Last Element
InsertaddFirst(e)
offerFirst(e)
addLast(e)
offerLast(e)
RemoveremoveFirst()
pollFirst()
removeLast()
pollLast()
ExaminegetFirst()
peekFirst()
getLast()
peekLast()

Insert element in Deque:

The addFirst() and offerFirst() methods are used to insert the elements at the beginning of the deque.

The addLast() and offerLast() methods are used to insert the elements at the beginning of the deque.

If the Dequeue is Full, then addFirst() and addLast() throws IllegalStateException

Remove element from Deque:

The removeFirst() and pollFirst() methods are used to remove the elements at the beginning of the deque.

The removeLast() and pollLast() methods are used to remove the elements at the beginning of the deque.

If the Dequeue is Null , then removeFirst() and removeLast() throws NoSuchElementException whereas pollFirst() and pollLast() returns Null

Examine element in Deque:

The getFirst() and peekFirst() methods are used to remove the elements at the beginning of the deque.

The getLast() and peekLast() methods are used to remove the elements at the beginning of the deque.

If the Dequeue is Null , then getFirst() and getLast() throws NoSuchElementException whereas peekFirst() and peekLast() returns Null

Leave a Reply

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

*