Java 에서 배열이 비어 있는지 확인하는 방법

JavaBeginner
지금 연습하기

소개

이 랩에서는 Java 에서 배열이 비어 있는지 확인하는 방법을 배우게 됩니다. 배열의 길이를 확인하는 기본적인 기술을 다루고, 배열 자체가 null 인 경우를 처리하는 방법도 다룰 것입니다. 다양한 배열 유형으로 이러한 개념을 연습하여 이해도를 높일 것입니다.

배열 길이가 0 인지 확인

이 단계에서는 Java 에서 배열의 길이를 확인하여 배열이 비어 있는지 확인하는 방법을 배우겠습니다. 이는 배열 작업 시 오류를 방지하기 위한 기본적인 연산입니다.

먼저, ~/project 디렉토리에 ArrayLengthCheck.java라는 새 Java 파일을 생성해 보겠습니다. 왼쪽의 WebIDE 파일 탐색기를 사용하여 이 작업을 수행할 수 있습니다. ~/project 영역을 마우스 오른쪽 버튼으로 클릭하고 "New File"을 선택한 다음 ArrayLengthCheck.java를 입력합니다.

이제 편집기에서 ArrayLengthCheck.java 파일을 열고 다음 코드를 추가합니다.

public class ArrayLengthCheck {

    public static void main(String[] args) {
        // Declare and initialize an empty integer array
        int[] emptyArray = {};

        // Declare and initialize an integer array with elements
        int[] populatedArray = {1, 2, 3, 4, 5};

        // Check the length of the empty array
        if (emptyArray.length == 0) {
            System.out.println("emptyArray is empty.");
        } else {
            System.out.println("emptyArray is not empty. Length: " + emptyArray.length);
        }

        // Check the length of the populated array
        if (populatedArray.length == 0) {
            System.out.println("populatedArray is empty.");
        } else {
            System.out.println("populatedArray is not empty. Length: " + populatedArray.length);
        }
    }
}

여기서 새로운 개념을 이해해 봅시다.

  • int[] emptyArray = {};: emptyArray라는 정수 배열을 선언하고 빈 배열로 초기화합니다.
  • int[] populatedArray = {1, 2, 3, 4, 5};: populatedArray라는 정수 배열을 선언하고 다섯 개의 정수 요소로 초기화합니다.
  • array.length: Java 에서 배열의 요소 수를 알려주는 배열의 속성입니다.
  • if (condition) { ... } else { ... }: 이는 프로그래밍의 기본적인 제어 흐름 구조인 if-else 문입니다. 이를 통해 프로그램이 결정을 내릴 수 있습니다. 괄호 안의 condition이 true 이면 if 블록 내부의 코드가 실행됩니다. 그렇지 않으면 else 블록 내부의 코드가 실행됩니다.

이 코드에서는 .length 속성을 사용하여 각 배열의 길이가 0과 같은지 확인합니다. 그렇다면 배열이 비어 있음을 나타내는 메시지를 출력합니다. 그렇지 않으면 비어 있지 않음을 나타내는 메시지를 출력하고 길이를 출력합니다.

파일을 저장합니다 (Ctrl+S 또는 Cmd+S).

이제 WebIDE 하단의 터미널을 엽니다. ~/project 디렉토리에 있는지 확인합니다. 그렇지 않은 경우 cd ~/project 명령을 사용합니다.

javac 명령을 사용하여 Java 프로그램을 컴파일합니다.

javac ArrayLengthCheck.java

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

이제 java 명령을 사용하여 컴파일된 프로그램을 실행합니다.

java ArrayLengthCheck

다음 출력이 표시되어야 합니다.

emptyArray is empty.
populatedArray is not empty. Length: 5

이 출력은 프로그램이 길이를 기반으로 빈 배열과 채워진 배열을 올바르게 식별했음을 확인합니다. 배열의 요소에 접근하기 전에 배열의 길이를 확인하는 것은 배열에 존재하지 않는 인덱스에서 요소에 접근하려고 할 때 발생하는 ArrayIndexOutOfBoundsException과 같은 오류를 방지하는 중요한 단계입니다.

Null 배열 처리

이전 단계에서는 배열의 길이를 확인하여 배열이 비어 있는지 확인하는 방법을 배웠습니다. 그러나 고려해야 할 또 다른 중요한 시나리오가 있습니다. 배열 자체가 null인 경우는 어떻게 해야 할까요?

Java 에서 변수는 객체에 대한 참조를 가질 수 있거나, 어떤 객체도 참조하지 않음을 의미하는 특수한 값인 null을 가질 수 있습니다. null인 배열 변수의 .length 속성에 접근하려고 하면 프로그램이 NullPointerException으로 충돌합니다. 이는 Java 에서 매우 흔한 오류이므로 이를 처리하는 방법을 아는 것이 중요합니다.

