我想在黑莓应用程序中实现peek和remove方法,类似于Java的Queue.peek()和Queue.remove()。我有一个自定义的队列实现,但是如何查看元素并从队列中删除元素?黑莓队列队列实现的Peek()和remove()方法
请帮忙,
在此先感谢。
我想在黑莓应用程序中实现peek和remove方法,类似于Java的Queue.peek()和Queue.remove()。我有一个自定义的队列实现,但是如何查看元素并从队列中删除元素?黑莓队列队列实现的Peek()和remove()方法
请帮忙,
在此先感谢。
尝试使用Arrays类...如果你需要偷看,采取最后一个元素的对象数组,只删除删除最后一个:
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());
}
}
使用例如:
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());
}
}
}
谢谢Coldice,它帮了我 – iOSDev 2009-12-08 06:55:45
不客气! – 2009-12-08 08:13:05
'Arrays.remove'从OS 4.0开始就没有记录,理由很充分:它在某些版本中不起作用。 – 2012-02-23 16:14:12