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?