SeouliteLab

[Java/자바] List가 비어있는지(null 체크)하는 다양한 방법 본문

프로그래밍

[Java/자바] List가 비어있는지(null 체크)하는 다양한 방법

Seoulite Lab 2024. 3. 8. 09:34

Java에서는 List가 비어있는지(null 체크)하는 다양한 방법이 있습니다. 이번 글에서는 List가 비어있는지 확인하는 3가지 방법을 살펴보겠습니다. 각 방법은 코드 예제와 함께 자세히 설명하겠습니다.

1. isEmpty() 메서드 사용하기

List의 isEmpty() 메서드는 해당 List가 비어있는지 확인하는 가장 간단한 방법입니다. isEmpty() 메서드는 List가 비어있으면 true를 반환하고, 비어있지 않으면 false를 반환합니다.

import java.util.ArrayList;
import java.util.List;

public class ListCheckExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        // List가 비어있는지 확인
        if (list.isEmpty()) {
            System.out.println("List는 비어있습니다.");
        } else {
            System.out.println("List는 비어있지 않습니다.");
        }
    }
}

2. size() 메서드와 비교 연산자를 사용하기

List의 size() 메서드를 활용하여 List의 크기를 확인하고, 비교 연산자를 사용하여 크기가 0인지 확인할 수도 있습니다. 이 방법은 isEmpty() 메서드보다 더 직관적일 수 있습니다.

import java.util.ArrayList;
import java.util.List;

public class ListCheckExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        // List의 크기가 0인지 확인
        if (list.size() == 0) {
            System.out.println("List는 비어있습니다.");
        } else {
            System.out.println("List는 비어있지 않습니다.");
        }
    }
}

3. null 체크 후 size() 메서드 사용하기

List가 null인지 확인한 후, null이 아닌 경우 size() 메서드를 사용하여 List가 비어있는지 확인할 수도 있습니다. 이 방법은 List가 null일 때 발생할 수 있는 NullPointerException을 방지할 수 있습니다.

import java.util.List;

public class ListCheckExample {
    public static void main(String[] args) {
        List<String> list = null;

        // List가 null인지 확인 후 비어있는지 확인
        if (list == null || list.size() == 0) {
            System.out.println("List는 비어있습니다.");
        } else {
            System.out.println("List는 비어있지 않습니다.");
        }
    }
}