Queue Api--queue in Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.