Search code examples
javaobjectconstructorinstantiationobjectinstantiation

How do I allow for infinite object instantiation?


I'm currently stuck on a Java program. My program, a city-builder game, needs the ability to instantiate objects at any moment based on the user's whim, and the number of objects needs to be infinite.

The program is going to have a Building type object.

(I know how to instantiate new objects; like so...

Building building1 = new Building();

...)

However, this methodology isn't acceptable for my program. My program needs to be able to instantiate new Building objects on the fly. Imagine the user has the option to click on a button that places a new Building into the world. They could click to place a new Building into the world zero times, or they can click 5,000 times, consequently placing 5,000 Buildings into the world.

I obviously don't want to have to instantiate 5,000 objects, like so:

Building building1 = new Building();
Building building2 = new Building();
...
Building building5000 = new Building();

Any suggestions to how you might code it? Thanks in advance!


Solution

  • There are two things you need to know about to do what you appear to be asking to do.

    The first is a collection of (in this case) Building objects. You could create one in Java with a line like

    ArrayList<Building> buildings = new ArrayList<Building>();
    

    In your code, if you execute the following two lines, you will create a building and add it to the list:

    Building building = new Building();
    buildings.add(building);
    

    After that, the building will remain in your list, even after the building variable goes out of scope. You will have to make sure the buildings object is referred to by an object that does not go out of scope for the period you want to keep the list of buildings.

    The second thing to realize is that you don't have to have 500 different instantiation statements to create 500 buildings. If the user clicks a button, there is code that can execute (depending on what UI framework you have, etc.); that code can create a building and put it in the list. That same code can execute for another button click; it would create another building and put it in the list. If there's an option for the number of buildings to create, then the click code can look at that option and create however many buildings it is supposed to, in a loop, and put them in the list.

    Please clarify your question if this doesn't cover what you need.

    EDIT: setting a value on an object in the array

    Building building = buildings.get(desiredIndex);
    building.setDesiredValue("42");
    

    You could alternately use:

    buildings.get(desiredIndex).setDesiredValue("42");
    

    but I think that's harder to read.

    Just FYI, "infinite" numbers of objects could only be supported on a machine with infinite memory; I took that to mean "determined at runtime".