Name an object according to another variable's value

Hello, i was wondering if there was anyway to name an object according to a variable’s value.
for example something like this:


for(int i = 0; i<20; i++){
Person "person"+i = new Person();
}

Use an array:


Person[] people = new Person[20];
for (int i=0; i<people.length; i++)
{
  people[i] = new Person();
}

Or an ArrayList if you don’t know the length, or a Map if they’re not laid out in order (google them!).

I could be misunderstanding it, but it seems you want other types / objects as indexes for arrays
like in php


$color["background"] = stuff();
$color["foreground"] = stuff();

well anyway, if you would want a string or other value(other than an integer) that relates to an object, I would use a map like Orangy Tang already said, especially a hashmap
then you have pairs of (eg)strings and objects

hashMap.put("myObject", someObject);
hashMap.get("myObject");

Remember that you can also have enums or constant ints and in many cases its better than a string.
checking a string is not really or good or fast thing to do.


public static final int MODE_GAME = 0;
public static final int MODE_MENU = 1;

objects[MODE_GAME] = new GameObject();
objects[MODE_MENU] = new MenuObject();

whatever, kinda pseudo, but you get the idea.

To clarify, you cannot dynamically name an object. In your example, your trying to end with a name for your objects with “person1”, “person2”, etc.
Use the methods in the previous posts.

You could use Javac to dynamically name something if you want to be completely retarded. :yawn:

what would even be the point of dynamically naming an object in a closed loop like that? is this a joke?

I imagine it’s a lack on programming experience, instead of a joke.

@counterp I think the closed loop part was just a way of demonstrating what jynx meant. I see no reason why you would ever have a for loop like that regardless of whether dynamically naming an object is possible. Although that too could be attributed to lack of experience with Java if someone didn’t know that an Object declared in a loop is only accessible in that same loop.