Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

Add ArrayList to another ArrayList in java

I am having the following java code, in which I am trying to copy the ArrayList to another ArrayList.

ArrayList<String> nodes = new ArrayList<String>();
ArrayList NodeList = new ArrayList();
ArrayList list = new ArrayList();

for (int i = 0; i < PropertyNode.getLength() - 1; i++) {
    Node childNode = PropertyNode.item(i);
    NodeList Children = childNode.getChildNodes();

    if (Children != null) {
        nodes.clear();
        nodes.add("PropertyStart");
        nodes.add(Children.item(3).getTextContent());
        nodes.add(Children.item(7).getTextContent());
        nodes.add(Children.item(9).getTextContent());
        nodes.add(Children.item(11).getTextContent());
        nodes.add(Children.item(13).getTextContent());
        nodes.add("PropertyEnd");
    }
    NodeList.addAll(nodes);
    list.add(NodeList);
}

I want the "list" array to be in this format:

[[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,d,e,f,PropertyEnd],[PropertyStart,......]]

But from the above code, the "list" array output is seen like this:

[PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,....PropertyEnd]

I think you might have noticed the difference. I am not able to achieve the result in expected format.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Then you need a ArrayList of ArrayLists:

ArrayList<ArrayList<String>> nodes = new ArrayList<ArrayList<String>>();
ArrayList<String> nodeList = new ArrayList<String>();
nodes.add(nodeList);

Note that NodeList has been changed to nodeList. In Java Naming Conventions variables start with a lower case. Classes start with an upper case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...