Add ArrayList to another ArrayList in java

后端 未结 6 1214
北荒
北荒 2020-12-03 13:16

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

 ArrayList nodes = new ArrayList

        
6条回答
  •  死守一世寂寞
    2020-12-03 14:12

    The problem you have is caused that you use the same ArrayList NodeList over all iterations in main for loop. Each iterations NodeList is enlarged by new elements.

    1. After first loop, NodeList has 5 elements (PropertyStart,a,b,c,PropertyEnd) and list has 1 element (NodeList: (PropertyStart,a,b,c,PropertyEnd))

    2. After second loop NodeList has 10 elements (PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd) and list has 2 elements (NodeList (with 10 elements), NodeList (with 10 elements))

    To get you expectations you must replace

    NodeList.addAll(nodes);
    list.add(NodeList)
    

    by

    List childrenList = new ArrayList(nodes);
    list.add(childrenList);
    

    PS. Your code is not readable, keep Java code conventions to have readble code. For example is hard to recognize if NodeList is a class or object

提交回复
热议问题