Queue接口的add()和offer()方法之间的区别 [英] Difference between add() and offer() methods of Queue interface

查看:92
本文介绍了Queue接口的add()和offer()方法之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过Java实现FIFO,并遇到了这个java.util.Queue接口.出队实现它,然后由链表实现.

我写了以下代码

 公共类FIFOTest {公共静态void main(String args []){队列< String>myQueue = new LinkedList< String>();myQueue.add("US");myQueue.offer("Canada");for(String element:myQueue){System.out.println("Element:" + element);}}} 

两者似乎都做同样的事情.将数据添加到队列的开头.这两种方法有什么区别?在任何特殊情况下,哪一个比另一个更有利?

解决方案

LinkedList#offer(E)实现为

 公开布尔报价(E e){返回add(e);} 

在这种情况下,它们是同一回事.只需要它们来满足接口. LinkedList 实现 Deque List . LinkedList#add(E)方法将不会抛出 Exception ,因为它总是会包含更多元素,但是会在另一个受限制的 Queue 实现中容量或仅包含某些种类的元素, add(E)可能会引发异常,而 offer(E)只会返回 false .

I was going though FIFO implementation in Java and came across this java.util.Queue interface. Dequeue implements it which in turn is implemented by Linked List.

I wrote the following code

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);
        }
    }

}

Both seem to do the same thing. Add data to the head of the queue. What is the difference between these two methods? Any special cases in which either would be more beneficial than other?

解决方案

LinkedList#offer(E) is implemented as

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

In this case, they are the same thing. They are just needed to satisfy the interfaces. LinkedList implements Deque and List. The LinkedList#add(E) method will not throw an Exception as it will always take more elements, but in another Queue implementation that has limited capacity or takes only certain kinds of elements, add(E) might throw an exception while offer(E) will simply return false.

这篇关于Queue接口的add()和offer()方法之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