If you really need to have variables with names unknown at compile time, you can achieve this effect by creating a structure that contains arbitrary names and values. For example, you can create a HashMap where the key is the name. Then your example above looks something like this:
HashMap myData=new HashMap(); for (int i=0;i<2;++i) { myData.put("hallo"+i,Integer.toString(i)); }
Later you pull them out:
String whatever=myData.get("hallo1");
and etc.
Of course, you cannot directly access the values ββfrom the map as variables, you will always need to make and receive updates and extract them, but the concept is the same.
However, I would be very careful about this because it makes code maintenance difficult. If the required names really get out of hand - if you write common code to read an arbitrary database table whose name was entered by the user at runtime or something like that - cool. But if you think this is a convenient shortcut for something like:
if (region.equals("1")) region1Total+=amount; else region2Total+=amount;
My simple answer would be NOT! Code is much easier to maintain if you use the IF statement and regular variables. Then anyone who reads the code can look at your ads and see what all the possible variables are. You can search for text to find wherever they are used. If you name the variable incorrectly, instead of magically creating a new variable, you will receive a clean compilation error message. Etc.
On the other hand, if you CAN write something like
String n=getInputFromScreen(); String s=getAnotherInputFromScreen(); hallo & n = s;
you would not have imagined which variables exist in your program and there is no way to track where they are used.
source share