1

Say I have a variable test with the value example. I want to make a new variable that is called the value of test, so the new variable would be called example.

Is this possible? If so, how?

Piccolo
  • 1,612
  • 4
  • 22
  • 38
  • Can you describe why you want this, and what you would do with the variable once created? Sounds more like a use for a Map than a regular Java variable. – Paul Grime Mar 31 '13 at 22:20
  • 1
    No you can't do that. That's like meta programming. – Sotirios Delimanolis Mar 31 '13 at 22:21
  • 2
    You can simulate this by using a `Map variables`. Example: `Map variables = new HashMap(); String test = "example"; variables.put("example", test)`; – Luiggi Mendoza Mar 31 '13 at 22:22
  • 2
    The answer is that no this can't be done nor should it be attempted. Variable names are not as important as you might think and almost don't exist in compiled code. Instead it's references that matter, and these can be associated with Strings via a Map (as @LuiggiMendoza notes above). – Hovercraft Full Of Eels Mar 31 '13 at 22:27
  • My intended use for this is as follows: I'm making a chat server, and I an storing all of the usernames in an ArrayList of the class `User` (which I made). I wanted to name each variable of User the name the user chose, because then it would be easier to remove from the list later on (i.e. `UserList.remove([name]);` I guess I'll store arbitrary variable names like `user`, and then to remove, have a `for` loop looking for the User.name property. Thanks everyone! – Piccolo Mar 31 '13 at 22:45
  • Again, use a Map. Please look at A.R.S.'s answer (1+) and follow it. – Hovercraft Full Of Eels Mar 31 '13 at 23:28
  • Also http://stackoverflow.com/questions/958848/is-it-possible-to-name-a-variable-using-a-variable-in-java?rq=1, and many others. – Stephen C Mar 31 '13 at 23:37

1 Answers1

3

No, this is not possible in Java. Variable names cannot be set at runtime. However, you can mimic this using a Map that maps String identifiers to values.

String test = "example";
...
Map<String, String> vars = new HashMap<String, String>();
vars.put(test, "...");
arshajii
  • 127,459
  • 24
  • 238
  • 287