简体   繁体   中英

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

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.

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.

You should be using an array so you can easily iterate over all of them.

You could also play with Lists if you do not know how many items there wil be.

The most convenient way is to use an intermediate array like this:

Radio radio1, radio2, radio3;
for(Radio radio: Arrays.asList(radio1, radio2, radio3))
    if( radio.method() )
        doSomething();

The java.util.Arrays is provided by the JDK.

This works. But please think about it, how many times you really want three separate Radio instances vs. how many times you are not interested in one of them but in all of them. In the later case put the three instances into a Collection or into an array right from the start and forget about the three individual instances.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM