问题
Have tried out a sample program to understand the difference between addFirst
and offerFirst
methods in ArrayDeque
of Java 6. But they seem to be same, any suggestions?
public void interfaceDequetest()
{
try{
ArrayDeque<String> ad = new ArrayDeque<String>();
ad.addFirst("a1");
ad.offerFirst("o1");
ad.addFirst("a2");
ad.offerFirst("02");
ad.addFirst("a3");
System.out.println("in finally block");
for (String number : ad){
System.out.println("Number = " + number);
}
}
回答1:
The difference is what happens when the addition fails, due to a queue capacity restriction:
.addFirst()
throws an (unchecked) exception,.offerFirst()
returnsfalse
.
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.
回答2:
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 ...
来源:https://stackoverflow.com/questions/22293468/differnce-between-addfirst-and-offerfirst-methods-in-arraydeque