What is the difference between the add and offer methods in a Queue in Java?
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.
- offer method - tries to add an element to a queue, and returns false if the element can't be added (like in case when a queue is full), or true if the element was added, and doesn't throw any specific exception.
- add method - tries to add an element to a queue, returns true if the element was added, or throws an IllegalStateException if no space is currently available.
There is no difference for the implementation of
PriorityQueue.add
:public boolean add(E e) {
return offer(e);
}
For
AbstractQueue
there actually is a difference:public boolean add(E e) {
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}
Comments
Post a Comment