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.