-
Java - List의 Null 체크하는 방법 (CollectionUtils)Java 2022. 7. 27. 19:30반응형
TL;DR
CollectionsUtils.isEmpty() 를 사용해서 List의 Null 체크하자.
List Null 체크하는 방법
1. List.isEmpty()
import java.util.Arrays; import java.util.List; class Example { public static void main(String[] args) { List<String> list = Arrays.asList(); System.out.println(list.isEmpty()); } }
list 객체에 isEmpty()를 호출해서 empty인지 체크할 수 있다.
그러나 list가 null일 경우 NullPointerException이 발생한다.
import java.util.Arrays; import java.util.List; class Example { public static void main(String[] args) { List<String> list = null; System.out.println(list.isEmpty()); } }
결과
Exception in thread "main" java.lang.NullPointerException at Example.main(Example.java:9)
2. CollectionUtils.isEmpty()
NullPointerException을 방지하려면 CollectionUtils.isEmpty() 를 사용하면 된다.
org.springframework.util의 CollectionUtils, org.apache.commons.collections4의 CollectionUtils가 있다.
여러가지 CollectionUtils 중에 좋은 것을 사용하면 된다.
CollectionUtils.isEmpty()를 사용했을 때 장점은 NullPointerException을 방지할 수 있다는 점이다.
public static void main(String[] args) { List<String> list = null; System.out.println(CollectionUtils.isEmpty(list)); }
이렇게 코드를 작성하면 결과가 true로 정상적으로 나온다.
참고
CollectionUtils (Apache Commons Collections 4.4 API)
Returns a Collection containing the exclusive disjunction (symmetric difference) of the given Iterables. The cardinality of each element e in the returned Collection will be equal to max(cardinality(e,a),cardinality(e,b)) - min(cardinality(e,a), cardinalit
commons.apache.org
CollectionUtils (Spring Framework 5.3.22 API)
Check whether the given Collection contains the given element instance. Enforces the given instance to be present, rather than returning true for an equal element as well.
docs.spring.io
반응형'Java' 카테고리의 다른 글
Java - generic 이해하기 (0) 2022.08.12 Java - List 중복 제거 (0) 2022.08.01 Java - String을 Long으로 변환하기 (0) 2022.07.25 Java - Int를 Long으로 변환, Long을 Int로 변환 (0) 2022.07.18 Java - Map getOrDefault 사용 방법, 예제 (0) 2022.07.18