Spring
[Java] List ์ ํจ์ฑ ๊ฒ์ฌ
young-ji
2022. 12. 1. 20:11
๋ฆฌ๋ทฐ ๋ฐ์๋ค๐คฃ
https://jihyehwang09.github.io/2020/04/13/java-list-null-check/
List.size() == 0 ๋ณด๋ค๋ List.isEmpty()
ํผ๋๋ฐฑ ๋ฐ์ ๊ฒ๊ณผ ๊ฐ์ด isEmpty๊ฐ ๊ฐ๋ ์ฑ๋ฉด์ ์ง๊ด์ ์ด๋ค.
๋ฟ๋ง ์๋๋ผ, list์ ์ฌ์ด์ฆ๊ฐ 0์ด ์๋๊ฒฝ์ฐ size() ๋ฉ์๋๋ O(n)์ ์๊ฐ๋ณต์ก๋๋ฅผ ๊ฐ์ง๊ธฐ ๋๋ฌธ์ isEmpty() ๋ณด๋ค ๋น์ฉ์ด ๋ง์ด ๋ ๋ค. (isEmpty()๋ O(1)์ ์๊ฐ ๋ณต์ก๋)
List null ์ฒดํฌ
Java Spring ์ฌ์ฉ์์๋ ์ํ์น ๋ผ์ด๋ธ๋ฌ๋ฆฌ CollectionUtils.isEmpty()๋ฅผ ์ฌ์ฉํ์.
import org.springframework.util.CollectionUtils;
public class Main {
public static void main(String[] args) {
List<Email> emailList = new ArrayList<>();
System.out.println(CollectionUtils.isEmpty(emailList)); // true
}
}
Collection ํ๋ผ๋ฏธํฐ์ ๋ํ null ์ฒดํฌ๋ฅผ ํด์ฃผ๊ธฐ ๋๋ฌธ์ NPE์ ์ข ๋ ์์ ํ ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ํด์ค์์๋ค.
์๋ชป๋ ์ ๋ณด๊ฐ ์๋ค๋ฉด ๋๊ธ์ ํตํด ์๋ ค์ฃผ์ธ์. ๊ฐ์ฌํฉ๋๋ค.