How to build an hierarchy tree of categories in java using enums or any other way?

前端 未结 3 1928
借酒劲吻你
借酒劲吻你 2021-01-03 10:35

Assuming that we have a set of categories: categories={A,B}. Let\'s assume more that A consists of subcategories: {A1,A2,A3} and B consists of subcategories: {B1,B2}.In addi

3条回答
  •  一个人的身影
    2021-01-03 10:44

    java.util.Map objects with java.util.Collection value types can represent arbitrary tree structures:

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

    Or you could try something like javax.swing.tree.DefaultTreeModel.

提交回复
热议问题