Reputation: 812
The code below gives me a compiling error. It says I should have initialised v
somewhere before using it in the second loop while in the first loop everything seems fine. I thought maybe it will implicitly initialised to 0. Appreciate any feedback on this. Also, What is the best practice in such cases.
public static void main(String[] args) {
ArrayList<Integer> list=new ArrayList<Integer>();
ArrayList<Integer>[] list2=(ArrayList<Integer>[])new ArrayList[10];
for(int v:list)
System.out.println(v);
for(int v:list2[v])
System.out.println(v);
}
Upvotes: 0
Views: 70
Reputation: 4692
Have look at this article http://www.java-made-easy.com/variable-scope.html.
It states.
Any variables created inside of a loop are LOCAL TO THE LOOP. This means that once you exit the loop, the variable can no longer be accessed! This includes any variables created in the loop signature.
Upvotes: 0
Reputation: 556
Your code is similar to the following code.
//begin loop 1
for(int v:list){
System.out.println(v);
}
//end loop 1
//begin loop 2
for(int v:list2[v]){
System.out.println(v);
}
//end loop 2
Here the variable v will lost to the program because it is limited to the first for loop. (Same as method local variable)
The correct code would be like this :
for (int v : list) {
System.out.println(v);
for (int x : list2[v]) {
System.out.println(x);
}
}
Upvotes: 1
Reputation: 23015
The scope of your first 'v' is limited to the first for loop.
So in the second loop, the 'v' you use in the subscript is not declared when it is first used.
What do you expect to do in the second 'for'? Print everything inside list2 ? If yes, then you need to make a nested for loop like this:
for(ArrayList<> innerList : list2)
for(int i : innerList)
System.out.println(i);
Notice that as list2 contains ArrayLists and not ints, then you cannot do the for as you had it in your code (the iterating variable cannot be an int).
Upvotes: 3
Reputation: 92
The first 'v' which you have declared is only limited to first for loop, and the second 'v' is limited to only second for loop, so you can access the first 'v' with in the second for loop
Upvotes: 2