如何使用枚举或任何其他方式在java中构建类别的层次结构树?

假设我们有一组类别:categories = {A,B}。 让我们更多地假设A由子类别组成:{A1,A2,A3}和B由子类别组成:{B1,B2}。此外,还有更多子类别如下:对于A1:{A1a,A1b},对于A2 :{A2a,A2b},A3:{A3a,A3b,A3c},B1:{B1a,B1b,B1c},B2:{B2a,B2b}。 如何在java中构建层次结构?

由于每个集合的基数是固定的并且事先已知,我最初的方法是使用枚举类型而不是使用inheritance构建类,但我对任何建议持开放态度。 我不知道如何处理这个问题。

提前致谢。

可能是这个的实现:

public interface Category { String getName(); Category getParent(); List getSiblings(); List getChildren(); List getDescendants(); void addChild(Category category); void addChildren(List categories); } 

除了上面的答案,我想分享一些我在互联网上找到的东西。 我还没有测试过,但它似乎提供了另一种选择:

http://alexradzin.blogspot.hk/2010/10/hierarchical-structures-with-java-enums_05.html

 public enum OsType { OS(null), Windows(OS), WindowsNT(Windows), WindowsNTWorkstation(WindowsNT), WindowsNTServer(WindowsNT), Windows2000(Windows), Windows2000Server(Windows2000), Windows2000Workstation(Windows2000), WindowsXp(Windows), WindowsVista(Windows), Windows7(Windows), Windows95(Windows), Windows98(Windows), Unix(OS) { @Override public boolean supportsXWindows() { return true; } }, Linux(Unix), AIX(Unix), HpUx(Unix), SunOs(Unix), ; private OsType parent = null; private OsType(OsType parent) { this.parent = parent; } 

java.util.Map值类型的java.util.Map对象可以表示任意树结构:

  final Map> map = Collections.unmodifiableMap( new HashMap>() { { put( "A", Collections.unmodifiableSet( new HashSet<>(Arrays.asList("A1", "A2", "A3")) ) ); put( "A1", Collections.unmodifiableSet( new HashSet<>(Arrays.asList("A1a", "A1b")) ) ); put( "A2", Collections.unmodifiableSet( new HashSet<>(Arrays.asList("A2a", "A2b")) ) ); put( "A3", Collections.unmodifiableSet( new HashSet<>(Arrays.asList("A3a", "A3b", "A3c")) ) ); put( "B", Collections.unmodifiableSet( new HashSet<>(Arrays.asList("B1", "B2")) ) ); put( "B1", Collections.unmodifiableSet( new HashSet<>(Arrays.asList("B1a", "B1b", "B1c")) ) ); put( "B2", Collections.unmodifiableSet( new HashSet<>(Arrays.asList("B2a", "B2b")) ) ); } } ); 

或者你可以尝试像javax.swing.tree.DefaultTreeModel这样的东西。