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

I have created class Ticket and I need to create 10 tickets in a loop, but I have a problem with name for that object. In this code that I write above name for object is t1. I am wondering if there is a way to change this name every time when I'm creating new object in loop for.

Ivar
  • 6,138
  • 12
  • 49
  • 61
  • 7
    i dont think so, but if you do need to refer to each Ticket separately, you could store the tickets in an arraylist or array, and refer to it using index – experiment unit 1998X Jul 08 '22 at 17:56
  • 1
    right. A quick search gave me this link which says: no, you cant assign dynamic variable names. https://stackoverflow.com/q/6729605/16034206 – experiment unit 1998X Jul 08 '22 at 17:59
  • 2
    thats what arrays or other collections are for. – OldProgrammer Jul 08 '22 at 18:24
  • 1
    Dare I say you could if you could go completely meta and write a java program that generates java source code that creates the variables you need in a dynamic way and load it at runtime? But I would *not* advise that. There should be no need to do so as there are much more easier ways to do so. – skubski Jul 08 '22 at 18:56
  • Each pass through the loop, an object gets created, then never referenced outside of the loop. Why even bother naming the result of `new Ticket()`? How does the name matter at all? – Kaan Jul 09 '22 at 04:17

0 Answers0