tags:

views:

701

answers:

5

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.

A: 

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.

Here Be Wolves
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
No, the OP wants to create variables with a name determined at runtime. But there are no variable names at runtime.
newacct
+1  A: 

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
+6  A: 

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>());
Rob Di Marco
+1  A: 

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
A: 

You Can't!

There is no direct way to this. Arrays, reflection etc. can help.

NinethSense