Java Queue Usage Guide
In Java, a Queue is a data structure representing a queue (First-In-First-Out) that extends the Collection interface and provides additional methods for manipulating elements within the queue.
Common implementation classes of Queue in Java include:
- LinkedList: A queue implemented based on linked lists, which allows for fast addition and removal of elements, but has relatively lower efficiency for element access.
- PriorityQueue: A queue implemented based on a heap, which sorts elements by priority, but has relatively lower efficiency for adding and removing elements.
The Queue interface provides basic methods for manipulating elements in the queue, such as:
add(E e): Adds the specified element to the tail of the queue.offer(E e): Adds the specified element to the tail of the queue.remove(): Removes and returns the head of the queue.poll(): Removes and returns the head of the queue.peek(): Returns the head of the queue without removing it.element(): Returns the head of the queue without removing it.
Note: When using Queue, calling remove() or poll() on an empty queue will throw a NoSuchElementException. In contrast, calling peek() or element() will not throw an exception; instead, they return null or throw a NoSuchElementException.
Additionally, the Deque (Double-ended Queue) interface in Java also extends the Queue interface and provides additional methods for manipulating elements in the double-ended queue, such as:
addFirst(E e): Adds the specified element to the head of the deque.addLast(E e): Adds the specified element to the tail of the deque.removeFirst(): Removes and returns the head of the deque.removeLast(): Removes and returns the tail of the deque.getFirst(): Returns the head of the deque without removing it.getLast(): Returns the tail of the deque without removing it.
Note: When using a Deque, calling removeFirst(), removeLast(), getFirst(), or getLast() on an empty queue will throw a NoSuchElementException. In contrast, calling pollFirst(), pollLast(), peekFirst(), or peekLast() will not throw an exception; instead, they return null or throw a NoSuchElementException.
A Queue is a queue. Common queues in Java are as follows:
- ArrayBlockingQueue: A bounded blocking queue implemented based on array data structures.
- LinkedBlockingQueue: An unbounded blocking queue implemented based on linked list data structures.
- PriorityBlockingQueue: An unbounded blocking queue that supports priority sorting.
- DelayQueue: An unbounded blocking queue that supports delayed operations.
- SynchronousQueue: A blocking queue used for thread synchronization.
- LinkedTransferQueue: An unbounded blocking queue implemented based on linked list data structures.
- LinkedBlockingDeque: A bidirectional blocking queue implemented based on linked list data structures.