Queue offer vs add - what's the difference?

843    Asked by alexGONZALEZ in Java , Asked on Oct 13, 2022

 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?

Answered by Anil Mer

Queue Offer vs Add

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



Your Answer

Interviews

Parent Categories