I have the variable X, which is constantly changing. How would I be able to declare a new String named after the value of variable X? I am using this in a while loop, where each cycle, I need to temporarily declare a variable to hold information.
Asked
Active
Viewed 71 times
0
-
2how would other code reference this randomized name? how about place each object into a Collection of some sort, like an array or map.. – Randy Jul 14 '14 at 21:36
-
1Sounds like you want to use a [HashMap](http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html) – PoByBolek Jul 14 '14 at 21:37
-
I should use a HashMap, but I would prefer to use variables here, is it possible though? – Starfire1337 Jul 14 '14 at 21:38
-
1It is neither possible nor desirable, I think. – David Conrad Jul 14 '14 at 21:42
-
The only language I've ever used that had this ability was REXX. (Boy, you could do some nasty and convoluted things with that feature!) – Hot Licks Jul 14 '14 at 22:22
1 Answers
0
What you're trying to do isn't possible. The compiler needs to know the names of all variable names at compile time, but your loop won't execute until runtime. Use a HashMap as suggested by PoByBolek and Starfire1337.

Tim
- 2,027
- 15
- 24
-
It **is** possible, see the answers in http://stackoverflow.com/questions/1192534/is-there-away-to-generate-variables-names-dynamically-in-java. Ths doesn't mean it's a good idea though :) – DavidPostill Jul 15 '14 at 10:47