[Java Learning] Detailed explanation of the usage of Queue and Deque implemented by LinkedList

Java's LinkedList is an important collection that can implement both one-way and two-way queues, and can also be used as a heap.
If you look at the LinkedList methods in the API, you will find that there are many methods with very similar functions, and it is impossible to tell which data structure they come from.
Next, this article will sort out the two important interfaces implemented in LinkedList: Queue and Deque.

Queue

Queue<Integer> m_queue = new LinkedList<>();

The Queue interface narrows access to methods in LinkedList and specifies specific methods for implementing a first-in-first-out queue.
At the same time, whether it is Queue or Deque, the method corresponding to each operation exists in two forms: one throws an exception when the operation fails, and the other returns a special value (null or false, depending on the operation) .

Therefore, the commonly used methods are as follows:

throw an exception Return special value
add(e) offer(e)
remove() poll()
element() peek()

When using Queue, it is recommended to use a set of functions that return special values ​​to avoid throwing exceptions directly when the method fails.

Therefore

Deque<Integer> m_deque = new LinkedList<>();

Deque inherits the Queue interface and has three main uses: double-ended queue, stack, and ordinary queue.

1. Double-ended queue

The related methods of double-ended queues are as follows:
Insert image description here
It can be found that whether it is a normal queue or a double-ended queue, the group that throws exceptions is the add, remove, and get series; the group that returns special values ​​is the offer, poll, and peek series. of.
If there are no special requirements, it is recommended to use a group that returns special values.
Another thing to note is that when Deque is used as a double-ended queue, you can also call the element() and peek() methods, which are equivalent to getFirst() and peekFirst() in the double-ended queue.

2.Stack

The stack class Stack in Java is obsolete, and it is officially recommended to use Deque to implement the stack.
Deque as a stack only needs to remember three methods:
push(e), pop(), peek().

3. Ordinary queue

Since Deque inherits Queue, it is completely possible to use Deque to implement a normal queue and use the Queue method above. You can also use the "first in" and "first out" methods in a double-ended queue. However, I personally suggest that if you just want to implement a normal queue, just use Queue directly, which is more concise and clear, and easier to remember.

Guess you like

Origin blog.csdn.net/weixin_43390123/article/details/122672237