Sunday, January 26, 2014

Java Collections : DQueue

In DQueue the head element is always removed according to the processing order. Processing order is defined by natural ordering. DQueue interface extends Queue interface to provide double ended queues.Operations are allowed at the head and tails.DQueue can be used as FIFO and LIFO queues.push() and pop() methods are provided for implementation of stack .

ArrayQueue and Linked List class 

Both classess implements DQueue interface.ArrayQueue has better performance because of FIFO algorithm.This is better choice that java.util.Stack. ArrayQueue is iterable.Traversal from bottom is possible using  descendingIterator().



package collections;

import java.util.ArrayDeque;
import java.util.Iterator;

public class DQueueTest {

       public static void main(String[] args) {
              ArrayDeque<String> adq = new ArrayDeque<String>();
              adq.offer("Test1");
              adq.offerFirst("Test2");
              adq.offerLast("Test3");
              System.out.println(adq);
              adq.push("Test4");

              System.out.println(adq);
              adq.offer("Test5");
              adq.offer("Test6");
              adq.offer("Test7");
              adq.offer("Test8");
              adq.offer("Test9");
              adq.offer("Test10");
              adq.offer("Test11");
              System.out.println(adq);

              // Get and remove elements
              System.out.println(adq.pollFirst());
              System.out.println(adq.pollLast());

              System.out.println(adq);

              adq.pop();// Remove from head
              System.out.println(adq);
              adq.removeFirst();// throws NoSuchElementException
              adq.removeLast();// throws NoSuchElementException
              System.out.println(adq);

              adq.removeFirstOccurrence("Test7");
              adq.removeLastOccurrence("Test9");

              //These method wont remove the elements
              System.out.println(adq);
              adq.peekFirst();
              adq.peekLast();
              adq.getFirst();
              adq.getLast();
              // Descending iterator
              Iterator<String> desItr = adq.descendingIterator();
              while (desItr.hasNext()) {
                     System.out.println(desItr.next());
              }

       }
}

 

No comments: