LinkedList提供了几种用于同一功能的方法-为什么? [英] LinkedList offers several methods for the same function- Why?
问题描述
我正在检查 Java.util.LinkedList
类,发现Linked List类提供了几种方法
I was checking Java.util.LinkedList
class and found that Linked List class offers several methods
public void addFirst(E e)
public boolean offerFirst(E e)
public void push(E e)
所有这3种方法都会在列表的开头添加一个元素.那么为什么不同的实现需要相同的功能呢?
All these 3 methods add an element to the head of the list. So why does different implementation require for the same function?
是因为推送适用于Stack和
Is it because push is meant for Stack and
offerFirst –出队
offerFirst – Dequeue
addFirst – LinkedList
addFirst – LinkedList
还是其他一些基本原理?
or some other fundamentals?
请在此处分享一些见解.谢谢
Please share some insight here. Thanks
推荐答案
由于 Deque
接口的约定,这些方法在 LinkedList
中实现.
These are implemented in LinkedList
due to the contract of Deque
interface.
javadocs 用于 Deque
清楚地说明了区别:
And the javadocs for Deque
clearly explain the difference:
void addFirst(E e)
void addFirst(E e)
如果可以立即在不影响容量限制的情况下在此双端队列的前面插入指定的元素.在使用容量受限的双端队列时,通常最好使用方法offerFirst(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)
boolean offerFirst(E e)
将指定的元素插入此双端队列的前面,除非会违反容量限制.当使用容量受限的双端队列时,此方法通常比addFirst(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.
The ArrayBlockingQueue
class (javadocs) is an example of a bounded queue implementation that implements Deque
.
这篇关于LinkedList提供了几种用于同一功能的方法-为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!