要从队列中删除元素,请使用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("\nRemaining 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