本文介绍了Java中Queue中的add和offer方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 以 PriorityQueue 为例 http://java.sun.com/j2se/1.5.0/docs/api/java/util/PriorityQueue.html#offer(E)Take the PriorityQueue for example http://java.sun.com/j2se/1.5.0/docs/api/java/util/PriorityQueue.html#offer(E)任何人都可以给我一个 队列 其中 添加 和 offer 方法不同?Can anyone give me an example of a Queue where the add and offer methods are different?根据 集合 doc, add 方法经常会寻求确保元素存在于集合中,而不是添加重复项。所以我的问题是, 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 中添加和商品方法是相同的方法(参见下面的答案)。任何人都可以给我一个类的示例,其中添加和商品方法有所不同吗?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),方法提供通常是,优于方法 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中Queue中的add和offer方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-30 12:54