Reputation: 11
I have a list of categories and some of them have subcategories. I need to implement this hierarchy using enumeration. I did this:
public enum Type {
Category1(1, new LinkedHashMap<Integer, String>()),
Category2(2, getSubcategory2()),
Category3(3, getSubcategory3());
private final int id;
private final Map<Integer, String> subcategories;
Type(int id, Map<Integer, String subcategories) {
this.id = id;
this.subcategories = subcategories;
}
public int getId() {
return id;
}
public Map<Integer, String> getSubcategories() {
return subcategories;
}
}
I want a more elegant solution because in this moment if I want to see if a category have subcategories I have to verify every time if subcategories.size() > 0.
Upvotes: 1
Views: 954
Reputation: 141
public enum Category {
CATEGORY_1(null),
CATEGORY_1_1(CATEGORY_1),
CATEGORY_1_2(CATEGORY_1),
CATEGORY_2(null),
CATEGORY_2_1(CATEGORY_2),
CATEGORY_2_1_1(CATEGORY_2_1),
CATEGORY_2_1_2(CATEGORY_2_1);
private final Category parent;
private final List<Category> children = new ArrayList<>();
private final List<Category> roChildren = Collections.unmodifiableList(children);
private Category(Category parent) {
this.parent = parent;
if (parent != null) {
parent.children.add(this);
}
}
public Category getParent() {
return parent;
}
public List<Category> getChildren() {
return roChildren;
}
}
Upvotes: 4