Monday, April 8, 2013

Example on java.util.Queue and its implementation classes

Example on java.util.Queue  and its implementation classes usage.

package com.pramasa;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

public class QueueExample {
    public static void main(String[] args) {
     // Java 6 introduced a double ended queue implementation.       
        Deque dq=new ArrayDeque();
        dq.offer("Bronze");
        dq.offer("Silver");
        dq.offer("Gold");
        dq.offer("Platinum");
        dq.offer("Diamond");   
       
        String item=null;
        for(Iterator it=dq.iterator(); it.hasNext();){
            item=it.next();
            System.out.println("item-->"+item);
        }
        System.out.println("----------------------------");
        for(Iterator it=dq.descendingIterator(); it.hasNext();){
            item=it.next();
            System.out.println("item-->"+item);
        }
        System.out.println("----Some of the methods available------------------------");
        dq.addFirst("Iridium");dq.addLast("PinkDiamond");
       
        for(Iterator it=dq.iterator(); it.hasNext();){
            item=it.next();
            System.out.println("item-->"+item);
        }


       //  Java 5 introduced ArrayBlockingQueue 
      // and below code describes how 'add' throws exception when we try to add items more than its   
      // actual size
        Queue q= new ArrayBlockingQueue(5);
        q.offer("Malay");
        q.offer("English");
        q.offer("Chinese");
        q.offer("Tamil");
        q.offer("Hindi");
        q.offer("Telugu"); // Here we don't get any exception
       
        for(Iterator it=q.iterator(); it.hasNext();){
            item=it.next();
            System.out.println("ArrayBlockingQueue item using method Offer-->"+item);
           
        }
        q.add("Malay");
        q.add("English");
        q.add("Chinese");
        q.add("Tamil");
        q.add("Hindi");
        //q.add("Telugu");// Here we get the IllegalStateException
       
        for(Iterator it=q.iterator(); it.hasNext();){
            item=it.next();
            System.out.println("ArrayBlockingQueue item using  method add-->"+item);
        }
    }
}




No comments: