Is it possible to set a variable, if i want to have it flexible? I think an exmaple makes it easier to understand.
String hallo1;
String hallo2;
for(int i = 0; i < 2; i++) {
hallo & i = Integer.toString(i);
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you really have a need to have variables with names not known at compile time, you can achieve this effect by creating a structure that holds arbitrary names and values. Like, you could create a HashMap where the key is the name. Then your example above becomes something like:
Later you’d pull them out with:
etc.
Of course you can’t access values from the map as variables directly, you’d always have to do put and get to update and retrieve them, but the concept is the same.
That said, I’d be very cautious about doing this, because it makes the code difficult to maintain. If the names that you need are really coming out of the blue — if you’re writing generic code to read an arbitrary database table whose name was typed in by the user at runtime or something like that — cool. But if you’re thinking that this is a handy shortcut for something like:
My simple answer would be DON’T!! The code is much easier to maintain if you use the IF statement and normal variables. Then anyone reading the code can look at your declarations and see what all the possible variables are. You can do text searches to find everywhere they’re used. If you mis-spell a variable name, instead of magically creating a new variable you will get a clean compile-time error message. Etc.
On the other hand, if you COULD write something like
you would have no idea what variables exist in your program and no way to track where they are used.