简体   繁体   English

在java中将ArrayList添加到另一个ArrayList

[英]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.我有以下 java 代码,其中我试图将 ArrayList 复制到另一个 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:但是从上面的代码来看,“list”数组的输出是这样的:

[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.我无法以预期的格式获得结果。

Then you need a ArrayList of ArrayLists :然后你需要一个ArrayListArrayLists

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 .请注意, NodeList已更改为nodeList In Java Naming Conventions variables start with a lower case.Java 命名约定中,变量以小写开头。 Classes start with an upper case.类以大写开头。

Your Problem你的问题

Mainly, you've got 2 major problems:主要是,你有两个主要问题:

You are using adding a List of String s.您正在使用添加String List You want a List containing List s of Strings .你想要一个List包含ListStrings

Note as well that when you invoke this:还要注意,当您调用它时:

NodeList.addAll(nodes);

... all you say is to add all elements of nodes (which is a list of Strings) to the (badly named) NodeList , which is using Objects and thus adds only the strings inside. ...您所说的只是将节点的所有元素(它是一个字符串列表)添加到(名称错误的) NodeList ,它使用对象,因此只添加内部的字符串。 Which leads me to the next point.这使我进入下一点。

You seem to be confused between your nodes and NodeList .您似乎对您的nodesNodeList感到困惑。 Your NodeList keeps growing over time, and that's what you add to your list.您的NodeList随着时间的推移不断增长,这就是您添加到列表中的内容。

So, even if doing things right, if we were to look at the end of each iteration at your nodes , nodeList and list , we'd see:因此,即使做对了,如果我们在您的nodesnodeListlist处查看每次迭代的结尾,我们会看到:

  • i = 0我 = 0

     nodes: [PropertyStart,a,b,c,PropertyEnd] nodeList: [PropertyStart,a,b,c,PropertyEnd] list: [[PropertyStart,a,b,c,PropertyEnd]]
  • i = 1我 = 1

     nodes: [PropertyStart,d,e,f,PropertyEnd] nodeList: [PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd] list: [[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd]]
  • i = 2我 = 2

     nodes: [PropertyStart,g,h,i,PropertyEnd] nodeList: [PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,g,h,i,PropertyEnd] list: [[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,g,h,i,PropertyEnd]]
  • and so on...等等...

Some Other Corrections其他一些更正

Follow the Java Naming Conventions遵循 Java 命名约定

Don't use variable names starting with uppercase letters.不要使用以大写字母开头的变量名。 So here, replace NodeList with nodeList ).所以在这里,用nodeList替换NodeList )。

Learn a Bit More About Types了解更多关于类型的信息

You say "I want the "list" array [...]".您说“我想要“列表”数组 [...]”。 This is confusing for whoever you will be communicating with: It's not an array.这会让您将与之通信的任何人感到困惑:它不是数组。 It's an implementation of List backed by an array.它是由数组支持的List的实现。

There's a difference between a type, an interface, and an implementation.类型、接口和实现之间存在差异。

Use Generics for Stronger Typing in Collections使用泛型在集合中进行更强大的输入

Use generic types, because static typing really helps with these errors.使用泛型类型,因为静态类型确实有助于解决这些错误。 Also, use interfaces where possible, except if you have a good reason to use the concrete type.此外,尽可能使用接口,除非您有充分的理由使用具体类型。

So your code becomes:所以你的代码变成:

List<String> nodes = new ArrayList<String>();
List<String> nodeList = new ArrayList<String>();
List<List<String>> list = new ArrayList<List<String>>();

Remove Unnecessary Code删除不必要的代码

You could do away with the nodeList entirely, and write the following once you've fixed your types:您可以完全取消nodeList ,并在修复类型后编写以下内容:

list.add(nodes);

Use the Right Scope使用正确的范围

Except if you have a very strong reason to do so, prefer to use the inner-most scope to declare variables and limit both their lifespan for their references and facilitate the separation of concerns in your code.除非您有非常强烈的理由这样做,否则更喜欢使用最内部的作用域来声明变量并限制它们的引用寿命并促进代码中关注点的分离。

Here you could then move List<String> nodes to be declared within the loop (and then forget the nodes.clear() invocation).在这里,您可以移动要在循环中声明的List<String> nodes (然后忘记nodes.clear()调用)。

A reason not to do this could be performance, as you might want to avoid recreating an ArrayList on each iteration of the loop, but it's very unlikely that's a concern to you (and clean, readable and maintainable code has priority over pre-optimized code ).不这样做的一个原因可能是性能,因为您可能希望避免在循环的每次迭代中重新创建ArrayList ,但您不太可能担心(并且干净、可读和可维护的代码优先于预先优化的代码) )。

