Обработка нулевых ссылок на очередь
На предыдущих этапах мы работали с объектом Queue
, который был правильно инициализирован. Однако в реальном программировании можно столкнуться с ситуациями, когда ссылка на Queue
(или любой другой объект) равна null
. Попытка вызвать метод у объекта, равного null
, приведет к NullPointerException
, что является распространенной ошибкой времени выполнения в Java.
Важно обрабатывать потенциальные нулевые ссылки, чтобы избежать таких ошибок. Перед вызовом методов, таких как isEmpty()
или size()
, для объекта Queue
всегда следует проверить, не равна ли ссылка на очередь null
.
Давайте еще раз модифицируем нашу программу QueueCheck.java
, чтобы показать, как обрабатывать нулевую ссылку на очередь.
-
Откройте файл QueueCheck.java
в редакторе WebIDE.
-
Измените метод main
, чтобы он включал проверку на нулевую ссылку на очередь. Замените существующий метод 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
.
-
Сохраните измененный файл QueueCheck.java
.
-
Откройте терминал и убедитесь, что вы находитесь в каталоге ~/project
.
-
Скомпилируйте обновленную Java-программу:
javac QueueCheck.java
-
Запустите скомпилированную программу:
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
. Всегда помните проверять на null
при работе с ссылками на объекты в Java, особенно если они могут поступать из внешних источников или быть результатом операций, которые могут вернуть null
.