开发者

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 开发者_如何学Cand remove elements from queue?

Please help,

Thanks in advance.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