Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use a String instead of a variable name in Java

I've created 3 variables

radio1 radio2 radio3

is it possible to use a for loop and from a String called "radio" to add the counter in the end in order to get the variable?

for instance something like this

for(i=1;i<=3;i++)
    if(("radio" + i).method())
          do something

thanks in advance

like image 521
ksm001 Avatar asked Feb 28 '26 12:02

ksm001


2 Answers

You can use a Radio object and use arrays instead:

Radio[] radios = new Radio[] {radio1, radio2, radio3};
for(i=0;i<3;i++)
    if(radios[i].method())
          do something

If you want to access variable by forming their names, you can also use Java's reflection API. But it is an expensive operation and is not advisable in general.

like image 145
Hari Menon Avatar answered Mar 03 '26 03:03

Hari Menon


It looks to me like you want to use a Dictionary or similar data structure, which lets you store objects indexed by, for example, a string.

EDIT

As several people noted, HashMap is a more modern and better alternative.

like image 39
dsolimano Avatar answered Mar 03 '26 03:03

dsolimano