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 ์ฒดํฌ๋ฅผ ํด์ผํ๊ณ , ์ด๋ ์ฝ๋ ๊ฐ๋ ์ฑ์ ๋จ์ด๋จ๋ฆฌ๊ณ ์ค๋ฅ๋ฅผ ์ ๋ฐํ ์ ์๋ค. ํด๊ฒฐ์ฑ ์ ์์ฃผ ๊ฐ๋จํ๊ฒ ๋น ์ปฌ๋ ์ ์ ๋ฐํํ๋ฉด ๋๋ค.
class Example {
private final List<String> list = new ArrayList<>();
public List<String> getList() {
return list.isEmpty()
? Collections.emptyList()
: new ArrayList<>(list);
}
private static final String[] EMPTY_ARRAY = new String[0]; // ๊ธธ์ด๊ฐ 0์ธ ๋ฐฐ์ด์ ๋ชจ๋ ๋ถ๋ณ์ด๊ธฐ ๋๋ฌธ์ ์ฌ์ฌ์ฉ ๊ฐ๋ฅ
// ๋ฐฐ์ด์ ๋ฐํํด์ผ ํ๋ ๊ฒฝ์ฐ
public String[] getArray() {
return list.toArray(EMPTY_ARRAY);
}
}
๋น ๋ฐฐ์ด์ ๋ฐํํด์ผํ๋ ๊ฒฝ์ฐ์๋ null์ ๋ฐํํ์ง ๋ง๊ณ toArray
๋ฉ์๋์ ๋น ๋ฐฐ์ด์ ์ธ์๋ก ์ ๋ฌํ๋ฉด ๋๋ค.
(์์ ์ฝ๋์์๋ EMPTY_ARRAY
๋ฅผ ๋ฏธ๋ฆฌ ์ ์ธํ์ฌ ์ฌ์ฉํด ์ฑ๋ฅ ์ ํ๋ฅผ ๋ฐฉ์งํ๋ค.)
Last updated
Was this helpful?