java - Queue#offer() 应该优先于 Queue#add() 吗?为什么?

标签 java queue

offer() 返回 boolean,而如果 Queue 中没有元素,add() 会抛出 Exception。那么,一般应该使用哪一种以及使用其中一种相对于另一种有哪些优势?

最佳答案

我想区别在于契约(Contract),当元素无法添加到集合中时,add 方法会抛出异常,而 Offer 不会。

来自: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.

来源:- What is the difference between the add and offer methods in a Queue in Java?

关于java - Queue#offer() 应该优先于 Queue#add() 吗?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33860018/

相关文章:

java - 在运行时延迟初始化 spring 安全性 + 重新加载 spring 安全性配置

java - 上载到Google Play时android应用崩溃

大小为 1 的 Java BlockingQueue?

C 队列清理指针

java - @Autowired 不能在类实例使用反射创建的类内部工作

java - NoClassDefFoundError:com/google/api/client/extensions/appengine/http/UrlFetchTransport?

c++ - 自定义队列类 C++

C++ 试图创建一个二维点(数组)队列

C# 让线程在出队时休眠?

java - 在 Spring Boot 中将 Oauth2 与 formlogin 和执行器安全性相结合