队列接口在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);