package 队列queue; import java.util.LinkedList; import java.util.NoSuchElementException; import java.util.Queue; /** * * 创建时间:2017年12月8日 下午3:47:25 * 项目名称:集合 * @author ukyozq * @version 1.0 * @since JDK 9.0 * 文件名称:Queue_Test01.java * -----------------------------------------------------------------~ * 类说明:以下代码显示如何将链表用作 FIFO[*]队列. * [*] First Input First Output 的缩写,先入先出队列, * 这是一种传统的按序执行方法,先进入的指令先完成并引退,跟着才执行第二条指令 -------------------------------------------------^_^---------------*/ public class Queue_Test01 { public static void main(String[] args) { /*------------------------------------------------~ LinkedList 和 PriorityQueue 是 Queue 接口的两个实现类. LinkedList 还实现了 List 接口 --------------------------------------------------*/ Queue<String> queue = new LinkedList<>(); /*--------------------------------------------------~ add() 如果可能,向队列中添加一个元素.否则,它抛出异常. offer() will work the same as add() offer() 如果不能添加元素,则将元素添加到队列中,而不抛出异常. 它在失败时返回false,成功时返回true. ----------------------------------------------------*/ queue.add("Apple"); queue.offer("Select"); queue.offer("Canada"); queue.offer("X-man"); System.out.println("Queue:"+queue); /*---------------------------------------------~ Let's remove elements until the queue is empty | 让我们 删除 元素们 直到 那 队列 为 空 | -----------------------------------------------*/ /*---------------------------------------------~ [queue] ↓peek() | [10][9][8][7][6][5][4][3][2][1][0] | -> -> -> -> -> -> -> -> -> -> -> -> -> -> -> ->| -----------------------------------------------*/ while(queue.peek() != null) { System.out.println("Head Element:"+queue.peek()); queue.remove(); System.out.println("Removed one element from Queue."); System.out.println("Queue:"+queue); } /*----------------------------------------------------------~ IsEmpty()是Java中用于判断某种容器是否有元素的系统库函数。 如用来判断ArrayList,HashSet,HashMap是否有元素等。 peek() 返回队列顶部,如果队列为空而不是抛出异常,则返回null。 poll() 移除并返问队列头部的元素 。队列为空不抛出异常,返回null。 ------------------------------------------------------------*/ System.out.println("queue.isEmpty():"+queue.isEmpty()); System.out.println("queue.peek():"+queue.peek()); System.out.println("queue.poll():"+queue.poll()); try { String str = queue.element(); System.out.println("queue.element():"+str); str = queue.remove(); System.out.println("queue.remove():"+str); } catch (NoSuchElementException e) { // e.printStackTrace(); System.out.println("queue.remove(): Queue is empty."); } } } /*------------------------------------~~~~ 输出: Queue:[Apple, Select, Canada, X-man] Head Element:Apple Removed one element from Queue. Queue:[Select, Canada, X-man] Head Element:Select Removed one element from Queue. Queue:[Canada, X-man] Head Element:Canada Removed one element from Queue. Queue:[X-man] Head Element:X-man Removed one element from Queue. Queue:[] queue.isEmpty():true queue.peek():null queue.poll():null queue.remove(): Queue is empty. ---