【问题标题】:Difference between add() and offer() methods of Queue interfaceQueue接口的add()和offer()方法的区别
【发布时间】:2013-12-11 18:16:24
【问题描述】:

我正在研究 Java 中的 FIFO 实现,并遇到了这个 java.util.Queue 接口。 Dequeue 实现它,而它又由 Linked List 实现。

我写了以下代码

public class FIFOTest {

    public static void main(String args[]){

        Queue<String> myQueue = new LinkedList<String>();
        myQueue.add("US");
        myQueue.offer("Canada");

        for(String element : myQueue){
            System.out.println("Element : " + element);
        }
    }

}

两者似乎都在做同样的事情。将数据添加到队列的头部。这两种方法有什么区别?任何一种都比其他更有益的特殊情况?

【问题讨论】:

标签: java queue fifo


【解决方案1】:

LinkedList#offer(E) 实现为

public boolean offer(E e) {
    return add(e);
}

在这种情况下,它们是相同的。它们只需要满足接口。 LinkedList 实现 DequeListLinkedList#add(E) 方法不会抛出 Exception,因为它总是需要更多元素,但是在另一个容量有限或只接受某些类型元素的 Queue 实现中,add(E) 可能会抛出异常,而 offer(E)只会返回false

【讨论】:

  • 我猜 poll() 和 remove() 也一样?
  • @Aniket 不完全是。如果没有元素,poll 将返回 nullremove() 将抛出 NoSuchElementException
  • 这是相同的想法:offer()poll() 在失败时返回特殊值,而 add()remove() 抛出异常。
【解决方案2】:

根据the docs,主要区别在于,当操作失败时,一个(add)抛出异常,另一个(offer)返回一个特殊值(false):

这些方法中的每一种都以两种形式存在:一种在操作失败时抛出异常,另一种返回特殊值(null 或 false,取决于操作)。后一种形式的插入操作是专门为与容量受限的队列实现一起使用而设计的;在大多数实现中,插入操作不会失败。

【讨论】:

    【解决方案3】:

    这两种方法有什么区别?

    • Queue.add - 如果操作失败则抛出异常,
    • Queue.offer- 返回一个特殊值(nullfalse,取决于操作)。

    任何一种都比其他更有益的特殊情况?

    根据文档,插入操作的 Queue.offer 形式是专门为 与容量受限的队列实现一起使用;多数情况 实现,插入操作不会失败。

    详情请阅读docs

    【讨论】:

      【解决方案4】:
      • add() 来自Collection 接口。
      • offer() 来自Queue 接口。

      队列的offer()方法的文档说

        Inserts the specified element into this queue if it is possible to do
        so immediately without violating capacity restrictions.
        When using a capacity-restricted queue, this method is generally
        preferable to {@link #add}, which can fail to insert an element only
        by throwing an exception.
      

      队列的add()方法的文档说

       Inserts the specified element into this queue if it is possible to do so
       immediately without violating capacity restrictions, returning
       <tt>true</tt> upon success and throwing an <tt>IllegalStateException</tt>
       if no space is currently available.
      

      【讨论】:

        猜你喜欢
        • 2015-05-19
        • 2016-02-24
        • 2013-03-13
        • 2022-10-18
        • 1970-01-01
        • 2019-02-20
        • 1970-01-01
        • 1970-01-01
        • 2013-07-09
        相关资源
        最近更新 更多