[JAVA] List의 null 체크 (with isEmpty())

    [JAVA] List의 null 체크 (with isEmpty())

     

    아래와 같은 List가 있다고 가정할때

    List<String> stringList = new ArrayList<>();

     

    stringList.get(0);

    List에 아무런 값이 없을 경우에 위와 같이 get을 사용하여 값을 가져오고자 하면 Nullpointerexception이 발생하게 된다.

     

    if (stringList != null && !stringList.isEmpty()) {
        TestDto testDto = stringList.get(0);
    }

    이경우 null과 "" 빈값을 체크해주면 된다.

     

    또는 ObjectUtils.isEmpty();를 사용해주면 되는데

    ObjectUtils.isEmpty() 란?

    null과 .isEmpty()를 동시에 체크하고 있어 둘중 선택하여 사용하면 될 것 같다.

    댓글

    Designed by JB FACTORY