16

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?

yannis
  • 39,547
  • 40
  • 183
  • 216
agent13
  • 391
  • 1
  • 2
  • 8

2 Answers2

25

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).

yannis
  • 39,547
  • 40
  • 183
  • 216
6

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, else false...

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.

gnat
  • 21,442
  • 29
  • 112
  • 288
  • 2
    Pffft you went and looked at the docs. Weak. ;P – yannis Mar 12 '13 at 13:13
  • 1
    @YannisRizos next thing you'll see would be me [complaining like Col Shrapnel](http://meta.stackexchange.com/q/171172/165773) :) _oh you can't compete with 30-seconds answers: a question will get 5 answers before you can even find an appropriate link blah blah_ – gnat Mar 12 '13 at 13:16