Search code examples
javavariablesloopsprimitive

Increment variable names?


Okay so for what I am doing i need to increment my variables name, so for example int Taco1 = 23432..... int Taco2 = 234235656..... int Taco3 = 11111.......

But instead i need it to be a variable like

 int X = 0;
 some method with loop or recursion()
 int Taco(X) = bla bla bla
 x++

Trying to get my variable names to auto name themselves incremented by 1 every time, so they don't overwrite themselves. If this is impossible then my apologies.


Solution

  • You can't do this in Java and more importantly, you don't want to do this as this isn't how Java works. In fact variable names aren't nearly as important as you think and hardly even exist in compiled code. What is much more important is that you are able to get a reference to your objects in as easy and reliable a way as possible. This can involve an array, an ArrayList (likely what you want here), a LinkedList, a Map such as a HashMap, a Set, and other types of collections.

    For example:

    List<Taco> tacoList = new ArrayList<Taco>();
    for (int i = 0; i < MAX_TACOS; i++) {
       tacoList.add(new Taco(i));
    }