Java 队列中的 add 和 offer 方法有什么区别?

2022-01-21 00:00:00 queue add java

PriorityQueue 为例 http://java.sun.com/j2se/1.5.0/docs/api/java/util/PriorityQueue.html#offer(E)

谁能给我一个 队列其中 addoffer 方法不一样?

Can anyone give me an example of a Queue where the add and offer methods are different?

根据Collection doc,add 方法通常会寻求确保元素存在于 Collection 中,而不是添加重复项.所以我的问题是,addoffer 方法有什么区别?

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 中,addoffer 方法是相同的方法(请参阅下面的答案).谁能给我一个 addoffer 方法不同的类的例子吗?

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.

相关文章