"Before software can be reusable it first has to be usable"- Ralph Johnson

Monday, November 21, 2011

Deque and ArrayDeque

By 10:55 AM
Deque is the abbreviation of “Double Ended Queue”. A Collection that allows us to add (or) remove elements at both ends. Deque supports total size of collection for both fixed and unspecified size limits.

Deque implementation can be used as Stack(Last in first out ) or Queue(First in First Out). For each insertion, retrieval and removal of elements from deque there exists methods in 2 flavours. One will throw exception if it fails in an operation and another one returns status or special value for each operation.

OperationSpecial value methodException throwing method
Insertion at headofferFirst(e)addFirst(e)
Removal at headpollFirst()removeFirst()
Retrieval at Head
peekFirst()getFirst()
Insertion at TailofferLast(e)addLast(e)
Removal at TailpollLast()removeLast()
Retrieval at Tail
peekLast()getLast()

Implementation of Deque doesn’t require preventing the insertion of null, but when we are using special value method null is return to indicate that collection is empty. So it is recommendable not to allow insertion of null.

ArrayDeque is a class that implements Deque. It has no capacity restrictions. It will perform faster than stack when used as stack and faster than linked list when used as queue. ArrayDeque is not thread Safe. The following example explains how to write program using ArrayDeque.

Example:
import java.util.ArrayDeque;
import java.util.Iterator;


public class DequeExample
{
public static void main(String as[])
{
ArrayDeque adObj = new ArrayDeque(); 


//Insertion by using various methods
adObj.add("Oracle"); 
adObj.addFirst("DB2");
adObj.offerFirst("MySQL");   //returns boolean - true R false 
adObj.offerLast("Postgres");   //returns boolean - true R false

//Retrievals 
System.out.println("Retrieving First Element :" + adObj.peekFirst());
System.out.println("Retrieving Last Element  :"+ adObj.peekLast());


//Removals
System.out.println("Removing First  Element  :"+ adObj.pollFirst());
System.out.println("Removing Last  Element   :"+ adObj.pollLast());


//Reverse traversal
System.out.println("Remaining Elements :");
Iterator it = adObj.descendingIterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}


Output:
Retrieving First Element :MySQL
Retrieving Last Element  :Postgres
Removing First  Element  :MySQL
Removing Last  Element   :Postgres
Remaining Elements :
Oracle
DB2


For more please visit- http://download.oracle.com/javase/6/docs/api/java/util/ArrayDeque.html

0 comments:

Post a Comment