iOSDev
iOSDev

Reputation: 3617

Peek() and remove() methods for Queue implementation in Blackberry

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 to peek at elements and remove elements from queue?

Please help,

Thanks in advance.

Upvotes: 1

Views: 7730

Answers (2)

Marc Novakowski
Marc Novakowski

Reputation: 45408

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.

Upvotes: 3

Maksym Gontar
Maksym Gontar

Reputation: 22775

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());
        }
    }
}

Upvotes: 4

Related Questions