1

I have a for loop that adds values to an array of objects. Say I have class B, and make a array of class B inside class A. like

    B array1 = new B[10];

How can I name each object with a reference name that will look like

for(int x = 0; x<array1.length; x++){
    B object+x = new Bar(int value1, int value2);
    x++;
}

each time it goes through the for-loop I'm not sure how to add a number after "object" so that I can have 10 array objects like object1, object2, object3...

I want to be able to reference these saved objects inside another method in class A, without creating a new object each time, and then call a method from class B on the object.
Sorry I cant provide much code, its part of a assignment and I cant post my code.

mint_x
  • 9
  • 3
  • how about using an array of arrays? (aka https://stackoverflow.com/questions/1067073/initialising-a-multidimensional-array-in-java) – Bill Oct 07 '17 at 10:08
  • You can't do something like that. The closest thing you have to that is an array. – Joe C Oct 07 '17 at 10:09
  • @JoeC what do you mean? My teachers have said to create an array like this. – mint_x Oct 07 '17 at 10:20
  • Why do you want do that?The item of array have a reference named array[index],why do you want another reference to point it? – dabaicai Oct 07 '17 at 10:37
  • Java can't do that (although [Rexx](https://en.wikipedia.org/wiki/Rexx) can!). Exactly why do you want to "name" the `B` instances? If you really need to access them by name, use a `Map` – Bohemian Oct 07 '17 at 16:28

1 Answers1

0

You cannot this. In Java you cannot create variables with dynamic names calculated in runtime. If you think your teacher asked this of you, it is very likely a misunderstanding.

The closest would be probably something like:

Bar[] array1 = new Bar[10];

for(int x = 0; x<array1.length; x++){
    array1[x] = new Bar(...);
}
lexicore
  • 42,748
  • 17
  • 132
  • 221