Programming

Queue

Queue

在使用 Java 的 Queue 接口時,可以使用以下方法進行操作:

  1. offer(element): 將元素插入到佇列的尾部,如果成功插入,返回 true;如果無法插入(例如因為佇列已滿),返回 false。

  2. add(element): 將元素插入到佇列的尾部,如果成功插入,返回 true;如果無法插入(例如因為佇列已滿),則拋出一個 unchecked 異常(IllegalStateException)。

  3. poll(): 移除並返回佇列的頭部元素,如果佇列為空,則返回 null。

  4. remove(): 移除並返回佇列的頭部元素,如果佇列為空,則拋出一個異常(NoSuchElementException)。

  5. peek(): 返回佇列的頭部元素,但不移除該元素,如果佇列為空,則返回 null。

  6. element(): 返回佇列的頭部元素,但不移除該元素,如果佇列為空,則拋出一個異常(NoSuchElementException)。

image


public class Main {
    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);
        }
    }
}
輸出結果:
a
b
c
d
e
===
poll=a
b
c
d
e
===
element=b
b
c
d
e
===
peek=b
b
c
d
e

資料來源:https://www.runoob.com/java/data-queue.html

Priority Queue


public class Main{
	
    public static void main(String args[])
    {    	
    	//Priority Queue = A FIFO data structure that serves elements
    	//                             with the highest priorities first 
    	//				  before elements with lower priority
    	
    	//Strings in default order
    	Queue<String> queue = new PriorityQueue<>();
    	
    	//Strings in reverse order
    	Queue<String> queue = new PriorityQueue<>(Collections.reverseOrder());
    	
    	queue.offer("B");
    	queue.offer("C");
    	queue.offer("A");
    	queue.offer("F");
    	queue.offer("D");
    	
    	while(!queue.isEmpty()) {
    		System.out.println(queue.poll());
    	}
    }
}