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?

1
  • 2
    I agree with Mark. Using an array index rather than the field names would be the way I'd do it. Commented Jun 24, 2010 at 19:01

3 Answers 3

11

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];
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Mark. Do you know of good code to look at as example?
Better yet, use some Collection. Avoid using arrays when possible.
While we're introducing arrays to Joe, maybe you can give an example of a foreach and an iterated loop, as well?
I need to use array in this case. But thanks Colin! This is helping a lot. Thank you guys.
1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.