Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java support variable variables?

Tags:

java

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.

like image 969
me_here Avatar asked Jun 03 '09 13:06

me_here


People also ask

Can you name a variable with a variable in Java?

A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign " $ ", or the underscore character " _ ". The convention, however, is to always begin your variable names with a letter, not " $ " or " _ ".

What are the 3 types of variables in Java?

There are three different types of variables a class can have in Java are local variables, instance variables, and class/static variables.

Which variable Cannot be used in Java?

Which of these can not be used for a variable name in Java? Explanation: Keywords are specially reserved words which can not be used for naming a user defined variable, example: class, int, for etc.


3 Answers

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>());
like image 165
Rob Di Marco Avatar answered Sep 22 '22 12:09

Rob Di Marco


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.

like image 33
jrharshath Avatar answered Sep 24 '22 12:09

jrharshath


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.

like image 2
jjnguy Avatar answered Sep 23 '22 12:09

jjnguy