Deque interface in Java with Example

In this article, we will learn about the Deque interface in Java with Example.

The deque interface is available in the package java.util is a subtype of the queue interface. The deque is tie at two ends to the queue, which provides for the addition or removal of elements at each end of the data structure. It can use as a queue (First In, First Out / FIFO) or as a stack (Last In, First Out / LIFO). Deque is the abbreviation for Double Ended Queue.

Declaration

public interface Deque extends Queue

Creating Deque Objects

Deque being an interface, no object of type deque can be created. We still need a class that extends this list to create an object. In addition, after the introduction of generics in Java 1.5, it is possible to restrict the type of object that can be registered in the Deque. This secure type queue can be defined as follows

Deque<Obj> deque = new ArrayDeque<Obj> ();

Example

import java.util.*;

public class DequeExample {
	public static void main(String[] args)
	{
		Deque<String> deque = new LinkedList<String>();

		// Add at the last
		deque.add("Element 1 (tail)");

		// Add at the first
		deque.addFirst("Element 2 (head)");

		// Add at the last
		deque.addLast("Element 3 (tail)");

		// Add at the first
		deque.push("Element 4 (head)");

		// Add at the last
		deque.offer("Element 5 (tail)");

		// Add at the first
		deque.offerFirst("Element 6 (head)");

		System.out.println(deque + "\n");

		// We can remove the first element or the last element.
		deque.removeFirst();
		deque.removeLast();
		System.out.println("Deque after removing "
						+ "first and last: "
						+ deque);
	}
}

That’s all, we will learn about the Deque interface in Java with Example.

Next Article

1. PriorityQueue in Java
2. Stack Class in Java
3. Vector Class in Java
4. Queue Interface In Java
5. List Interface in Java with Examples

Please share this post:
Posts created 73

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: