Item37 - ordinal 인덱싱 대신 EnumMap을 사용하라

ordinal() 이란?

예시코드 - 식물을 간단히 난타낸 클래스

public class Plant {

    enum LifeCycle {
        ANNUAL, // 한해살이
        PERENNIAL, // 여러해살이
        BIENNIAL // 두해살이
    }

    final String name;
    final LifeCycle lifeCycle;

    Plant(String name, LifeCycle lifeCycle) {
        this.name = name;
        this.lifeCycle = lifeCycle;
    }

    @Override
    public String toString() {
        return name;
    }

}

상황

<aside> 💡 정원에 심은 식물들을 배열 하나로 관리하고, 이들의 생애주기(라이프사이클)별로 묶어보자.

</aside>

예시코드 1 - ordinal 사용

public class PlantManager {

    public static void main(String[] args) {
        Set<Plant>[] plantsByLifeCycle = 
											(Set<Plant>[]) new Set[Plant.LifeCycle.values().length];

        List<Plant> plants = Arrays.asList(
            new Plant("ANNUAL_TREE_1", LifeCycle.ANNUAL),
            new Plant("ANNUAL_TREE_2", LifeCycle.ANNUAL),
            new Plant("ANNUAL_TREE_3", LifeCycle.ANNUAL),
            new Plant("BIENNIAL_TREE_1", LifeCycle.BIENNIAL),
            new Plant("PERENNIAL_TREE_1", LifeCycle.PERENNIAL)
        );

        for (int i = 0; i < plantsByLifeCycle.length; i++) {
            plantsByLifeCycle[i] = new HashSet<>();
        }

        for (Plant p : plants) {
            plantsByLifeCycle[p.lifeCycle.ordinal()].add(p);
        }

        for (int i = 0; i < plantsByLifeCycle.length; i++) {
            System.out.printf("%s: %s%n", Plant.LifeCycle.values()[i], 
																													plantsByLifeCycle[i]);
        }

    }

}

Untitled

ordinal의 문제점?

예시코드 2 - EnumMap 사용

public class PlantManager {

    public static void main(String[] args) {
        Map<Plant.LifeCycle, Set<Plant>> plantsByLifeCycle = new EnumMap<>(Plant.LifeCycle.class);

        List<Plant> plants = Arrays.asList(
            new Plant("ANNUAL_TREE_1", LifeCycle.ANNUAL),
            new Plant("ANNUAL_TREE_2", LifeCycle.ANNUAL),
            new Plant("ANNUAL_TREE_3", LifeCycle.ANNUAL),
            new Plant("BIENNIAL_TREE_1", LifeCycle.BIENNIAL),
            new Plant("PERENNIAL_TREE_1", LifeCycle.PERENNIAL)
        );

        for (Plant.LifeCycle lifeCycle : LifeCycle.values()) {
            plantsByLifeCycle.put(lifeCycle, new HashSet<>());
        }

        for (Plant p : plants) {
            plantsByLifeCycle.get(p.lifeCycle).add(p);
        }

        System.out.println(plantsByLifeCycle);
    }

}