-3

I want create 10 objects in a loop and assign them to variables.

for (int i = 0; i <= 10; i++) {
    Cat i = new Cat();
}

How can I create a variable name dynamically?

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
Mr tintin
  • 1
  • 4

1 Answers1

-1

Something like this might be the solution you are looking for,

ArrayList<Cat> catList = new ArrayList<>();

for(int idx = 0; idx < 10; idx++){
    catList.add(new Cat());
}

// In order to retrieve items,

// catList.get(0) -> Object first inserted.
// catList.get(1) -> Object second inserted.....
static const
  • 953
  • 4
  • 16
  • That will create 11 objects, not 10. – FredK Jun 27 '19 at 20:42
  • That is what OP is using in his loop. But I guess I missed the part where he said he wants to create 10 objects, it thought it was for java 10. I will update my answer. Thanks – static const Jun 27 '19 at 20:43