2014-01-08 69 views
1

我有一個類別列表,其中一些有子類別。我需要使用枚舉實現這個層次結構。 我這樣做:具有枚舉的Java層次結構

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

我希望有一個更優雅的解決方案,因爲在這一刻,如果我想看看是否有類小類我必須驗證每次如果subcategories.size()> 0

+1

更精美的解決方案到底是什麼?如果有幫助,你可以很容易地使用'hasSubcategories'方法返回'!subcategories.isEmpty()'。 –

+0

注意,不能使用基元作爲泛型,它們不會編譯。你應該使用'new LinkedHashMap ()'來代替。 –

+0

這個'enum'究竟使用了多少? – gregor

回答

4
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; 
    } 
} 
+0

考慮添加說明,OP代碼中的問題以及發生了什麼變化,以便其他人也可以獲得幫助。 – Panther