Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between offer() and add() in priority queue in java? [duplicate]

Tags:

java

Why two functions for doing same thing?

Description provided in java api docs at http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html is same.

like image 765
TheCrazyProgrammer Avatar asked Mar 23 '13 19:03

TheCrazyProgrammer


People also ask

What is the difference between ADD and offer in queue?

The offer method inserts an element if possible, otherwise returning false. This differs from the Collection. add method, which can fail to add an element only by throwing an unchecked exception.

How does Java priority queue handle duplicates?

A PriorityQueue in Java does not have any restriction with regard to duplicate elements. If you want to ensure that two identical items are never present in the priority queue at the same time the simplest way would be to maintain a separate Set in parallel with the priority queue.

Does priority queue in Java allow duplicates?

Answer: Yes. Priority Queue allows duplicate values.

What is offer in priority queue?

PriorityQueue. offer() method is used to insert a particular element into the Priority Queue. It acts similar to the add() method of Priority Queue. Syntax: Priority_Queue.offer(Object element) Parameters: The parameter element is of the type PriorityQueue and refers to the element to be inserted into the Queue.


1 Answers

The two functions come from two different interfaces that PriorityQueue implements:

  • add() comes from Collection.
  • offer() comes from Queue.

For a capacity-constrained queue, the difference is that add() always returns true and throws an exception if it can't add the element, whereas offer() is allowed to return false if it can't add the element.

However, this doesn't apply to PriorityQueue; the two functions are synonymous.

like image 72
NPE Avatar answered Oct 26 '22 23:10

NPE