Have tried out a sample program to understand the difference between addFirst
and offerFirst
methods in ArrayDeque
of Java 6. But they
The difference is what happens when the addition fails, due to a queue capacity restriction:
.addFirst()
throws an (unchecked) exception,.offerFirst()
returns false
.This is documented in Deque, which ArrayDeque
implements.
Of note is that ArrayDeque
has no capacity restrictions, so basically .addFirst()
will never throw an exception (and .offerFirst()
will always return true
); this is unlike, for instance, a LinkedBlockingQueue built with an initial capacity.
the source code of offerFirst :
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
And addFirst
public void addFirst(E e) {
if (e == null)
throw new NullPointerException();
elements[head = (head - 1) & (elements.length - 1)] = e;
if (head == tail)
doubleCapacity();
}
offerFirst returns true, thats the only difference ...