简体   繁体   English

将元素添加到数组列表

[英]Add elements to Array list

I have an array list of array list: 我有一个数组列表的数组列表:

ArrayList<ArrayList<Character>> NodesAndServices = new ArrayList<ArrayList<Character>>();

I want to add eachRow of NodesAndServices to another arraylist allChars : 我想将NodesAndServices的NodesAndServices添加到另一个arraylist allChars

    List<Character> allChars = new ArrayList<Character>();

    for (int i = 0; i < NodesAndServices.size(); i++) {
    List<Character> eachListRow = NodesAndServices.get(i);

    for (List<Character> chr : eachListRow) { //Error
        for (char ch : chr) {
            allChars.add(ch);
        }
    }
}

But u get compile time error: 但是你得到编译时错误:

required: java.util.list
found: java.lang.character

UPDATE UPDATE

for (int i = 0; i < NodesAndServices.size(); i++) {
    List<Character> eachListRow = NodesAndServices.get(i);

    for (Character chr : eachListRow.get(i)) { //Error,foreach not applicable to type character

            allChars.add(each);
    }
}

eachListRow is not a list of lists. eachListRow不是列表列表。 Try this: 尝试这个:

 for (Character chr : eachListRow) {...

Update: 更新:

 for (int i = 0; i < nodesAndServices.size(); i++) {
        List<Character> eachListRow = nodesAndServices.get(i);

        for (Character chr : eachListRow) {
            allChars.add(chr);
        }
    }
for (List<Character> chr : eachListRow) { //Error

When writing an enhanced for loop like this one, the loop variable chr will take the value of each element of the collection eachListRow , which is a List<Character> . 当编写像这样的增强的for循环时,循环变量chr将采用集合eachListRow中每个元素的值,即List<Character> Therefore, chr must be of type Character , not List<Character> . 因此, chr必须为Character类型,而不是List<Character>

Then you'll realize you don't even need the nested loop: 然后您将意识到甚至不需要嵌套循环:

for (Character chr : eachListRow) { // OK
    allChars.add(ch);
}

Note: you could also use an enhanced for loop for the first loop, leading to the following code, which is much nicer to read: 注意:您也可以在第一个循环中使用增强的for循环,从而导致以下代码,这更易于阅读:

List<Character> allChars = new ArrayList<Character>();

for (List<Character> eachListRow : NodesAndServices) {
    for (Character chr : eachListRow) {
        allChars.add(ch);
    }
}

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

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