This seems like a very basic question, but I’ve been stuck for hours.
When do we use methods enqueue/ dequeue & when do we use offer/ poll?!
I want to create a PQ of integers with the void enqueue(int x, int p) and int dequeue() methods, how do I declare such a queue?
Thanks.
I am assuming that “PQ” means “priority queue”. I’ve never used such a queue (my mental image of a queue is that of a strictly FIFO structure), but after reading documentation, I think you can do this:
First, you need to create the class of the object you want to store in the queue. Assuming
intcontents andintpriority:Now, create your priority queue. If I understood correctly the class documentation, it will use the
compareTomethod to sort your objects:Check: http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html
Java queues don’t have
enqueueanddequeuemethods; these operations are done using the following methods:add(e): throws exception if it fails to insert the objectoffer(e): returnsfalseif it fails to insert the objectremove(): throws exception if the queue is emptypoll(): returnsnullif the queue is emptyelement(): throws exception if the queue is emptypeek(): returnsnullif the queue is emptyAnd now, finally: when to use
offerandadd?About
offerandadd: Well, that depends on how do you want to handle the failure of the insertion in the queue:(see: http://docs.oracle.com/javase/tutorial/collections/interfaces/queue.html)
Hope this helps you