In java.util.PriorityQueue we have the methods add(E e)
and offer(E e)
. Both methods are documented as:
Inserts the specified element into this priority queue.
What are the differences between these two methods?
The difference is that offer()
will return false
if it fails to insert the element on a size restricted Queue, whereas add()
will throw an IllegalStateException
.
You should use offer()
when failure to insert an element would be normal, and add()
when failure would be an exceptional occurrence (that needs to be handled).
To find out the difference, one needs to follow PriorityQueue API javadocs which in turn have “Specified By” sections that refer reader to respective methods in Queue
interface:
-
Queue.add
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available…
Returns:true
(as specified by Collection.add(E))
Throws:IllegalStateException
– if the element cannot be added at this time due to capacity restrictions… -
Queue.offer
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. When using a capacity-restricted queue, this method is generally preferable to add(E), which can fail to insert an element only by throwing an exception…
Returns:true
if the element was added to this queue, elsefalse
…
Both methods are present because these are required to be implemented by declared interface.
Note that since PriorityQueue is unbounded (as stated in javadocs: “unbounded priority queue based on a priority heap…”), preference of API designers expressed above do not apply. This means it is left at programmer discretion to pick the method that better suits their needs in a specific usage context.
2