0

I have method getMap(String name, Integer value) so inside method i'm creating new HashMap() object, but i want HashMap() object reference name as String name value

Here is my code, i know i should not do like this because name is String type, but just to show

public static void main(String[] args) {
    getMap("refMap", 10);

    }

public static void getMap(String name, Integer value) {

    Map name = new HashMap<>();  // Compile Error duplicate local variable
    //Map refMap = new HashMap<>(); i want like this

}

Is this possible?

Deadpool
  • 33,221
  • 11
  • 51
  • 91
  • You need to create a [mcve] that we really can understand. So far I can see that you have a `String name`, a `Integer value` and you want to meddle with `Map` out of nowhere (you aren't even returning a `Map`!). – Jai Jul 16 '18 at 02:38
  • can you tell us why you need to create a variable name from the method parameter – Keaz Jul 16 '18 at 03:09
  • it's just to learn Java has that feature or not, in some of the script languages we can achieve that – Deadpool Jul 16 '18 at 03:12
  • Does the `Map` *have* to be named `name`? In the comment you use `refMap` instead. Is this not an option? And what do you mean by ' want HashMap() object reference name as String name value'? Do you want to put the value `value` for the key `name` into the map? Also, what do you do with the new map? `getMap` sounds like you want to return it. –  Jul 16 '18 at 07:53

1 Answers1

1

I'm assuming you know about HashMaps because of the code you have listed. You can use HashMaps to associate String values to specific objects which serves a similar purpose as naming the object as the String value parameter.

Check out this answer: Creating a variable name using a String value

josh
  • 354
  • 1
  • 16
  • so just in one word this is not possible in this way, am i right? – Deadpool Jul 16 '18 at 02:30
  • Yes, this is not possible in Java. Although other languages like PHP offer support for this, Java was not designed to do this. – josh Jul 16 '18 at 15:19