I have several fields, each one is like this:
field1
field2
field3
...
Using a loop with a counter, I want to be able to say fieldx. Where x is the value of the counter in that loop. This means if I have 6 entries in my array, fields1 - field6 will be given values.
Is fieldx possible?
I think you would have to go through reflection. Have a look at the
java.lang.reflect
package, specifically theField
class.You can do it with reflection, but in general it is better if you can declare your fields in an array. Instead of:
You can do this:
Then you can loop over the array setting the values:
As an alternative using a plain ol' array (see Mark's answer), you could use an
Arraylist
. Declare your fields like so:Then after putting in the fields (most likely using
fields.add(SomeType t)
, you can iterate using:ArrayLists
have all the same features of arrays with some additional benefits, like compatibility with generics.Also note that as of Java 5, you can use for-each loops with arrays! So, instead of keeping track of indeces and remembering whether you need to call
length
orsize()
, you can use a for-each loop.