Thursday, February 25, 2010

Queue in Blackberry

The java.util or net.rim.device.api.util packages of blackberry does not have Queue class. In queue elements are removed in the same order in which they are added. This is called as FIFO, meaning First In First Out. Queue is data structure and is required for various purposes. Queue data structure works as normal queue you can see for getting tickets, boarding on plane or bus where the first person is served and the new person joins at the end of the queue.


Two basic operations that should be supported by queue are:

1. Enqueue: Inserts element at the end of queue.
2. Dequeue: Removes element from the top of the queue and return that element.


There can be various approach to do this, but this one is using Vector class of java.util package. (Instead of Vector, LinkedList will be useful but LinkedList is also not supported and for now I am not creating LinkedList class). In this approach, Vector is composited in Queue class.


Queue Class:

import java.util.*;

/**
* Queue.java
* A queue of objects in which elements are removed in the same order they have entered (FIFO).
* @author Dipak Vanarse
*/
public class Queue
{
private Vector m_oItems;

/**
* Constructor
*/
public Queue()
{
m_oItems = new Vector();
}

/**
* Inserts an element at the end of the queue.
* @param oElement Element to be inserted.
*/
public Object enqueue(Object oElement)
{
m_oItems.addElement(oElement);
return oElement;
}

/**
* Removes the element at the top of the queue.
* @return The removed element.
* @throws EmptyQueueException if the queue is empty.
*/
public Object dequeue() throws EmptyQueueException
{
// If there are no items in the list
if(0 == m_oItems.size())
{
// Exception
throw new EmptyQueueException();
}

// Remove element at the top and return it
Object oItem = m_oItems.elementAt(0);
m_oItems.removeElementAt(0);
return oItem;
}

/**
* @return The total number of elements in the queue.
*/
public int size()
{
return m_oItems.size();
}

/**
* @return true if the queue is empty, and false otherwise.
*/
public boolean empty()
{
return (0 == m_oItems.size());
}

/**
* Inspects the element at the top of the queue without removing it.
* @return A reference to the value at the front of a non-empty queue; null if the queue is empty
*/

public Object front()
{

if(m_oItems.size()== 0)
{
m_oItems.elementAt(0);
}

return
}
}