How to name objects with variables?

I have a class for a game, and i want to create more objects from that class. For that, i’d like to use a for loop. How to name the separate objects correctly? It is important, that later on i’d like to use their functions too.

Well, let’s say you want to make a Player class for a multiplayer game. The most naive way to instantiate them would be

Player p1 = new Player();
Player p2 = new Player();

and so on, which is tedious and what you’re trying to avoid. To put this in a loop, one way to do it is to use an array

Player players[];//declare the array
players = new Player[4];//create the array references (not the objects)

//loop initializes the objects in the array
for(int i = 0; i  <  players.length;  i++ ){
  players[i] = new Player();
}

//objects can now be addressed individually by index...
players[0].move();
players[3].move();

If you aren’t sure how many objects you’ll need to store, look into the ArrayList data structure. If you want to address them by key-value pairs, look into hashmaps.

4 Likes