简体   繁体   中英

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 :

    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

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. 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> . Therefore, chr must be of type Character , not 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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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