offer()
returns boolean
whereas add()
throws Exception
if there are no elements in the Queue
. So, which one should be used in general and what are the advantages of using one over the other?

- 112
- 12
-
1Well, throwing an exception is expensive. That would be one reason to prefer the other method. In general though I'd say "depends on your requirements." – markspace Nov 22 '15 at 20:57
-
1Thanks! Any example "requirement"? – Akki Nov 22 '15 at 22:05
1 Answers
I guess the difference is in the contract, that when element can not be added to collection the add method throws an exception and offer doesn't.
From: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html#add%28E%29
If a collection refuses to add a particular element for any reason other than that it already contains the element, it must throw an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns. From:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Queue.html#offer%28E%29
Inserts the specified element into this queue, if possible. When using queues that may impose insertion restrictions (for example capacity bounds), method offer is generally preferable to method Collection.add(E), which can fail to insert an element only by throwing an exception.
Source:- What is the difference between the add and offer methods in a Queue in Java?