Item 37. EnumMap
ordinal
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;
}
}
class Main {
public static void main(String[] args) {
Set<Plant>[] plantsByLifeCycle = (Set<Plant>[]) new Set[Plant.LifeCycle.values().length]; // ๋น๊ฒ์ฌ ํ๋ณํ ๊ฒฝ๊ณ
List<Plant> garden = List.of(
new Plant("๋ฐ์ง", Plant.LifeCycle.ANNUAL),
new Plant("์บ๋ฌ์จ์ด", Plant.LifeCycle.BIENNIAL),
new Plant("๋", Plant.LifeCycle.ANNUAL),
new Plant("๋ผ๋ฒค๋", Plant.LifeCycle.PERENNIAL),
new Plant("ํ์ฌ๋ฆฌ", Plant.LifeCycle.BIENNIAL),
new Plant("๋ก์ฆ๋ง๋ฆฌ", Plant.LifeCycle.PERENNIAL)
);
for (int i = 0; i < plantsByLifeCycle.length; i++) {
plantsByLifeCycle[i] = new HashSet<>();
}
for (Plant p : garden) {
plantsByLifeCycle[p.lifeCycle.ordinal()].add(p);
}
for (int i = 0; i < plantsByLifeCycle.length; i++) {
// ๋ฐฐ์ด์ ์ธ๋ฑ์ค์ ์๋ฏธ๋ฅผ ๋ชจ๋ฅด๊ธฐ ๋๋ฌธ์ ์ถ๋ ฅํ ๋ ๋ง๋ค LifeCycle.values()๋ฅผ ํธ์ถํด์ผ ํ๋ค.
System.out.printf("%s: %s%n", Plant.LifeCycle.values()[i], plantsByLifeCycle[i]); // ArrayIndexOutOfBoundsException ๋ฐ์ ๊ฐ๋ฅ
}
}
}EnumMap
์ด๊ฑฐ ํ์
๊ฐ๋ค ๋งคํ ์์
Last updated