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>
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]);
}
}
}
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);
}
}