Let's say I have a class myClass and a String myString. How would I do this:
myClass [value of myString] = new myClass;
Let's say I have a class myClass and a String myString. How would I do this:
myClass [value of myString] = new myClass;
You can't have a dynamic variable in Java. Still, you can use a Map<String, Object> to have the String myString as the key and set the new value as new instance of your class:
Map<String, Object> map = new HashMap<String, Object>();
map.put(myString, new MyClass());
If you're sure your map will only contain MyClass instances, then you can use Map<String, MyClass>.
Map<String, MyClass> map = new HashMap<String, MyClass>();
You cannot use the value of a string variable as a variable name. Java doesn't allow that.
However, with a Map, you can associate a string (as a key) to a value:
Map<String, MyClass> map = new HashMap<String, MyClass>();
map.put(myString, new MyClass());
It's not exactly what you're looking for, but in Java, that's as close as you're going to get.
myString.what about using generics and creating a base class with type parameters
public MyGenClass<K,V>{
private Map<K,V> map = new HashMap<K,v>();
public Map<K,V> getMap(){
return map;
}
public void setMap(Map<K,V> iMap){
map=iMap;
}
}
using this class, you can easily get different kind of maps while having similar methods.
enjoy :)