初学Collection之三

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

import javax.crypto.IllegalBlockSizeException;

public class App {
    public static void main(String[] args) {
        Queue<Integer> q1 = new ArrayBlockingQueue<>(3);
        try {
            System.out.println(q1.element());// 由于没有元素会抛出异常
        } catch (Exception e) {
            // TODO: handle exception
        }
        System.out.println("no elememts");

        q1.add(1);
        q1.add(2);
        q1.add(3);

        try {
            q1.add(4);
        } catch (Exception e) {
            System.out.println("too many elements");
        }

        System.out.println("the elements in q1");
        for (Integer value : q1)
            System.out.println(value);

        System.out.println("remove elements");

        System.out.println(q1.remove());
        System.out.println(q1.remove());
        System.out.println(q1.remove());

        System.out.println("the rest elements in q1");
        for (Integer value : q1)
            System.out.println(value);

        /// 另外的查看输入,删除方法,如果超过约定的大小,不会抛出异常
        Queue<Integer> q2 = new ArrayBlockingQueue<>(2);
        System.out.println(q2.peek());

        q2.offer(1);
        q2.offer(2);
        q2.offer(3);
        System.out.println("the elements in q2");
        for (Integer value : q2)
            System.out.println(value);

        System.out.println("remove elements");
        System.out.println(q2.poll());
        System.out.println(q2.poll());
        System.out.println(q2.poll());
        System.out.println("the rest elements in q1");

        for (int value : q2)
            System.out.println(value);

    }
}

Queue的特点是元素的输入输出采用先入先出的方式,其中的一种ArrayBlockingQueue是需要规定大小的,这样,如果操作越界的话会有异常抛出;而LinkedQueue是没有大小规定的。

猜你喜欢

转载自blog.csdn.net/juttajry/article/details/48931125