Use a variable inside a variable?

I have several fields, each of which looks as follows:

field1
field2
field3
...

Using a loop with a counter, I want to say fieldx. Where x is the counter value in this loop. This means that if I have 6 entries in my array, fields1 to field6 will be given values.

Is field x possible?

+3
source share
3 answers

You can do this using reflection , but in general it is better if you can declare your fields in an array. Instead:

SomeType field1;
SomeType field2;
SomeType field3;
...
SomeType field6;

You can do it:

SomeType[] fields = new SomeType[6];

Then you can iterate over the array by setting the values:

for (int i = 0; i < fields.length; ++i)
{
    fields[i] = yourValues[i];
}
+11
source

, ol 'array (. "" ), Arraylist. :

ArrayList<SomeType> fields = new ArrayList<SomeType>();

( , fields.add(SomeType t), :

for (Sometype t : fields)
{
    // Do stuff with t
}

ArrayLists , .

, Java 5 ! , , , length size(), for-each.

+1

, . java.lang.reflect, Field.

0

Source: https://habr.com/ru/post/1751642/


All Articles