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.

3
  • 13
    my head hurts, what the heck? Commented Jun 3, 2009 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. Commented Jul 29, 2018 at 19:26
  • @bakriawad think I got it, thanks...but head still hurts (9 years later) Commented Aug 2, 2018 at 14:23

4 Answers 4

13

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>());
Sign up to request clarification or add additional context in comments.

1 Comment

I believe Map<String,Object> 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));
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.

2 Comments

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.
No, the OP wants to create variables with a name determined at runtime. But there are no variable names at runtime.
2

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.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.