Sunday, November 28, 2010

Array based Queue Implementation in Java

Array Based queue Implementation in java :


import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Queue;




public class ArrayQueue implements Queue {


    Object queueObjects[];
    private int front;
    private int back;
    private int currentSize;
    
    
    public ArrayQueue(){
this(5);
makeEmpty();
    }
    public ArrayQueue(int DEFAULT_CAPACITY)
    {
this.queueObjects = new Object[DEFAULT_CAPACITY];
    }
    
    public static void main(String[] args) throws UnderFlowException{
ArrayQueue obj = new ArrayQueue();
obj.enqueue(new String("sekhar"));
obj.enqueue(new String("Ramu"));
System.out.println("Object Front "+obj.dequeue());
    }
    public void makeEmpty(){
currentSize = 0;
front = 0;
back = -1;
    }
    /*
     * Remove an item from the Queue which is at the front position.    
     */
    public Object dequeue() throws UnderFlowException {
      if(isMyQueueEmpty()){
   throw new UnderFlowException("ArrayQueue dequeue");
      }
 Object returnValue = queueObjects[front];
 front--;
 currentSize--;
        return returnValue;
      
    }
    public boolean isMyQueueEmpty(){

return currentSize == 0;

    }
    public boolean checkFront(int front){

return front == currentSize;
    }
    public void enqueue(Object o){

if(currentSize == queueObjects.length){
   //Increase the Size of the Queue to Accommdate the new Objects
   ensureCapacity();
}
else{
   queueObjects[++back] = o;
   currentSize++;
   front = currentSize - 1;
}
    }
    
    public void ensureCapacity()
    {
int newCapacity = queueObjects.length * 2;
Object oldData[] = queueObjects;
queueObjects = Arrays.copyOf(oldData, newCapacity);
    }

No comments:

AWS certification question

AWS AWS Hi! this is for questions related to AWS questions. EC2 instances EC2 storage types cold HDD : 1. Defines performance in terms...