Reputation: 13
im stuck with the dilemma of defining multiple objects with different names, i would like to define an amount of objects according to an amount i need taken from another part of the program
the part object(i) isnt correct, i just put it there to illustrate my problem
for(int i = 1; i <= amountOfObjectsNeeded; i++){
someclass object(i) = new someclass();
}
does anyone know how to get around this?
Upvotes: 1
Views: 150
Reputation: 114847
Consider using a map, if you want to assign names/ids to your objects and access them later on by those names:
Map<String, SomeClass> map = new HashMap<String, SomeClass>();
for (int i = 0; i < numberOfObjects; i++) {
String name = getNameForObjectNr(i);
map.put(name, new SomeClass());
}
// later on
SomeClass someClass = map.get(someName); // to read an instance from the map
Upvotes: 2
Reputation: 68172
You should use an array in this case:
Someclass[] array = new Someclass[amountOfObjectsNeeded];
for (int i = 0; i < amountOfObjectsNeeded; i++) {
array[i] = new Someclass();
}
Note how the loop starts from 0 rather than 1--arrays in Java are indexed starting at 0.
Upvotes: 5