SSCCE南昌

Last but not least, if you want help give us the exact reproducible case with a short, self-Contained, correct example .最后但并非最不重要的一点是,如果您需要帮助,请通过简短的、独立的、正确的示例为我们提供准确的可重现案例。

Here you give us your program's outputs, but don't mention how you got them, so we're left to assume you did a System.out.println(list) .在这里,您将程序的输出提供给我们,但不要提及您是如何获得它们的,因此我们假设您执行了System.out.println(list) And you confused a lot of people, as I think the output you give us is not what you actually got.你让很多人感到困惑,因为我认为你给我们的输出并不是你实际得到的。

Wouldn't it just be a case of:难道这不只是一个案例:

ArrayList<ArrayList<String>> outer = new ArrayList<ArrayList<String>>();
ArrayList<String> nodeList = new ArrayList<String>();

// Fill in nodeList here...

outer.add(nodeList);

Repeat as necesary.根据需要重复。

This should return you a list in the format you specified.这应该以您指定的格式返回一个列表。

The problem you have is caused that you use the same ArrayList NodeList over all iterations in main for loop.您遇到的问题是导致您在主 for 循环中的所有迭代中使用相同的 ArrayList NodeList Each iterations NodeList is enlarged by new elements.每次迭代NodeList都会被新元素放大。

  1. After first loop, NodeList has 5 elements (PropertyStart,a,b,c,PropertyEnd) and list has 1 element (NodeList: (PropertyStart,a,b,c,PropertyEnd))第一次循环后, NodeList有 5 个元素 (PropertyStart,a,b,c,PropertyEnd),列表有 1 个元素 (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))在第二个循环之后NodeList有 10 个元素(PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd)并且列表有 2 个元素(NodeList(有 10 个元素),NodeList(有 10 个元素))

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.您的代码不可读,请保持 Java 代码约定以获得可读代码。 For example is hard to recognize if NodeList is a class or object例如很难识别 NodeList 是类还是对象

Initiate the NodeList inside the for loop and you will get the desired output.在 for 循环内启动 NodeList,您将获得所需的输出。

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

        for(int i=0;i<PropertyNode.getLength()-1;i++){
            ArrayList NodeList=new ArrayList();
            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);
        }

Explanation: NodeList is an object which remains same throughout the loop so adding same variable to list in a loop will actually add it only once.说明:NodeList 是一个在整个循环中保持不变的对象,因此在循环中向列表添加相同的变量实际上只会添加一次。 The loop is only adding its variables in single NodeList array hence you must be seeing该循环仅将其变量添加到单个 NodeList 数组中,因此您必须看到

[/*list*/    [  /*NodeList*/   ]   ]

and NodeList contains [prostart, a,b,c,proend,prostart,d,e,f,proend ...]和 NodeList 包含 [prostart, a,b,c,proend,prostart,d,e,f,proend ...]

Very first will declare outer Arraylist which will contain another inner Arraylist inside it首先将声明外部 Arraylist,其中将包含另一个内部 Arraylist

ArrayList> CompletesystemStatusArrayList; ArrayList> CompletesystemStatusArrayList; ArrayList systemStatusArrayList ArrayList systemStatusArrayList

CompletesystemStatusArrayList=new ArrayList CompletesystemStatusArrayList=新的ArrayList

systemStatusArrayList=new ArrayList(); systemStatusArrayList=new ArrayList();

    systemStatusArrayList.add("1");
    systemStatusArrayList.add("2");
    systemStatusArrayList.add("3");
    systemStatusArrayList.add("4");
    systemStatusArrayList.add("5");
    systemStatusArrayList.add("6");
    systemStatusArrayList.add("7");
    systemStatusArrayList.add("8");

    CompletesystemStatusArrayList.add(systemStatusArrayList);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM