Imagine an array of objects.
int MAX_ALLOWED = 5;
Object [] object = new Object [MAX_ALLOWED];
Suppose the object was a unit for a game with its respective location. When the user presses a button called "spawn unit" the code will be:
unit [] = new Object (location);
As you can see there is no identifier in the [ _ ] so this presents the problem. I don't know what to put in here.If I put 0 it will over-ride the memory of the object at 0 every-time I create an object.
When accessing a particular object or unit.
for (int i = 0; i <= unit.length; i++)
{
if (location = unit [i].get_Location)
{
move (unit [i]);
}
}
But doing this will give me a null-pointer exception if I access an element after 0.
Arrays should be avoided for the general problem of storing lists of things. Instead, Collections are far more programmer friendly, and still pretty fast.
In your case, using an array would mean having to keep the index of the last used element and manage the size, etc, etc. Using a List
is way easier:
List<Unit> units = new ArrayList<Unit>();
then to use, simply:
units.add(new Unit());
if you want to restrict the size, before you add:
if (units.size() == MAX_ALLOWED) {
// do something else
}
To iterate over the elements:
for (Unit unit : units) {
// do something with unit
}
A good thing about Lists is they will grow in size as needed, although in your case this may not be needed as you seem to want a fixed maximum.