In-depth explanation of Java data structure – Queue.
A queue is a type of data structure that follows the first in, first out (FIFO) principle, allowing elements to be inserted at one end and removed at the other. In a queue, the end where elements are inserted is called the rear, and the end where elements are removed is called the front.
The Queue interface in Java is a subinterface of the Collection interface, which defines methods for operating on queues. Common implementations include LinkedList and ArrayDeque.
Here are the commonly used methods in the Queue interface:
- enqueue(E e): Insert element e into the end of the queue.
- dequeue(): Remove and return the element at the front of the queue.
- peek(): retrieves the element at the front of the queue without removing it.
- isEmpty() function is used to check if the queue is empty.
- size(): obtain the number of elements in the queue.
LinkedList and ArrayDeque are commonly used queue implementation classes in Java. Both of them implement the Queue interface, allowing direct use of the methods defined in the Queue interface.
- LinkedList is a data structure that implements a doubly linked list and can be used as a queue. Its enqueue(E e) method inserts an element at the end of the list, while the dequeue() method removes and returns the first element of the list.
Sample code:
Queue<Integer> queue = new LinkedList<>();
queue.enqueue(1); // 队列中插入元素1
queue.enqueue(2); // 队列中插入元素2
System.out.println(queue.peek()); // 输出队头元素
int num = queue.dequeue(); // 删除队头元素,并返回该元素
System.out.println(num); // 输出删除的元素
System.out.println(queue.isEmpty()); // 判断队列是否为空
System.out.println(queue.size()); // 输出队列中元素的个数
- ArrayDeque is a class that implements a double-ended queue, and can also serve as an implementation of a queue. Its enqueue(E e) method inserts an element at the end of the double-ended queue, and the dequeue() method removes the first element of the double-ended queue and returns it.
Sample code:
Queue<Integer> queue = new ArrayDeque<>();
queue.enqueue(1); // 队列中插入元素1
queue.enqueue(2); // 队列中插入元素2
System.out.println(queue.peek()); // 输出队头元素
int num = queue.dequeue(); // 删除队头元素,并返回该元素
System.out.println(num); // 输出删除的元素
System.out.println(queue.isEmpty()); // 判断队列是否为空
System.out.println(queue.size()); // 输出队列中元素的个数
The application scenarios of queues are very extensive, such as implementing message queues and thread pools, where queue data structures can be used.