这似乎是一个非常基本的问题,但我一直坚持了几个小时。Enqueue/Dequeue OR offer/poll
什么时候使用offer/poll ?!什么时候我们使用方法enqueue/dequeue &?
我想用void enqueue(int x, int p)
和int dequeue()
方法创建整数的PQ,我该如何声明这样的队列?
谢谢。
这似乎是一个非常基本的问题,但我一直坚持了几个小时。Enqueue/Dequeue OR offer/poll
什么时候使用offer/poll ?!什么时候我们使用方法enqueue/dequeue &?
我想用void enqueue(int x, int p)
和int dequeue()
方法创建整数的PQ,我该如何声明这样的队列?
谢谢。
我假设“PQ”的意思是“优先队列”。我从来没有使用过这样的队列(我的队列的心理图像是严格的FIFO结构),但在阅读文档后,我认为你可以这样做:
首先,你需要创建类您想要存储在队列中的对象。假设int
内容int
优先级:
public class MyClass implements Comparable<MyClass> {
private int x, p;
/*
* x: Contents
* p: Priority
*/
public MyClass(int x, int p) {
this.x = x;
this.p = p;
}
@override
public int compareTo(MyClass o) {
return this.p - o.p;
}
public int getX() {
return x;
}
}
现在,创建你的优先级队列。如果我理解正确类的文档,它会使用compareTo
方法的对象进行排序:
....
PriorityQueue<MyClass> pq = new PriorityQueue<MyClass>();
....
pq.add(new MyClass(x, p));
....
检查:http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html
Java的队列没有enqueue
和dequeue
方法;这些操作是使用以下方法进行:
offer(e)
:返回false
如果无法插入对象remove()
:抛出异常,如果队列为空poll()
:返回null
如果队列为空element()
:抛出异常,如果队列为空peek()
:返回null
如果队列为空而现在,最后:何时使用offer
和add
?
关于offer
和add
:嗯,这取决于你想如何处理插入的队列中失败的原因:
的从收藏继承添加方法,其中队列,插入一个元素,除非它违反了队列的容量限制,在这种情况下,它会抛出IllegalStateException。所述报价方法,其旨在仅仅上使用有界队列,不同于添加仅在于它表示失败通过返回假插入的元件。
(参见:http://docs.oracle.com/javase/tutorial/collections/interfaces/queue.html)
希望这有助于你
谢谢,它帮助了我很大。我很感激。 – InspiringProgramming
@InspiringProgramming:那么你应该接受答案,并upvote它。 –
我仍然不被允许投票,因为我的声望低于15:( 我希望我可以。 – InspiringProgramming
哪个队列你在说什么?标准['java.util.Queue'](http://docs.oracle.com/javase/6/docs/api/java/util/Queue.html)没有任何'enqueue' /'dequeue'方法。 –
有关澄清问题的详细信息,请参见['队列'](http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html)。 –
trashgod