Java的LinkedList中的链表peek和元素
peek和Java的LinkedList中的元素有什么区别
以下是OracleJava文档页面对它们的描述,但它们没有解释区别
public E peek()
Retrieves, but does not remove, the head (first element) of this list.
Specified by: peek in interface Deque<E>
Specified by: peek in interface Queue<E>
Returns: the head of this list, or null if this list is empty
Since: 1.5public E element()
Retrieves, but does not remove, the head (first element) of this list. Specified by: element in interface Deque<E>
Specified by: element in interface Queue<E>
Returns: the head of this list
Throws: NoSuchElementException - if this list is empty
Since: 1.5
如果我们的列表是空的,那么一个抛出异常,另一个返回null,这就是区别吗
# 1 楼答案
查看the documentation of ^{} ,我们发现下表:
正如我们所看到的,不同之处在于^{} 可以抛出^{} ,而^{} 不抛出