0

I am not able to create the name of the object at runtime. My statement is:

Map<String,String>  objectName+""+lineNumber = new HashMap<String,String>();

It's giving me compiletime error. I want to create the HashMap object at runtime depending upon the line number.

Jayy
  • 2,368
  • 4
  • 24
  • 35
user900721
  • 1,417
  • 4
  • 17
  • 29

3 Answers3

1

Java is not a interpreted but rather a compiled language. So the compiler does not knows how to handle this. Such a thing might make sense in a scripting language.

If you need a custom Name for a "variable" maybe a construct like the following might make sense:

Map<String,Map<String,String>> varMap = new HashMap<String,Map<String,String>>();
varMap.put(objectName+" "+lineNumber, new HashMap<String, String>());
romedius
  • 775
  • 6
  • 20
0

You can't do this directly in Java (without major tricks)

What you can (and probably should) do:

Put your Map in another map which has the 'variable' name as a key.

If you really want to do that you have to do code generation. For this again you have multiple options:

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
-1

Having a dynamic object name is of No Use.

At first, it's not possible to give reference a dynamic name. The bigger question is Why do you want to do it?

If, just for learning and doing experiments, I'll suggest you should follow proper exercises.

But, if you are trying to achieve some project requirement, Pls. explain the requirement. There will be some other way to achieve that.

Azodious
  • 13,752
  • 1
  • 36
  • 71