I am playing around learning Lambda within Java and needed to create a list of variables. I created a for loop which creates a new String variable on each iteration, however each one has the same variable name which is not aloud outside of a for loop.
I see in the following post, Why is it allowed to declare a variable in a for loop? , they detail that its because of the scope of the created variable within the loop. However, I added the variable to an ArrayList outside of the scope of the for loop and then iterated through it to see that the duplicated name variables still exists with no errors.
I duplicated the code to have each variable have the same String value as well, to check if it had something to do with the values being different, but it still allowed the variables to be stored into the Array...
Code is below.
import java.util.ArrayList;
public class Lambda
{
public static void main(String[] args)
{
ArrayList<String> names = new ArrayList<String>();
for(int i = 0; i<10; i++)
{
String name = "name: ";
names.add(name);
}
names.forEach((name) -> {System.out.println(name);});
System.out.println("\n***********************************\n");
for(String temp: names)
{
System.out.println(temp);
}
}
}
The code fragment
ArrayList<String> names = new ArrayList<String>();
for(int i = 0; i<10; i++)
{
String name = "name: ";
names.add(name);
}
is equivalent to
ArrayList<String> names = new ArrayList<String>();
// here the `ArrayList` referenced by `names` is empty
{
String name = "name: ";
names.add(name);
}
// at this point there is no variable called name
// the `ArrayList` referenced by `names` contains one reference to the string "name: "
{
String name = "name: ";
names.add(name);
}
// at this point there is no variable called name
// the `ArrayList` referenced by `names` contains two references to the string "name: "
// some repetitions left out for brevity
I think your misunderstanding is this:
I added the variable to an
ArrayList
outside of the scope of the for loop
You cannot add variables to an ArrayList
- you can only add the objects referenced by variables to an ArrayList
The ArrayList.add()
doesn't know how you called your variable - or whether you used a variable at all - maybe you were calling it as names.add("name: ");