randomly generate variable names?
I've got a problem.. I've got something like...
if(condition(TEST) == true){
something (NAME) = new something(this);
}
This is inside a loop where there are man开发者_StackOverflow中文版y TEST variables being iterated through. I don't know how many and its possible each of them would need a "(NAME)" variable so basically I want to know how would I make java "on the fly" generate a name for these variables?
Thanks!
Are you sure you don't want to store the results in either an array or a collection?
The closest thing would be to use a Map
. Randomly generate a String
or an Integer
key, and use it as a key to your Something
value.
// Before all
Map<String, Something> myMap = new HashMap<String, Something>();
// For each of these
if(condition(TEST) == true){
String name = "VAR" + Math.random() // Don't remember the syntax here
myMap.put(name, new something(this));
}
Unless I'm misunderstanding your problem, you won't need to do this.
Variables in Java are lexically scoped, in that they are defined solely for the block in which they exist. On every iteration through the loop, your name
parameter will refer to a different object, and will not be affected by the values it held on previous loops.
So you will only need as many parameters in your loop as there are attributes you want to operate on within the loop (possibly only one), which in all cases is something you'll know for sure when you write your code (at compile time) and is divorced from the (runtime) number of TEST objects.
If you're not storing them or referencing them later, and they're all the same type, you could use the same variable for all of them:
// Outside loop ...
something $name;
// Inside loop ...
if(condition(TEST) == true){
$name = new something(this);
}
The simplest way to generate in id (e.g. for a Map) is to use an AtomicInteger.
AtomicInteger counter = new AtomicInteger();
Map<String, Something> map = ...
String id = Integer.toString(counter.getAndIncrement(), 36);
map.put(id, new Something());
// later
Something s = map.get("0");
or it would be simpler to use a List which is naturally indexed.
List<Something> list = ...
list.add(new Something());
// later
Something s = map.get(0);
精彩评论