Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

queue java

作者:若离   发布日期:2026-02-28   浏览:74

// Queue in Java using LinkedList

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
    public static void main(String[] args) {
        // Create a queue object
        Queue<Integer> queue = new LinkedList<>();

        // Add elements to the queue
        queue.add(1);
        queue.add(2);
        queue.add(3);

        // Display the queue
        System.out.println("Queue: " + queue);

        // Remove an element from the queue (FIFO)
        int removedElement = queue.remove();
        System.out.println("Removed element: " + removedElement);

        // Display the queue after removal
        System.out.println("Queue after removal: " + queue);

        // Peek at the front element of the queue
        int frontElement = queue.peek();
        System.out.println("Front element: " + frontElement);

        // Check if the queue is empty
        boolean isEmpty = queue.isEmpty();
        System.out.println("Is the queue empty? " + isEmpty);
    }
}

解释说明:

  • Queue接口Queue 是 Java 集合框架中的一个接口,表示队列。队列是一种遵循 FIFO(先进先出)原则的数据结构。
  • LinkedList实现:这里使用 LinkedList 类来实现 Queue 接口。LinkedList 实现了 Queue 接口,并且提供了高效的插入和删除操作。
  • add() 方法:将元素添加到队列的末尾。
  • remove() 方法:移除并返回队列的第一个元素(即最早加入队列的元素)。
  • peek() 方法:查看队列的第一个元素,但不移除它。
  • isEmpty() 方法:检查队列是否为空。

希望这段代码和解释能帮助你理解如何在 Java 中使用队列。

上一篇:java中protected的作用

下一篇:java 随机

大家都在看

java url decode

java判断是windows还是linux

java连接数据库的代码

java date类型比较大小

java djl

ubuntu 卸载java

es java api

java list 查找

java 解压rar

java读取excel中的图片

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站