Queue接口的add()和offer()方法的区别

Difference between add() and offer() methods of Queue interface(Queue接口的add()和offer()方法的区别)

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

问题描述

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

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.

我写了以下代码

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) 实现为

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

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

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()方法的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Queue接口的add()和offer()方法的区别

基础教程推荐