❮ Previous Next ❯

Dequeue Implementaion

Being a Queue subtype all methods in the Queue and Collection interfaces are also available in the Dequeinterface.Since Deque is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following Deque implementations in the Java Collections API:

LinkedList is a pretty standard deque / queue implementation.ArrayDeque stores its elements internally in an array. If the number of elements exceeds the space in the array, a new array is allocated, and all elements moved over. In other words, the ArrayDeque grows as needed, even if it stores its elements in an array.

There are also Queue implementations in the java.util.concurrent package, but I will leave the concurrency utilities out of this tutorial.

Here are a few examples of how to create a Deque instance:

Deque dq = new LinkedList();
Deque dq = new ArrayDeque();

Adding and Accessing Elements :

To add elements to the tail of a Deque, you call its add() method. You can also use the addFirst() andaddLast() methods, which add elements to the head and tail of the deque.

Deque dq = new LinkedList();
dq.add("Tapuuu"); //add element at tail
dq.addFirst("Silan”); //add element at head
dq.addLast ("Silan Software); //add element at tail

The order in which the elements added to the Deque are stored internally, depends on the implementation. The two implementations mentioned earlier both store the elements in the order (first or last) in which they are inserted.

You can peek at the element at the head of the queue without taking the element out of the queue. This is done via the element() method. You can also use the getFirst and getLast() methods, which return the first and last element in the Deque. Here is how that looks:

Object firstElement = dq.element();
Object firstElement = dq.getFirst();
Object lastElement =dq.getLast();

Removing Elements :

To remove elements from a deque, you call the remove(), removeFirst() and removeLast methods. Here are a few examples:

Object firstElement = dq.remove();
Object firstElement = dq.removeFirst();
Object lastElement =dq.removeLast();
❮ Previous Next ❯


Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Email: info@silantechnology.com
      Phone: 0674-2361252
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved