Reputation: 2363
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);
}
}
Upvotes: 1
Views: 120
Reputation: 5424
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);
}
}
Upvotes: 1
Reputation: 37859
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);
}
}
Upvotes: 1