從 Java 佇列中移除一個元素
要從佇列中移除一個元素,請使用 remove() 方法。
首先,設定一個佇列並插入一些元素 -
Queue<String> q = new LinkedList<String>(); q.offer("abc"); q.offer("def"); q.offer("ghi"); q.offer("jkl"); q.offer("mno"); q.offer("pqr"); q.offer("stu"); q.offer("vwx");
移除第一個元素 -
System.out.println("Queue head = " + q.element()); System.out.println("Removing element from queue = " + q.remove());
以下是一個示例 -
示例
import java.util.LinkedList; import java.util.Queue; public class Demo { public static void main(String[] args) { Queue<String> q = new LinkedList<String>(); q.offer("abc"); q.offer("def"); q.offer("ghi"); q.offer("jkl"); q.offer("mno"); q.offer("pqr"); q.offer("stu"); q.offer("vwx"); System.out.println("Queue head = " + q.element()); System.out.println("Removing element from queue = " + q.remove()); System.out.println("
Remaining Queue elements..."); Object ob; while ((ob = q.poll()) != null) { System.out.println(ob); } } }
輸出
Queue head = abc Removing element from queue = abc Queue head now = abc Remaining Queue elements... def ghi jkl mno pqr stu vwx
廣告