java - LinkedList 为同一功能提供了多种方法-为什么?

标签 java collections linked-list

这个问题在这里已经有了答案:





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)界面。
javadocsDeque清楚地说明区别:

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/

相关文章:

java - 将 linkedList 转换为数组列表时出现 ArrayIndexOutOfBoundsException

java - Eclipse "Class File Editor"调试时找不到源

java - 为什么组件没有出现在屏幕中央?

java - 如何在java中对具有多个数据排序的对象列表进行排序

vb.net - 如何在VB.NET中将List(Of T)转换为ObservableCollection(Of T)?

链表可以通过改变引用来排序吗?

java - 反转单链表

java - 需要字符串匹配器正则表达式

java - 未调用静态 block

java - 如果我的 hashCode() 很弱,在 ConcurrentHashMap 中设置 concurrencyLevel 有什么帮助?