Java中的集合Queue

package com.zhaogang.test;

import org.junit.Test;

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

/**
 * Created by weixiang.wu on 2017/10/9.
 */
public class TestQueue {

    /**
     * 在java5中新增加了java.util.Queue接口,用以支持队列的常见操作。Queue接口与List、Set同一级别,都是继承了Collection接口。
     * Queue使用时要尽量避免Collection的add()和remove()方法,而是要使用offer()来加入元素,使用poll()来获取并移出元素。它们的优
     * 点是通过返回值可以判断成功与否,add()和remove()方法在失败的时候会抛出异常。 如果要使用前端而不移出该元素,使用
     * element()或者peek()方法。
     * 值得注意的是LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Queue来用。
     */
    @Test
    public void testQueue() {
        Queue<String> queue = new LinkedList<>();
        queue.offer("hi,");
        queue.offer("world");
        queue.offer("!");
        String str;
        System.out.println(queue.size());
        while ((str = queue.poll()) != null) {
            System.out.println(str);
        }
        System.out.println(queue.size());
    }
}

输出结果: 

3
hi,
world
!
0

转载于:https://my.oschina.net/wuweixiang/blog/1548005

原文地址:https://www.cnblogs.com/twodog/p/12139236.html