Java 에서 큐 (Queue) 가 비어 있는지 확인하는 방법

JavaBeginner
지금 연습하기

소개

이 랩에서는 Java 에서 Queue가 비어 있는지 확인하는 방법을 배우게 됩니다. 이는 큐 (Queue) 를 사용할 때 오류를 방지하기 위한 중요한 기술입니다.

이 확인을 위한 주요 메서드인 isEmpty()를 살펴보고, size() 메서드를 사용하여 큐의 상태를 확인하는 방법도 알아보겠습니다. 또한, 큐가 null 일 수 있는 시나리오를 처리하는 방법도 다룰 것입니다. 실습 예제를 통해 Java 큐의 비어있음을 판단하는 실질적인 경험을 얻게 될 것입니다.

isEmpty() 를 사용하여 큐 확인

이 단계에서는 Java 에서 isEmpty() 메서드를 사용하여 Queue가 비어 있는지 확인하는 방법을 살펴보겠습니다. 이는 컬렉션 (collection) 을 사용할 때 기본적으로 수행해야 하는 작업으로, 빈 큐에서 요소를 접근하려 할 때 발생할 수 있는 오류를 방지할 수 있게 해줍니다.

먼저, isEmpty() 사용법을 보여주는 간단한 Java 프로그램을 만들어 보겠습니다.

  1. WebIDE 를 열고 왼쪽의 파일 탐색기에서 ~/project 디렉토리로 이동합니다.

  2. 파일 탐색기의 빈 공간을 마우스 오른쪽 버튼으로 클릭하고 "New File"을 선택한 다음, 이름을 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;: 이 줄은 큐 (Queue) 작업을 위해 필요한 클래스를 가져옵니다. Queue 인터페이스의 구체적인 구현으로 LinkedList를 사용하고 있습니다.
    • Queue<String> myQueue = new LinkedList<>();: 이 줄은 String 요소를 저장할 수 있는 myQueue라는 새 Queue 객체를 생성합니다.
    • myQueue.isEmpty(): 이것이 우리가 집중하는 메서드입니다. 큐에 요소가 없으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.
    • myQueue.add("Element 1");: 이 코드는 큐의 끝에 요소를 추가합니다.
  5. QueueCheck.java 파일을 저장합니다 (Ctrl+S 또는 Cmd+S).

  6. WebIDE 하단에서 터미널을 엽니다. ~/project 디렉토리에 있는지 확인합니다. 그렇지 않은 경우, cd ~/project를 입력하고 Enter 키를 누릅니다.

  7. 다음 명령을 입력하고 Enter 키를 눌러 Java 프로그램을 컴파일합니다.

    javac QueueCheck.java

    컴파일이 성공하면 아무런 출력도 표시되지 않습니다. ~/project 디렉토리에 QueueCheck.class 파일이 생성됩니다.

  8. 다음 명령을 입력하고 Enter 키를 눌러 컴파일된 Java 프로그램을 실행합니다.

    java QueueCheck

    다음과 유사한 출력을 볼 수 있습니다.

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

    이 출력은 isEmpty() 메서드가 요소를 추가하기 전과 후에 큐의 상태를 올바르게 보고했음을 확인합니다. isEmpty()를 사용하는 것이 컬렉션이 비어 있는지 확인하는 권장 방법입니다. 특히 특정 컬렉션 구현의 경우, 크기가 0 인지 확인하는 것보다 일반적으로 더 효율적입니다.

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 큐 처리

이전 단계에서는 제대로 초기화된 Queue 객체로 작업했습니다. 그러나 실제 프로그래밍에서는 Queue (또는 모든 객체) 에 대한 참조가 null인 상황을 만날 수 있습니다. null 객체에서 메서드를 호출하려고 하면 Java 에서 흔히 발생하는 런타임 오류인 NullPointerException이 발생합니다.

이러한 오류를 방지하려면 잠재적인 null 참조를 처리하는 것이 중요합니다. Queue에서 isEmpty() 또는 size()와 같은 메서드를 호출하기 전에 항상 큐 참조 자체가 null인지 확인해야 합니다.

null 큐를 처리하는 방법을 보여주기 위해 QueueCheck.java 프로그램을 다시 수정해 보겠습니다.

  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) 블록으로 묶었습니다. 이렇게 하면 myQueuenull이 아닌 경우에만 메서드를 호출할 수 있습니다. 또한 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() 메서드를 사용하는 데 중점을 두었습니다. 우리는 isEmpty()가 빈 큐에 대해 true를 반환하고 요소가 추가된 후 false를 반환하는 방법을 보여주는 간단한 Java 프로그램을 만들었습니다.

또한, 우리는 비어 있는지 확인하는 대체 방법으로 size() 메서드를 탐구했으며, 크기가 0 이면 빈 큐임을 나타냅니다. 마지막으로, 큐 객체에서 메서드를 호출하기 전에 큐 객체가 null 인지 확인하여 잠재적인 NullPointerException을 처리하는 것의 중요성에 대해 논의했습니다.