Java算法转到包含列表列表

时间:2016-05-09 16:47:14

标签: java algorithm list

我想从列表中获取所有元素,但此元素也有列表,直到列表为空(node.getChildNotes() == null)

我尝试了以下方法,但它不是一种无穷无尽的算法。

private List<Layout> createChildList(Node node) {
        List<Layout> layouts = new ArrayList<>();
        int count = 0;
        while (true) {
            Node child = node.getChildNodes().item(count);
            if(child == null){
                break;
            }
            NodeList children = child.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                child = children.item(i);
                Layout layout = new Layout();
                layout.setName(child.getNodeName());
                layouts.add(layout);
            }
        count++
        }
        return layouts;
    }

private List<LayoutEntity> createChildList(Node node) {
        List<LayoutEntity> layouts = new ArrayList<>();
        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);
            LayoutEntity layout = new LayoutEntity();
            layout.setId(getIdByNode(childNode));
            layout.setName(childNode.getNodeName());
            layouts.add(layout);
            if (childNode.hasChildNodes()) {
                createChildList(childNode);
            }
        }
        return layouts;
    }

2 个答案:

答案 0 :(得分:1)

我认为使用深度递归函数,您可以首先获取父节点的所有子节点,然后只需为每个节点创建new Layout

private List<Node> createChildList(Node parent) {
        List<Node> result = new ArrayList<Node>();
        NodeList children = parent.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            result.addAll(createChildList(children.item(i)));
        }
        return result;
    }

答案 1 :(得分:0)

在if条件之后,您将获得子节点并且有一个for循环,您可以在其中检查所有这些子节点。我不知道为什么你需要while(true)循环。就像这样离开它。而且,count变量是没用的。

private List<Layout> createChildList(Node node) {
        List<Layout> layouts = new ArrayList<>();
        //int count = 0; WHY TO USE THIS USE THIS?
        Node child = node.getChildNodes().item(0);
        if(child == null){
            break;
        } else{
            NodeList children = child.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                child = children.item(i);
                Layout layout = new Layout();
                layout.setName(child.getNodeName());
                layouts.add(layout);
        }

        return layouts;
    }