1

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);
    }
}
1
  • 2
    Not related to the question, but NodesAndServices should start with a lowercase to meet Java conventions. Commented Aug 9, 2015 at 17:24

2 Answers 2

1
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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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);
        }
    }

2 Comments

I get this error: foreach not applicable to type character
@S-H, remove this error line, it's redundant because you already got the character in chr. Just add chr to you result list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.