Tutorials Hut

Java Collection: Deque and ArrayDeque

Java collection’s Deque or double ended queue is a queue in which we can perform operations from both ends of the queue(add or remove elements). Deque is an interface. In this article, we will look, in detail Java Collection: Deque and ArrayDeque.

Deque Interface declaration

public interface Deque<T> extends Queue<R>  

Methods of Java Deque Interface

Method

Description

boolean add(object)

Adds an element in Deque

boolean offer(object)

Inserts and elements.

Object remove()

Retrieves and removes an element.

Object poll()

Retrieves and removes head element.

Object element()

It retrieves an element but does not remove it.

Object peek()

It retrieves an element but does not remove it.

ArrayDeque

ArrayDeque is an implementation of Deque interface.

We can add or remove elements from both side of ArrayDeque.

It is not thread safe.

Example Of ArrayDeque

import java.util.*;

public class MyCollections2{
public static void main(String args[]){
    Deque<String> queue=new ArrayDeque<>();
    queue.add("D");
    queue.add("B");
    queue.add("C");
    queue.add("E");
  queue.add("A");

    queue.addFirst("G"); // ADD at first
     System.out.println("element:"+queue.element());

     System.out.println("peek:"+queue.peek());

    System.out.println("iterating the queue elements:");
    Iterator itr=queue.iterator();
    while(itr.hasNext()){
        System.out.println(itr.next());
     }

    queue.remove(); //removes at first
    queue.removeLast(); //removes last
     queue.poll();

    System.out.println("after removing 3 elements:");
    Iterator<String> itr2=queue.iterator();
    while(itr2.hasNext()) {
        System.out.println(itr2.next());
    }
}

Output

element:G
peek:G
iterating the queue elements:
G
D
B
C
E
A
after removing 2 elements:
B
C
E

Next Article

  • Java: Map Interface