Item 54. Empty Collection
null์ด ์๋, ๋น ์ปฌ๋ ์ ์ด๋ ๋ฐฐ์ด์ ๋ฐํํ๋ผ
์ฝ๋๋ฅผ ์์ฑํ๋ค๋ณด๋ฉด ์ปฌ๋ ์ ์ด ๋น ๊ฒฝ์ฐ null์ ๋ฐํํ๋ ๊ฒฝ์ฐ๋ฅผ ์ข ์ข ๋ณผ ์ ์๋ค.
class Example {
private final List<String> list = new ArrayList<>();
public List<String> getList() {
return list.isEmpty()
? null
: new ArrayList<>(list);
}
public static void main(String[] args) {
Example example = new Example();
List<String> list = example.getList();
if (list != null) {
System.out.println(list.size());
}
}
}๋น ๊ฒฝ์ฐ์ null์ ๋ฐํํ๊ฒ ๋๋ฉด ํด๋ผ์ด์ธํธ ์ฝ๋์์๋ ๋ถํ์ํ๊ฒ null ์ฒดํฌ๋ฅผ ํด์ผํ๊ณ , ์ด๋ ์ฝ๋ ๊ฐ๋ ์ฑ์ ๋จ์ด๋จ๋ฆฌ๊ณ ์ค๋ฅ๋ฅผ ์ ๋ฐํ ์ ์๋ค. ํด๊ฒฐ์ฑ ์ ์์ฃผ ๊ฐ๋จํ๊ฒ ๋น ์ปฌ๋ ์ ์ ๋ฐํํ๋ฉด ๋๋ค.
๋น ๋ฐฐ์ด์ ๋ฐํํด์ผํ๋ ๊ฒฝ์ฐ์๋ null์ ๋ฐํํ์ง ๋ง๊ณ toArray ๋ฉ์๋์ ๋น ๋ฐฐ์ด์ ์ธ์๋ก ์ ๋ฌํ๋ฉด ๋๋ค.
(์์ ์ฝ๋์์๋ EMPTY_ARRAY๋ฅผ ๋ฏธ๋ฆฌ ์ ์ธํ์ฌ ์ฌ์ฉํด ์ฑ๋ฅ ์ ํ๋ฅผ ๋ฐฉ์งํ๋ค.)
Last updated
Was this helpful?