简体   繁体   English

Java 的 LinkedList 中的 peek 和 element

[英]peek and element in Java's LinkedList

What is the difference between peek and element in Java's LinkedList? Java 的 LinkedList 中的 peek 和 element 有什么区别?

Here is what the Oracle Java Documentation Page describes them to be, but they do not explain the difference.这是 Oracle Java 文档页面描述的内容,但它们没有解释差异。

public E peek() Retrieves, but does not remove, the head (first element) of this list. public E peek() 检索但不删除此列表的头部(第一个元素)。 Specified by: peek in interface Deque Specified by: peek in interface Queue Returns: the head of this list, or null if this list is empty Since: 1.5指定者:接口 Deque 中的 peek 指定者:接口队列中的 peek 返回:此列表的头部,如果此列表为空,则为 null 自:1.5

public E element() Retrieves, but does not remove, the head (first element) of this list. public E element() 检索但不删除此列表的头部(第一个元素)。 Specified by: element in interface Deque Specified by: element in interface Queue Returns: the head of this list Throws: NoSuchElementException - if this list is empty Since: 1.5指定者:接口 Deque 中的元素指定者:接口队列中的元素返回:此列表的头部抛出:NoSuchElementException - 如果此列表为空自:1.5

Is the difference just that one throws and exception and another returns null in case our list is empty?如果我们的列表为空,区别仅仅是一个抛出和异常而另一个返回 null 吗?

Thank you谢谢

Looking at the documentation of Queue , we find the following table:查看Queue的文档,我们发现下表:

Summary of Queue methods队列方法总结

Throws Exception抛出异常 Returns special value返回特殊值
Insert插入 add(e) offer(e)
Remove消除 remove() poll()
Examine检查 element() peek()

So as we can see, the difference is that element() may throw a NoSuchElementException , while peek() does not.如我们所见,不同之处在于element()可能会抛出NoSuchElementException ,而peek()不会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM