Java中的队列
队列接口在java.util包中提供,并且实现了Collection接口。队列实现FIFO,即先进先出。这意味着首先输入的元素是首先删除的元素。
演示Java中队列的程序如下所示-
示例
import java.util.LinkedList;
import java.util.Queue;
public class Example {
public static void main(String[] args) {
Queue<Integer> q = new LinkedList<>();
q.add(6);
q.add(1);
q.add(8);
q.add(4);
q.add(7);
System.out.println("The queue is: " + q);
int num1 = q.remove();
System.out.println("The element deleted from the head is: " + num1);
System.out.println("The queue after deletion is: " + q);
int head = q.peek();
System.out.println("The head of the queue is: " + head);
int size = q.size();
System.out.println("The size of the queue is: " + size);
}
}输出结果
The queue is: [6, 1, 8, 4, 7] The element deleted from the head is: 6 The queue after deletion is: [1, 8, 4, 7] The head of the queue is: 1 The size of the queue is: 4
现在让我们了解上面的程序。
队列中插入了五个元素。然后显示队列。证明这一点的代码片段如下所示-
Queue<Integer> q = new LinkedList<>();
q.add(6);
q.add(1);
q.add(8);
q.add(4);
q.add(7);
System.out.println("The queue is: " + q);队列开头的元素将被删除并显示。然后显示队列的大小。证明这一点的代码片段如下所示-
int num1 = q.remove();
System.out.println("The element deleted from the head is: " + num1);
System.out.println("The queue after deletion is: " + q);
int head = q.peek();
System.out.println("The head of the queue is: " + head);
int size = q.size();
System.out.println("The size of the queue is: " + size);热门推荐
10 登上舞台祝福语大全简短
11 最真的新春祝福语简短
12 信耶稣的人祝福语简短
13 对女友的简短祝福语
14 关于开车的祝福语简短
15 校长退休文案祝福语简短
16 八十大寿简短祝福语
17 新年稳重的祝福语简短
18 男生打球祝福语简短霸气