Deque

The bearing of a child takes nine months, no matter how many women are assigned. Many software tasks have this characteristic because of the sequential nature of debugging. Fred Brooks

ArrayDeque

Language Java | Level Intermediate | Category Java collections framework (JCF) | 2015-07-22 18:47:54

0 Comments


Definition

Array deque is a resizable array with the implementation of a doubly ended queue. Most ArrayDeque operations run in amortized constant time.

Character

Array deques have no capacity restrictions, it grows dynamically.
It do not support concurrent access and not thread safe. If multiple threads try to access and update, it may throw ConcurrentModificationException.
It significantly add and remove in both ends through head and tail.
Iterator method is fail-fast. If the iterator accesses from multiple threads, it fails quickly and cleanly.
Array deque is faster than the stack and linked list.

source Code

								
package com.careerdrill.collections.deque;

import java.util.ArrayDeque;
import java.util.Arrays;

public class ArrayDequeUse {

	public static void main(String[] args) {

		int []array={10,20,30,40,50};
		System.out.println("Push the values to the array dequeue: " + Arrays.toString(array));
		
		ArrayDeque< Integer > deque = new ArrayDeque< >();
		
		for(int i : array)
			deque.push(i);
		
		
		int peekResult = deque.peek();
		System.out.println("Peek the value from Array Dequeue: "+peekResult);

		int popResult = deque.pop();
		System.out.println("Pop the value from Array Dequeue: "+popResult);

		popResult = deque.pop();
		System.out.println("Pop the value from Array Dequeue: "+popResult);
	}

}
						

Output

    					 
Push the values to the array dequeue: [10, 20, 30, 40, 50]
Peek the value from Array Dequeue: 50
Pop the value from Array Dequeue: 50
Pop the value from Array Dequeue: 40    					 
					    

Comparison

ArrayDeque ArrayList
Do not support to access the element using the index. Support to get the element using index.
Element can be inserted using head or tail Element can be inserted any place using index
Resizable-array implementation which grow dynamically Resizable-array implementation which grow dynamically
ArrayDequeue has less cost when insert the tail or head ArrayList has a high cost for insert and delete operations due to array copy.

When to use

If you need add/remove elements from both head and tail, ArrayDeque is significantly better than a linked list.

0 Comments



Please login to add comments.