简体   繁体   中英

peek and element in Java's LinkedList

What is the difference between peek and element in Java's LinkedList?

Here is what the Oracle Java Documentation Page describes them to be, but they do not explain the difference.

public E peek() Retrieves, but does not remove, the head (first element) of this list. 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

public E element() Retrieves, but does not remove, the head (first element) of this list. 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

Is the difference just that one throws and exception and another returns null in case our list is empty?

Thank you

Looking at the documentation of Queue , we find the following table:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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