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
Answer from dvd on Stack OverflowInserts 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.
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.
The short answer: it depends on the concrete implementation.
If your queue has a max capacity limit, there actually is a difference.
- Case #1 (no max capacity limit) applied:
There is no difference like the implementation of PriorityQueue:
public boolean add(E e) {
return offer(e);
}
- Case #2 (max capacity limit) applied:
There actually is a difference like the implementation of ArrayBlockingQueue which extends AbstractQueue :
// ArrayBlockingQueue which extends AbstractQueue
public boolean add(E e) {
return super.add(e);
}
// AbstractQueue
public boolean add(E e) {
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}
offer: if the queue is full, returnfalseand will not throw an exceptionadd: if the queue is full, throw an exception
Videos
Should I implement a queue using the LinkedList class or the ArrayDeque class. What are the pros and cons of using either.