[英]java LinkedList methods getFirst() and element()
So I can see that from previous answers in stackoverflow that there is a difference between getFirst
and peekFirst
as peekFirst
won't throw an exception
if the LinkedList is empty.所以我可以从 stackoverflow 的先前答案中看到getFirst
和peekFirst
之间存在差异,因为如果 LinkedList 为空, peekFirst
不会抛出exception
。
But what is the difference between getFirst
and element
?但是getFirst
和element
之间有什么区别?
getFirst() Returns the first element in this list. getFirst() 返回此列表中的第一个元素。
element() Retrieves, but does not remove, the head (first element) of this list. element() 检索但不删除此列表的头部(第一个元素)。
Both will throw out NoSuchElementException
if empty.如果为空,两者都会抛出NoSuchElementException
。
Thanks!谢谢!
They are equivalent as specified in the Deque
docs.它们与Deque
文档中指定的相同。
Retrieves, but does not remove, the head of the queue represented by this deque (in other words, the first element of this deque).检索但不删除此双端队列表示的队列的头部(换句话说,此双端队列的第一个元素)。 This method differs from peek only in that it throws an exception if this deque is empty.此方法与 peek 的不同之处仅在于,如果此双端队列为空,它会引发异常。
This method is equivalent to getFirst().此方法等效于 getFirst()。
https://docs.oracle.com/javase/7/docs/api/java/util/Deque.html#element() https://docs.oracle.com/javase/7/docs/api/java/util/Deque.html#element()
element
is in the Queue
interface, while getFirst
is not. element
在Queue
接口中,而getFirst
不在。 But (as noted elsewhere) the behaviors are the same.但是(如其他地方所述)行为是相同的。
The source code for LinkedList says it all: LinkedList的源代码说明了一切:
public E element() {
return getFirst();
}
The element()
method just calls getFirst()
. element()
方法只调用getFirst()
。 So, in the case of the LinkedList
implementation of List
, both methods effectively do the same thing.因此,在List
的LinkedList
实现的情况下,两种方法都有效地执行相同的操作。
Note: The other implementation of the Deque
interface, ArrayDeque
, also has an element()
implementation which just calls getFirst()
.注意: Deque
接口的另一个实现ArrayDeque
也有一个element()
实现, ArrayDeque
调用getFirst()
。
There is no difference, the implementation of element
is没有区别, element
的实现是
public E element() {
return getFirst();
}
The javadoc even states javadoc 甚至指出
This method is equivalent to {@link #getFirst()}这个方法等价于 {@link #getFirst()}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.