Java - Can I combine different data types to form an object/instance name?

memphis_1220

Limp Gawd
Joined
Aug 28, 2004
Messages
499
Hi

I have multiple instances of a custom class called a1,a2,a3,...an;

I would like to call a function from each using a for loop.

Is it possible to do something like the following:

for(int i=0;i<20;i++)
{
ai.getSomething(); // I know this isnt doing anything, just as an example.
}

Can I loop through numbers 1 to 19 and effectively call:
a1.getSomething();
a2.getSomething();
a3.getSomething();
etc?
 
You can do something similar using an array of the objects:
Code:
CustomClass instanceList[] =
{
   a1,a2,a3,a4,a5,
   a6,a7,a8,a9,a10,
   a11,a12,a13,a14,a15,
   a16,a17,a18,a19,a20
};


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

Does that satisfy your needs?
 
Tawnos said:
You can do something similar using an array of the objects:
Code:
CustomClass instanceList[] =
{
   a1,a2,a3,a4,a5,
   a6,a7,a8,a9,a10,
   a11,a12,a13,a14,a15,
   a16,a17,a18,a19,a20
};


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

Does that satisfy your needs?

This works up until I come to access the arrary. A cannot find symbol error pops up :S
 
You should be able to do something like this using the Reflection API. But I'm not going to tell you how, because I might have to work on code you write someday. This is a really bad practice to get into. You really should be using an array or a Collection.
 
You initialized the objects, right? That array just contains references to the objects, if I remember my java correctly.
 
How about something like this?
Code:
d-laptop> cat Test.java
class Test {
        public static void main(String[] args) {
                String test[] = new String[3];

                for(int i=0; i<test.length; i++) {
                        test[i] = Integer.toString(i);
                }

                for(int i=0; i<test.length; i++) {
                        System.out.println(test[i]);
                }
        }
}
d-laptop> javac Test.java ; java Test
0
1
2
d-laptop>

You should be able to see how to generalise this to do whatever you want with a custom class.
 
Tawnos said:
You can do something similar using an array of the objects:
Code:
CustomClass instanceList[] =
{
   a1,a2,a3,a4,a5,
   a6,a7,a8,a9,a10,
   a11,a12,a13,a14,a15,
   a16,a17,a18,a19,a20
};


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

Does that satisfy your needs?

After a bit of tweaking this works perfectly, many thanks!

Tawnos said:
You initialized the objects, right? That array just contains references to the objects, if I remember my java correctly.

Yup

LuminaryJanitor said:
I think this should be CustomClass[] instanceList = ..., which might explain why it's not working.

I tried it both ways for peace of mind. I believe arrays can be defined either way.
 
Back
Top