问题描述
尝试了一个示例程序,以了解 addFirst 和 offerFirst
方法之间的区别> ArrayDeque of Java 6.但它们似乎相同,有什么建议吗?
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);
}
}
推荐答案
差异是由于队列容量限制而在添加失败时发生的情况:
The difference is what happens when the addition fails, due to a queue capacity restriction:
-
.addFirst()
抛出(未经检查的)异常, -
.offerFirst()
返回false
。
.addFirst()
throws an (unchecked) exception,.offerFirst()
returnsfalse
.
这在,其中 ArrayDeque
implements。
This is documented in Deque
, which ArrayDeque
implements.
值得注意的是 ArrayDeque
没有容量限制,所以基本上 .addFirst()
永远不会抛出异常( .offerFirst()
将始终返回 true
);例如,这与。
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.
这篇关于ArrayDeque中addfirst和offerFirst方法之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!