How to create local references created in for loop into global references? The following code wont compile:
Also, in real project, the number of t’s and type of t’s are data driven (I’m looping through a map of maps to make decision), so I cannot specify t before starting for loop…..
public class TestLocal{
public static void main(String [] args){
for (int i=1; i<1; i++){
TestLocal t=new TestLocal();
}
System.out.println("This is the new object: " + t );
}
}
How could I make t accessible from outside for loop?
more code
Note:
1)test has many values, and what instance to create depends on its value.
2) since I’m looping through a map of maps which are data driven, the number of instances to be created depend on the number of inner maps……
for (int i=0;i<sortedMap.size();i++){
ArrayList<Object> a = new ArrayList<Object>(sortedMap.keySet());
Object o=a.get(i);
HashMap m=(HashMap)sortedMap.get(o);
int test = ((Number)m.get("textType")).intValue();
if (test==3){
System.out.println("all together: " + sortedMap.size() + "each element is: " + o + " value: " + m.get("textType"));
String mytest = (String)m.get("text");
ChapterAutoNumber chapter1 = new ChapterAutoNumber(mytest);
}
There’s no such thing as a “local reference” or a “global reference”. You’re just trying to access a variable without it being in scope. You want something like:
Note that this will print
nullthough, because you’re not actually going to run the loop body (because 1 is not less than 1).If you want to collect the objects created in the loop, a list may be more appropriate: