Java quick question on "dynamic" variables
Let's say I've got an app that reads information from a config file. And let's say that every time I encounter the word "Hello" in that config file I want to be able to create a variable of type String and name it Hello0, Hel开发者_运维百科lo1, Hello2, etc etc...
I know dynamic variables like this are not possible (for the most part) in programming. But would there be some kind of workaround? Like letting the user decide how many variables to have?
Hash maps are very good for storing this kind of information.
hashMap.put("Hello0", string);
stores your info
hashMap.get("Hello0");
pulls it out.
If you want these to be "Class" (member) variables you can make the hashmap a member variable so that it will stick around the life of the class.
This is very common. Many dynamic languages like Ruby actually use hashmaps for all their variables, but they hide the syntax so you access them like you do in any language.
If the syntax really bugs you, start your class like this:
public class MyClass {
private HashMap<String, Object> vars=new HashMap();
private var(String s, Object o) {
vars.put(s, o);
}
private Object var(String s) {
return vars.get(s);
}
}
Then from anywhere in the class you can use:
var("var1", 5); // create or update variable 1 to the value 5
System.out.println("value ="+var("var2")); // get variable
for a slightly better syntax. (But be careful of the first example--if you have problems look up "Autoboxing" because that's what Java does when you pass an int as an object)
Sounds like you just need a List<String>
instead - or if you need to access them by name, perhaps a Map<String, List<String>>
. (So "Hello" maps to a list of string values.)
精彩评论