null 배열을 시연하고 처리하기 위해 이전 프로그램을 수정해 보겠습니다.

WebIDE 편집기에서 ArrayLengthCheck.java 파일을 엽니다.

기존 코드를 다음으로 바꿉니다.

public class ArrayLengthCheck {

    public static void main(String[] args) {
        // Declare an integer array but do not initialize it (it will be null)
        int[] nullArray = null;

        // Declare and initialize an empty integer array
        int[] emptyArray = {};

        // Declare and initialize an integer array with elements
        int[] populatedArray = {1, 2, 3, 4, 5};

        // Function to check if an array is null or empty
        checkArrayStatus(nullArray, "nullArray");
        checkArrayStatus(emptyArray, "emptyArray");
        checkArrayStatus(populatedArray, "populatedArray");
    }

    // A helper method to check and print the status of an array
    public static void checkArrayStatus(int[] arr, String arrayName) {
        System.out.println("Checking " + arrayName + "...");
        if (arr == null) {
            System.out.println(arrayName + " is null.");
        } else if (arr.length == 0) {
            System.out.println(arrayName + " is empty.");
        } else {
            System.out.println(arrayName + " is not empty. Length: " + arr.length);
        }
        System.out.println(); // Print a blank line for better readability
    }
}

변경 사항을 살펴보겠습니다.

  • int[] nullArray = null;: 정수 배열 변수 nullArray를 선언하고 해당 값을 명시적으로 null로 설정합니다.
  • public static void checkArrayStatus(int[] arr, String arrayName): checkArrayStatus라는 새 메서드를 만들었습니다. 이 메서드는 정수 배열 (arr) 과 문자열 (arrayName) 을 입력으로 받습니다. 이는 배열 상태를 확인하기 위한 로직을 재사용하는 데 도움이 됩니다.
  • if (arr == null): 이는 null 배열을 처리하는 데 중요한 부분입니다. 먼저, 등가 연산자 ==를 사용하여 배열 변수 arrnull인지 확인합니다. null인 경우 메시지를 출력하고 이 배열에 대한 추가 조건을 확인하는 것을 중지합니다.
  • else if (arr.length == 0): 이 확인은 배열이 null아닌 경우에만 수행됩니다. 배열이 null이 아니면 길이가 0인지 확인하여 비어 있는지 확인합니다.
  • 이제 main 메서드는 각 배열 (nullArray, emptyArray, populatedArray) 에 대해 checkArrayStatus를 호출합니다.

파일을 저장합니다 (Ctrl+S 또는 Cmd+S).

~/project 디렉토리에서 터미널을 엽니다.

수정된 Java 프로그램을 컴파일합니다.

javac ArrayLengthCheck.java

컴파일이 성공하면 프로그램을 실행합니다.

java ArrayLengthCheck

다음 출력이 표시되어야 합니다.

Checking nullArray...
nullArray is null.

Checking emptyArray...
emptyArray is empty.

Checking populatedArray...
populatedArray is not empty. Length: 5

이 출력은 프로그램이 null 배열, 빈 배열 및 채워진 배열을 올바르게 식별했음을 보여줍니다. 길이를 확인하기 전에 null을 확인하여 null 배열에서 .length에 접근하려고 할 때 발생하는 NullPointerException을 방지합니다. 이는 Java 프로그래밍의 기본적인 모범 사례입니다.

다양한 배열 타입으로 테스트

이전 단계에서는 정수 배열 (int[]) 로 작업했습니다. null을 확인하고 .length 속성을 확인하는 개념이 int, double, boolean과 같은 기본 유형이든 String 또는 사용자 정의 클래스와 같은 객체 유형이든 Java 의 모든 데이터 유형의 배열에 적용된다는 것을 이해하는 것이 중요합니다.

다양한 유형의 배열 상태를 확인하는 것을 시연하기 위해 프로그램을 한 번 더 수정해 보겠습니다.

WebIDE 편집기에서 ArrayLengthCheck.java 파일을 엽니다.

기존 코드를 다음으로 바꿉니다.

public class ArrayLengthCheck {

    public static void main(String[] args) {
        // Declare a null String array
        String[] nullStringArray = null;

        // Declare an empty double array
        double[] emptyDoubleArray = {};

        // Declare a boolean array with elements
        boolean[] populatedBooleanArray = {true, false, true};

        // Declare a String array with elements
        String[] populatedStringArray = {"apple", "banana", "cherry"};

        // Use the helper method to check different array types
        checkArrayStatus(nullStringArray, "nullStringArray");
        checkArrayStatus(emptyDoubleArray, "emptyDoubleArray");
        checkArrayStatus(populatedBooleanArray, "populatedBooleanArray");
        checkArrayStatus(populatedStringArray, "populatedStringArray");
    }

