如何检查 Java 中的队列是否为空

JavaJavaBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在这个实验中,你将学习如何检查 Java 中的 Queue 是否为空。这是在处理队列时避免错误的一项关键技能。

我们将探讨用于此检查的主要方法 isEmpty(),还将了解如何使用 size() 方法验证队列的状态。此外,我们将介绍如何处理队列可能为 null 的情况。通过实际操作示例,你将获得判断 Java 队列是否为空的实践经验。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/DataStructuresGroup(["Data Structures"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/DataStructuresGroup -.-> java/collections_methods("Collections Methods") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("Exceptions") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/linkedlist("LinkedList") subgraph Lab Skills java/if_else -.-> lab-559972{{"如何检查 Java 中的队列是否为空"}} java/collections_methods -.-> lab-559972{{"如何检查 Java 中的队列是否为空"}} java/exceptions -.-> lab-559972{{"如何检查 Java 中的队列是否为空"}} java/linkedlist -.-> lab-559972{{"如何检查 Java 中的队列是否为空"}} end

使用 isEmpty() 检查队列

在这一步中,我们将探讨如何使用 isEmpty() 方法检查 Java 中的 Queue 是否为空。这是处理集合时的一项基本操作,因为它能让我们避免在尝试从空队列中访问元素时可能出现的错误。

首先,让我们创建一个简单的 Java 程序来演示 isEmpty() 的用法。

  1. 打开 WebIDE,在左侧的文件资源管理器中导航到 ~/project 目录。

  2. 在文件资源管理器的空白处右键单击,选择“新建文件”,并将其命名为 QueueCheck.java

  3. 在编辑器中打开 QueueCheck.java 文件。

  4. 将以下代码复制并粘贴到编辑器中:

    import java.util.LinkedList;
    import java.util.Queue;
    
    public class QueueCheck {
    
        public static void main(String[] args) {
            // Create a Queue using LinkedList
            Queue<String> myQueue = new LinkedList<>();
    
            // Check if the queue is empty
            boolean isEmptyBeforeAdd = myQueue.isEmpty();
            System.out.println("Is the queue empty before adding elements? " + isEmptyBeforeAdd);
    
            // Add some elements to the queue
            myQueue.add("Element 1");
            myQueue.add("Element 2");
    
            // Check if the queue is empty again
            boolean isEmptyAfterAdd = myQueue.isEmpty();
            System.out.println("Is the queue empty after adding elements? " + isEmptyAfterAdd);
        }
    }

    让我们快速回顾一下这段代码的新部分:

    • import java.util.LinkedList;import java.util.Queue;:这两行导入了处理队列所需的类。我们使用 LinkedList 作为 Queue 接口的具体实现。
    • Queue<String> myQueue = new LinkedList<>();:这行代码创建了一个名为 myQueue 的新 Queue 对象,它可以容纳 String 元素。
    • myQueue.isEmpty():这是我们关注的方法。如果队列中没有元素,它返回 true,否则返回 false
    • myQueue.add("Element 1");:这将一个元素添加到队列的末尾。
  5. 保存 QueueCheck.java 文件(Ctrl+S 或 Cmd+S)。

  6. 打开 WebIDE 底部的终端。确保你位于 ~/project 目录中。如果不是,请输入 cd ~/project 并按回车键。

  7. 通过输入以下命令并按回车键来编译 Java 程序:

    javac QueueCheck.java

    如果编译成功,你将看不到任何输出。~/project 目录中会创建一个 QueueCheck.class 文件。

  8. 通过输入以下命令并按回车键来运行编译后的 Java 程序:

    java QueueCheck

    你应该会看到类似以下的输出:

    Is the queue empty before adding elements? true
    Is the queue empty after adding elements? false

这个输出证实了 isEmpty() 方法正确地报告了添加元素前后队列的状态。使用 isEmpty() 是检查集合是否为空的推荐方法,因为它通常比检查大小是否为零更高效,特别是对于某些集合实现。

使用 size() 方法验证

在上一步中,我们学习了如何使用 isEmpty() 方法检查队列是否为空。另一种判断集合是否为空的方法是检查其大小。size() 方法会返回集合中元素的数量。如果大小为 0,则集合为空。

虽然由于某些集合类型可能存在性能优势,通常更推荐使用 isEmpty() 来检查是否为空,但了解如何使用 size() 也很重要。

让我们修改 QueueCheck.java 程序,使其也使用 size() 方法。

  1. 在 WebIDE 编辑器中打开 QueueCheck.java 文件。

  2. 修改 main 方法,使其包含使用 size() 方法的检查。将现有的 main 方法替换为以下代码:

    import java.util.LinkedList;
    import java.util.Queue;
    
    public class QueueCheck {
    
        public static void main(String[] args) {
            // Create a Queue using LinkedList
            Queue<String> myQueue = new LinkedList<>();
    
            // Check if the queue is empty using isEmpty()
            boolean isEmptyBeforeAdd = myQueue.isEmpty();
            System.out.println("Is the queue empty before adding elements (isEmpty())? " + isEmptyBeforeAdd);
    
            // Check if the queue is empty using size()
            boolean isEmptyBySizeBeforeAdd = (myQueue.size() == 0);
            System.out.println("Is the queue empty before adding elements (size() == 0)? " + isEmptyBySizeBeforeAdd);
    
    
            // Add some elements to the queue
            myQueue.add("Element 1");
            myQueue.add("Element 2");
    
            // Check if the queue is empty again using isEmpty()
            boolean isEmptyAfterAdd = myQueue.isEmpty();
            System.out.println("Is the queue empty after adding elements (isEmpty())? " + isEmptyAfterAdd);
    
            // Check if the queue is empty again using size()
            boolean isEmptyBySizeAfterAdd = (myQueue.size() == 0);
            System.out.println("Is the queue empty after adding elements (size() == 0)? " + isEmptyBySizeAfterAdd);
    
            // Print the size of the queue
            System.out.println("Current queue size: " + myQueue.size());
        }
    }

    在这段更新后的代码中,我们添加了一些代码行,用于在添加元素前后检查队列的 size() 是否等于 0。我们还打印了队列的最终大小。

  3. 保存修改后的 QueueCheck.java 文件。

  4. 打开终端,确保你位于 ~/project 目录中。

  5. 编译更新后的 Java 程序:

    javac QueueCheck.java
  6. 运行编译后的程序:

    java QueueCheck

    你现在应该会看到类似以下的输出:

    Is the queue empty before adding elements (isEmpty())? true
    Is the queue empty before adding elements (size() == 0)? true
    Is the queue empty after adding elements (isEmpty())? false
    Is the queue empty after adding elements (size() == 0)? false
    Current queue size: 2

如你所见,isEmpty() 和检查 size() == 0 在判断队列是否为空时会得到相同的结果。size() 方法对于确切了解队列中当前有多少元素也很有用。

处理空队列(Null Queues)

在前面的步骤中,我们处理的是一个已正确初始化的 Queue 对象。然而,在实际编程中,你可能会遇到 Queue(或任何对象)引用为 null 的情况。尝试对 null 对象调用方法会导致 NullPointerException,这是 Java 中常见的运行时错误。

处理潜在的 null 引用以防止这些错误至关重要。在对 Queue 调用 isEmpty()size() 等方法之前,你应该始终检查队列引用本身是否为 null

让我们再次修改 QueueCheck.java 程序,以演示如何处理 null 队列。

  1. 在 WebIDE 编辑器中打开 QueueCheck.java 文件。

  2. 修改 main 方法,使其包含对 null 队列的检查。将现有的 main 方法替换为以下代码:

    import java.util.LinkedList;
    import java.util.Queue;
    
    public class QueueCheck {
    
        public static void main(String[] args) {
            // Create a Queue using LinkedList
            Queue<String> myQueue = new LinkedList<>();
    
            // Check if the queue is null before checking emptiness or size
            if (myQueue != null) {
                // Check if the queue is empty using isEmpty()
                boolean isEmptyBeforeAdd = myQueue.isEmpty();
                System.out.println("Is the queue empty before adding elements (isEmpty())? " + isEmptyBeforeAdd);
    
                // Check if the queue is empty using size()
                boolean isEmptyBySizeBeforeAdd = (myQueue.size() == 0);
                System.out.println("Is the queue empty before adding elements (size() == 0)? " + isEmptyBySizeBeforeAdd);
    
    
                // Add some elements to the queue
                myQueue.add("Element 1");
                myQueue.add("Element 2");
    
                // Check if the queue is empty again using isEmpty()
                boolean isEmptyAfterAdd = myQueue.isEmpty();
                System.out.println("Is the queue empty after adding elements (isEmpty())? " + isEmptyAfterAdd);
    
                // Check if the queue is empty again using size()
                boolean isEmptyBySizeAfterAdd = (myQueue.size() == 0);
                System.out.println("Is the queue empty after adding elements (size() == 0)? " + isEmptyBySizeAfterAdd);
    
                // Print the size of the queue
                System.out.println("Current queue size: " + myQueue.size());
            } else {
                System.out.println("The queue is null. Cannot perform operations.");
            }
    
            // Example with a null queue reference
            Queue<String> nullQueue = null;
    
            // Attempting to check isEmpty() or size() on nullQueue without a null check would cause a NullPointerException
            System.out.println("\nChecking a potentially null queue:");
            if (nullQueue != null) {
                 boolean isNullQueueEmpty = nullQueue.isEmpty();
                 System.out.println("Is the null queue empty? " + isNullQueueEmpty);
            } else {
                 System.out.println("The null queue is indeed null. Handled correctly.");
            }
        }
    }

    我们将操作 myQueue 的原始代码包装在 if (myQueue != null) 块中。这确保了只有当 myQueue 不为 null 时,我们才会对其调用方法。我们还添加了一个部分,用于演示检查显式设置为 null 的变量。

  3. 保存修改后的 QueueCheck.java 文件。

  4. 打开终端,确保你位于 ~/project 目录中。

  5. 编译更新后的 Java 程序:

    javac QueueCheck.java
  6. 运行编译后的程序:

    java QueueCheck

    你应该会看到类似以下的输出:

    Is the queue empty before adding elements (isEmpty())? true
    Is the queue empty before adding elements (size() == 0)? true
    Is the queue empty after adding elements (isEmpty())? false
    Is the queue empty after adding elements (size() == 0)? false
    Current queue size: 2
    
    Checking a potentially null queue:
    The null queue is indeed null. Handled correctly.

此输出表明,我们的代码正确处理了队列已初始化和队列引用为 null 这两种情况,从而避免了 NullPointerException。在 Java 中处理对象引用时,尤其是当它们可能来自外部源或可能是返回 null 的操作结果时,始终要记得检查 null

总结

在本次实验中,我们学习了如何检查 Java 中的 Queue 是否为空。我们主要关注使用 isEmpty() 方法,这是执行此检查的标准且推荐的方式。我们创建了一个简单的 Java 程序,以演示 isEmpty() 方法在队列为空时返回 true,在添加元素后返回 false

此外,我们还探索了使用 size() 方法作为检查队列是否为空的另一种方式,并指出大小为 0 表示队列为空。最后,我们讨论了在尝试对队列对象调用方法之前检查其是否为 null 的重要性,以避免潜在的 NullPointerException