Joe
Joe

Reputation: 33

Use a variable within a variable?

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?

Upvotes: 3

Views: 267

Answers (3)

Justin Ardini
Justin Ardini

Reputation: 9866

As an alternative using a plain ol' array (see Mark's answer), you could use an Arraylist. Declare your fields like so:

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

Then after putting in the fields (most likely using fields.add(SomeType t), you can iterate using:

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

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 or size(), you can use a for-each loop.

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838156

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

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

You can do this:

SomeType[] fields = new SomeType[6];

Then you can loop over the array setting the values:

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

Upvotes: 11

aioobe
aioobe

Reputation: 420961

I think you would have to go through reflection. Have a look at the java.lang.reflect package, specifically the Field class.

Upvotes: 0

Related Questions