    // A generic helper method to check and print the status of an array
    // We use Object[] because it can represent an array of any object type
    // For primitive types, the check still works on the array reference itself
    public static void checkArrayStatus(Object arr, String arrayName) {
        System.out.println("Checking " + arrayName + "...");
        if (arr == null) {
            System.out.println(arrayName + " is null.");
        } else if (arr instanceof Object[]) {
            // For object arrays, we can cast and check length
            Object[] objectArray = (Object[]) arr;
            if (objectArray.length == 0) {
                 System.out.println(arrayName + " is empty.");
            } else {
                 System.out.println(arrayName + " is not empty. Length: " + objectArray.length);
            }
        } else if (arr.getClass().isArray()) {
             // For primitive arrays, we can't cast to Object[], but can still check length
             // using reflection or simply rely on the null check and the fact that
             // primitive arrays also have a .length property accessible directly
             // (though accessing it here would require more complex reflection)
             // For simplicity in this example, we'll just indicate it's a non-null, non-empty primitive array
             // A more robust check would involve reflection or overloaded methods for each primitive type
             try {
                 int length = java.lang.reflect.Array.getLength(arr);
                 if (length == 0) {
                     System.out.println(arrayName + " is empty.");
                 } else {
                     System.out.println(arrayName + " is not empty. Length: " + length);
                 }
             } catch (IllegalArgumentException e) {
                  System.out.println("Could not determine length for " + arrayName);
             }

        } else {
             System.out.println(arrayName + " is not an array.");
        }
        System.out.println(); // Print a blank line for better readability
    }
}

변경 사항을 살펴보겠습니다.

  • String[], double[], boolean[]과 같은 다양한 유형의 배열을 만들었습니다.
  • checkArrayStatus 메서드는 이제 Object arr을 매개변수로 받습니다. 이를 통해 Java 의 모든 배열이 객체이므로 모든 유형의 배열을 허용할 수 있습니다.
  • checkArrayStatus 내부에서 먼저 arrnull인지 확인합니다.
  • null이 아닌 경우 instanceof Object[]를 사용하여 객체 배열인지 확인합니다. 그렇다면 Object[]로 캐스팅하고 .length를 확인합니다.
  • 또한 arr.getClass().isArray()를 추가하여 객체가 배열인지 확인합니다 (이는 객체 배열과 기본 배열 모두에 해당).
  • 기본 배열의 경우, 이 일반 메서드 내에서 .length에 직접 접근하는 것은 리플렉션 없이는 까다롭습니다. 제공된 코드는 java.lang.reflect.Array.getLength(arr)을 사용하여 모든 배열 유형의 길이를 얻는 보다 일반적인 방법을 사용합니다.

파일을 저장합니다 (Ctrl+S 또는 Cmd+S).

~/project 디렉토리에서 터미널을 엽니다.

수정된 Java 프로그램을 컴파일합니다.

javac ArrayLengthCheck.java

컴파일이 성공하면 프로그램을 실행합니다.

java ArrayLengthCheck

다음과 유사한 출력이 표시되어야 합니다.

Checking nullStringArray...
nullStringArray is null.

Checking emptyDoubleArray...
emptyDoubleArray is empty.

Checking populatedBooleanArray...
populatedBooleanArray is not empty. Length: 3

Checking populatedStringArray...
populatedStringArray is not empty. Length: 4

이는 null을 확인하고 길이를 확인하는 원칙이 Java 의 다양한 배열 유형에 걸쳐 일관되게 적용됨을 보여줍니다. Object와 리플렉션을 사용하는 일반적인 checkArrayStatus 메서드는 더 복잡하지만, null을 먼저 확인한 다음 .length를 확인하는 핵심 아이디어는 특정 배열 유형 (예: int[], String[] 등) 에 대해 동일하게 유지됩니다.

요약

이 랩에서는 Java 에서 배열의 length 속성을 검사하여 배열이 비어 있는지 확인하는 방법을 배웠습니다. ArrayLengthCheck.java라는 Java 파일을 생성하고 비어 있거나 채워진 정수 배열을 선언하는 코드를 작성했습니다. if-else 문을 사용하고 배열의 길이를 0 과 비교하여 각 배열이 비어 있는지 여부를 성공적으로 결정하고 결과를 콘솔에 출력했습니다. 이 기본적인 기술은 배열로 작업할 때 오류를 방지하는 데 매우 중요합니다.