java.util.Queue usage

Transfer from https://www.cnblogs.com/linjiqin/archive/2013/05/30/3107656.html Ruthless

A queue is a special linear table, which allows only the front end of the table delete operation (Front), while the rear end of insertion, the table (rear). Referred to as the tail end of the end, delete operation will be referred to as head-of-insertion operation. When there is no queue element, called an empty queue.

In such a queue data structure, the first insertion element will be the first element to be deleted; conversely the last inserted element will be deleted is the last element, the queue also known as "first in first out" (FIFO-first in first out) linear form.

In java5 new addition to java.util.Queue interface for common operations support queue. The interface extends the java.util.Collection interface.

When using the Queue To avoid add Collection () and remove () method, but to use the offer () to add elements, using poll () to capture and removal elements. Their advantage is based on success return value, add () and remove () method throws an exception when the failure. To use the front out of the element without using
element () or peek () method.

It is noteworthy that LinkedList class implements the Queue interface, so that we can put to use LinkedList as a Queue.

package com.ljq.test;

import java.util.LinkedList;
import java.util.Queue;

public class QueueTest {
    public static void main(String[] args) {
        //add()和remove()方法在失败的时候会抛出异常(不推荐)
        Queue<String> queue = new LinkedList<String>();
        //添加元素
        queue.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()); //返回第一个元素,并在队列中删除
        for(String q : queue){
            System.out.println(q);
        }
        System.out.println("===");
        System.out.println("element="+queue.element()); //返回第一个元素 
        for(String q : queue){
            System.out.println(q);
        }
        System.out.println("===");
        System.out.println("peek="+queue.peek()); //返回第一个元素 
        for(String q : queue){
            System.out.println(q);
        }
        
    }
}

Guess you like

Origin blog.csdn.net/weixin_39285712/article/details/90346381