본문 바로가기
IT 개발/개념정리

[JAVA] 배열 NULL 체크 방법

by Dev.Jeon 2023. 2. 22.
반응형
List.isEmpty()

isEmpty() 함수의 리턴 값은 true, false입니다.

*주의*

isEmpty() 한수 사용 시 list 객체가 null인 경우 NullPointException이 발생합니다.

그러므로 조건에 null 체크도 같이 해주어야 합니다.

List<String> list = Arrays.asList("A","B","C");
List<String> list2 = new ArrayList<>();

if(list == null || list.isEmpty()){
	System.out.println("list is empty");
}

if(list2 == null || list2.isEmpty()){
	System.out.println("list is empty");
}

 

 

List.size()

size() 함수는 요수 개수를 리턴합니다.

null인 경우 0이 리턴됩니다.

역시 null 체크도 먼저 선행 후 비교해 줍니다.

List<String> list = Arrays.asList("A","B","C");
List<String> list2 = new ArrayList<>();

if(list == null || list.size() == 0 ){
	System.out.println("list is empty");
}

if(list2 == null || list2.size() == 0){
	System.out.println("list is empty");
}

 

 

length()

length() 함수 역시 요소 개수를 리턴하고 null인 경우 0을 리턴합니다.

String[] arr = new String[5];

if(arr.length == 0) {
    System.out.println("The arr is Empty");
}
반응형

댓글