What is the difference between element/peek, remove/poll, add/offer commonly used in Queue


What is the difference between element/peek, remove/poll, add/offer commonly used in Queue

Although the bottom layer of ArrayList is an array, the addition and deletion operations after optimization are still not slow, which makes the LindedList rarely appear in our field of vision. But when it comes to Stack and Queue time (mainly brush title), LinkedList is still very common, because the bottom is a doubly linked list, but also realized the Deque interface is often made dizzy variety of methods, mainly as follows:
Insert picture description here
where The element/peek, remove/poll, and add/offer methods of the interface Queue have similar functions. The subtle differences are as follows:

  • Both element() and peek() are used to query elements at the head of the queue. Among them, element() will throw NoSuchElementException when checking the space, and peek() will return null when checking the space (come, go to the source code).
    Insert picture description here
    Insert picture description here
    Note on element(): Retrieve data, but do not delete the head of this queue. The difference between this method and peek() is that it throws a NoSuchElementException if the queue is empty.
    Note on peek(): Retrieve data, but do not delete the head of this queue. When this queue is empty, null will be returned.
    Let's take a look at how the method implementation in LinkedList is written:
    Insert picture description here
    Insert picture description here
  • Both remove() and poll() remove the first element from the queue. Among them, remove() will throw NoSuchElementException when deleting, and poll() will return null when deleting (come, source code).
    Insert picture description here
    Insert picture description here
    The meaning of the annotation and the specific implementation in LindedList are similar to element()/peek(), so I won’t be wordy here anymore.
  • Both add() and offer() add an element to the queue. Some queues have size limits, so if you want to add a new item to a full queue, calling the add() method will throw an IllegalStateException exception, and calling the offer() method will return false (come, source code).
    Insert picture description here
    Insert picture description here
    The note above add(): If the capacity limit is not violated, the specified element can be inserted into this queue and return true. If it fails, an IllegalStateException will be thrown.
    The above note of offer(): If the capacity limit is not violated, the specified element can be inserted into this queue and return true, if it fails, it returns false.

Record your own study notes for the first time. If you find any problems, please give pointers.

Guess you like

Origin blog.csdn.net/qq_42647711/article/details/108409315