查看 Java 的链表中的元素

peek and element in Java's LinkedList

Java 的 LinkedList 中的 peek 和 element 有什么区别?

这是 Oracle Java 文档页面对它们的描述,但它们没有解释区别。

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.5

public 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

区别只是一个抛出异常和另一个 returns null 以防我们的列表为空吗?

查看 the documentation of Queue,我们发现以下 table:

Summary of Queue methods

Throws Exception Returns special value
Insert add(e) offer(e)
Remove remove() poll()
Examine element() peek()

所以正如我们所见,不同之处在于 element() may throw a NoSuchElementException, while peek() 没有。