Java: how to turn local references created in for loop into global references?
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, t开发者_开发百科he 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:
TestLocal t = null;
for (int i=1; i<1; i++) {
TestLocal t=new TestLocal();
}
System.out.println("This is the new object: " + t );
Note that this will print null
though, 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:
List<TestLocal> list = new ArrayList<TestLocal>();
for (int i = 0; i < 10; i++) {
list.add(new TestLocal());
}
// Now access the objects via list
Put them in a collection. For example a Set
Set<TestLocal> set = new HashSet<TestLocal>();
for (..) {
TestLocal t = new TestLocal();
set.add(t);
}
Then you can iterate your instances:
for (TestLocal t : set) {
// access each instance
}
If you want just one instance to be accessible outside, then simply define it outside:
TestLocal t = null;
for (..) {
t = new TestLocal();
}
精彩评论