19

Such as in PHP:

<?php
$a = 'hello';
$$a = 'world';

echo $hello;
// Prints out "world"
?>

I need to create an unknown number of HashMaps on the fly (which are each placed into an arraylist). Please say if there's an easier or more Java-centric way. Thanks.

me_here
  • 2,329
  • 5
  • 19
  • 13
  • 13
    my head hurts, what the heck? – Gareth Davis Jun 03 '09 at 13:54
  • @GarethDavis , it is basically a way to reference a variable using a string, if `$a = "hello";`, then `$$a="world";` is equivalent to `$hello="world";`, it used the string as a variable name... this actually can be extremely powerful when used well, thanks to it, it made class builds for json encoding purposes a walk in the park, literally took 1 line to do with it; example: `function addParam($key,$val){$this->${$key} = $val }`. a new variable under the class gets created out of nothing at runtime. – bakriawad Jul 29 '18 at 19:26
  • @bakriawad think I got it, thanks...but head still hurts (9 years later) – Gareth Davis Aug 02 '18 at 14:23

4 Answers4

14

The best you can do is have a HashMap of HashMaps. For example:

Map<String,Map<String,String>> m = new HashMap<String,Map<String,String>>();
// not set up strings pointing to the maps.
m.put("foo", new HashMap<String,String>());
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
Rob Di Marco
  • 43,054
  • 9
  • 66
  • 56
  • 1
    I believe `Map` would fit better to match PHP's environment. Obviously checks of `map.get("key") instanceof Object.class` would have to be used for non string objects, for primitive types you would need to use their object form instead , i.e. `map.put("key",new Integer(5));` – bakriawad Jul 29 '18 at 19:38
3

Java does not support what you just did in PHP.

To do something similar you should just make a List<Map<>> and store your HashMaps in there. You could use a HashMap of HashMaps.

A 'variable variable' in Java is an array or List or some sort of data structure with varying size.

jjnguy
  • 136,852
  • 53
  • 295
  • 323
2

Its not called variable variables in java.

Its called reflection.

Take a look at java.lang.reflect package docs for details.

You can do all such sorts of things using reflection.

Bestoes,

jrh.

jrharshath
  • 25,975
  • 33
  • 97
  • 127
  • 3
    Well, you can, but it's not a good idea. For various reasons, particularly type safety and performance, reflection should generally only be used as a last resort. Here just using a Map (as described in other answers) is more appropriate. – sleske Jun 03 '09 at 15:17
  • 2
    No, the OP wants to create variables with a name determined at runtime. But there are no variable names at runtime. – newacct Jun 03 '09 at 15:44
1

No. You would do something like

List<Map<String,String> myMaps = new ArrayList<Map<String,String>>()

and then in your loop you would do:

Map<String,String> newMap = new Hashtable<String,String>();
//do stuff with newMap
myMaps.add(newMap);
Chad Okere
  • 4,570
  • 1
  • 21
  • 19