views:

270

answers:

3

Hi,

I want to implement peek and remove methods , similar to Java's Queue.peek() and Queue.remove() , in Blackberry application. I have a custom queue implementation ,but how do I get peek elements and remove elements from queue?

Please help,

Thanks in advance.

+1  A: 

Try to use Arrays class... if you need to peek, take last element from Object array, to remove just delete last one:

class Queue {
    private Object[] mElements = new Object[] {};

    public void enqueue(Object element) {
     Arrays.insertAt(mElements, element, 0);
    }

    public Object dequeue() {
     Object result = null;
     if (null != mElements && 0 < mElements.length) {
      result = mElements[mElements.length - 1];
      Arrays.remove(mElements, result);
     }
     return result;
    }

    public Object peek() {
     if (null != mElements && 0 < mElements.length)
      return mElements[mElements.length - 1];
     else
      return null;
    }

    public void remove() {
     if (null != mElements && 0 < mElements.length)
      Arrays.remove(mElements, peek());
    }
}

Using example:

class Scr extends MainScreen {
    public Scr() {
     Queue queue = new Queue();
     queue.enqueue(new String("3"));   
     queue.enqueue(new Boolean(true));
     queue.enqueue(new Integer(1));  
     //see "3" in console
     System.out.println(queue.peek());
     //see "3" still there
     System.out.println(queue.peek());
     //remove "3"
     queue.remove();
     //see "true" in console
     System.out.println(queue.peek());  
     //dequeue all elements
     Object element = null;
     while ((element = queue.dequeue()) != null) {
      System.out.println(element.toString());
     }
    }
}
Max Gontar
Thanks Coldice, it helped me
imMobile
You're welcome!
Max Gontar
+1  A: 

You should be able to use a Vector to do these types of operations - firstElement() to peek at the first in the list, lastElement() to peek at the last, or elementAt() to look at anything in between. Then use removeElementAt() to remove an element.

Marc Novakowski
Thanks Marc for the answer
imMobile
A: 

Hi, I am using above code successfully for queue manipulations. I need to add element at first location (addBefore in Java) .

How can I do it?

Please help

imMobile