这个问题在这里已经有了答案:
Differnce between addfirst and offerFirst methods in ArrayDeque
(2 个回答)
1年前关闭。
我在查Java.util.LinkedList
类,发现链表类提供了几种方法
public void addFirst(E e)
public boolean offerFirst(E e)
public void push(E e)
所有这 3 种方法都将一个元素添加到列表的头部。
那么为什么不同的实现需要相同的功能呢?
是不是因为
push 用于 Stack 和
offerFirst – 出队
addFirst – 链表
或者其他一些基础知识?
请在这里分享一些见解。谢谢
最佳答案
这些在 LinkedList
中实现由于Deque
的契约(Contract)界面。
和 javadocs为 Deque
清楚地说明区别:
void addFirst(E e)
Inserts the specified element at the front of this deque if it is possible to do so immediately without violating capacity restrictions. When using a capacity-restricted deque, it is generally preferable to use method offerFirst(E).
boolean offerFirst(E e)
Inserts the specified element at the front of this deque unless it would violate capacity restrictions. When using a capacity-restricted deque, this method is generally preferable to the addFirst(E) method, which can fail to insert an element only by throwing an exception.
ArrayBlockingQueue
类( javadocs )是实现 Deque
的有界队列实现的示例.
关于java - LinkedList 为同一功能提供了多种方法-为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34014814/