java - 使用四个层次结构存储字符串值

标签 java jsp servlets data-structures

下图显示了我的数据需要如何存储和相互链接:

值 v1、v2 等都是唯一的。对于不同的 v1...n,Av1...n 和 n1...n 对应该相同。存储后,我需要以以下格式检索它:

V1,Av1,n1
V1,Av1.n2
.
.
.
.
v4,Av1,n1

您建议我如何执行此操作?

最佳答案

使用树类来存储树及其子树的名称。然后迭代递归逻辑并打印它。

import java.util.ArrayList;
import java.util.List;

class Tree{
    private List<Tree> childTree;
    private String name;

    public Tree(String name) {
        this.name = name;
    }

    public List<Tree> getChildTree() {
        return childTree;
    }

    public void setChildTree(List<Tree> childTree) {
        this.childTree = childTree;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class TestDrive {

    public static void main(String arr[]){

        //Storing the values
        Tree a1 = new Tree("A1");

        Tree v1 = new Tree("v1");
        Tree v2 = new Tree("v2");

        List<Tree> a1Child = new  ArrayList<Tree>();
        a1Child.add(v1);
        a1Child.add(v2);

        a1.setChildTree(a1Child);

        Tree av1 = new Tree("av1");
        Tree av2 = new Tree("av2");

        List<Tree> v1Child = new  ArrayList<Tree>();
        v1Child.add(av1);
        v1Child.add(av2);

        v1.setChildTree(v1Child);

        Tree n1 = new Tree("n1");
        Tree n2 = new Tree("n2");

        List<Tree> av1Child = new  ArrayList<Tree>();
        av1Child.add(n1);
        av1Child.add(n2);

        av1.setChildTree(av1Child);

        Tree n11 = new Tree("n1");
        Tree n22 = new Tree("n2");
        List<Tree> av2Child = new  ArrayList<Tree>();
        av2Child.add(n11);
        av2Child.add(n22);

        av2.setChildTree(av2Child);

        //Retrieving the values

        printValue(a1,"");

    }

    private static void printValue(Tree tree,String treeName) {
        treeName = treeName+" : "+tree.getName();

        if(tree.getChildTree()!=null){
            List<Tree> childTreeList = tree.getChildTree();
            for (Tree childTree : childTreeList) {
                printValue(childTree,treeName);
            }
        }else{
            System.out.println(treeName);
        }
    }

}

关于java - 使用四个层次结构存储字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25786475/

相关文章:

java - 将 URL 中的特定 java 类作为 JSP 或独立类运行

jsp - 为什么将 JSP 转换为 Servlet?

java - 在 WEB-INF java 中显示文件路径是否存在安全风险

java - 是否可以将 Android 包导入普通的 Java 代码

java - 有没有类似appfuse的java web应用模板?

javascript - get如何获取动态生成的值

javascript - 使用javascript从数据库中检索多行并显示在html表格中

java - 自动检查equals、hashCode和compareTo一致性的技术?

java - 将参数从 Controller 传递到 Action

java - 用于过滤/排序大量数据的插件或模块?