The queue has a FIFO (first in and out) function, then how to implement this function, Hehe, Java has provided us with Api--queue, following an example to understand the API:
Import Java.util.queue;import Java.util.linkedlist;public class Testqueue {public static void Main (string[] args) { queue<string> Queue = new linkedlist<string> (); Queue.offer ("Hello");//Inserts the specified element into this queue (if it is feasible immediately and does not violate the capacity limit), the insert succeeds and returns true; When using a capacity-constrained queue, the offer method is generally better than the Add method--add method may not be able to insert elements, but only throw a illegalstateexception exception. Queue.offer ("World"); Queue.offer ("!"); System.out.println (Queue.size ());//output: 3 String str; while ((Str=queue.poll ())!=null) {//Gets and removes the header of this queue and returns null if this queue is empty. The Remove method can also get and remove the header of this queue, but the only difference between this method and the poll method is that if this queue is empty, the Remove method throws a Nosuchelementexception exception. System.out.println (str);//newline output in turn: Hello, World,! } System.out.println (Queue.size ());//output: 0 }}
The API also has two "get but not remove this queue header" method:
1, Element () Gets the header of the queue without removing the header of this queue. If this queue is empty, the nosuchelementexception exception is thrown.
2. Peek () Gets the header of the queue but does not remove the header of this queue. If this queue is empty, NULL is returned.
Queue Api--queue in Java