从 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
广告