views:

130

answers:

3

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?

+10  A: 

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];
}
Mark Byers
Thanks Mark. I wasn't thinking ><
badpanda
Thanks Mark. Do you know of good code to look at as example?
Joe
Better yet, use some `Collection`. Avoid using arrays when possible.
ColinD
While we're introducing arrays to Joe, maybe you can give an example of a foreach and an iterated loop, as well?
Jonathon
I need to use array in this case. But thanks Colin!This is helping a lot. Thank you guys.
Joe
Big thank you!!
Joe
A: 

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

aioobe
Thankfully, he will use an array instead.
Dimitris Andreou
+1  A: 

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.

Justin Ardini