The queue interface is the same level as list and set, and both inherit the collection interface. LinkedList implements the queue interface.
In this data structure of the queue, the first element to be inserted will be the first to be deleted, whereas the last element inserted will be the most
The queue is also known as the "FIFO" (Fifo-first in first out) linear table after the element is deleted.
A new Java.util.Queue interface has been added in Java5 to support common operations on queues. The interface extends the Java.util.Collection interface.
To avoid collection's add () and remove () methods as much as possible, use the offer () to add elements and use poll () to get and move out of the element. Their advantage is that the return value can be used to determine success or failure, and the Add () and remove () methods throw exceptions when they fail. If you want to use the front end without moving the element, use the
Element () or peek () method.
It is worth noting that the LinkedList class implements the queue interface, so we can use LinkedList as a queue.
Packagecom.ljq.test;Importjava.util.LinkedList;ImportJava.util.Queue; Public classQueuetest { Public Static voidMain (string[] args) {//The Add () and remove () methods throw exceptions when they fail (not recommended)queue<string> queue =NewLinkedlist<string>(); //adding elementsQueue.offer ("a"); Queue.offer ("B"); Queue.offer (C); Queue.offer ("D"); Queue.offer (E); for(String q:queue) {System.out.println (q); } System.out.println ("==="); System.out.println ("Poll=" +queue.poll ());//returns the first element and deletes it in a queue for(String q:queue) {System.out.println (q); } System.out.println ("==="); System.out.println ("Element=" +queue.element ());//returns the first element for(String q:queue) {System.out.println (q); } System.out.println ("==="); System.out.println ("Peek=" +queue.peek ());//returns the first element for(String q:queue) {System.out.println (q); } }}
Java.util.Queue usage