What is the difference between the add and offer methods in a Queue in Java?(Java 队列中的 add 和 offer 方法有什么区别?)
问题描述
以 PriorityQueue
为例 http://java.sun.com/j2se/1.5.0/docs/api/java/util/PriorityQueue.html#offer(E)
谁能给我一个 队列
其中 add
和 offer
方法不一样?
Can anyone give me an example of a Queue
where the add
and offer
methods are different?
根据Collection
doc,add
方法通常会寻求确保元素存在于 Collection
中,而不是添加重复项.所以我的问题是,add
和 offer
方法有什么区别?
According to the Collection
doc, the add
method will often seek to ensure that an element exists within the Collection
rather than adding duplicates. So my question is, what is the difference between the add
and offer
methods?
offer
方法是否无论如何都会添加重复项?(我怀疑这是因为如果 Collection
应该只有不同的元素,这将绕过它).
Is it that the offer
method will add duplicates regardless? (I doubt that it is because if a Collection
should only have distinct elements this would circumvent that).
在 PriorityQueue
中,add
和 offer
方法是相同的方法(请参阅下面的答案).谁能给我一个 add
和 offer
方法不同的类的例子吗?
In a PriorityQueue
the add
and offer
methods are the same method (see my answer below). Can anyone give me an example of a class where the add
and offer
methods are different?
推荐答案
我猜不同的是在合约中,当元素不能被添加到集合中时 add
方法会抛出异常并且 offer
没有.
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.
来自: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.
来自:http://java.sun.com/j2se/1.5.0/docs/api/java/util/Queue.html#offer%28E%29
将指定元素插入这个队列,如果可能的话.使用时可能强加插入的队列限制(例如容量bounds),方法offer一般是优于方法Collection.add(E),可能会失败仅通过抛出一个元素来插入一个元素例外.
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.
这篇关于Java 队列中的 add 和 offer 方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 队列中的 add 和 offer 方法有什么区别?
基础教程推荐
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01