Monday 15 September 2014

java - How do I allow for infinite object instantiation? -



java - How do I allow for infinite object instantiation? -

this question has reply here:

creating arraylist of objects 2 answers

i'm stuck on java program. program, city-builder game, needs ability instantiate objects @ moment based on user's whim, , number of objects needs infinite.

the programme going have building type object.

(i know how instantiate new objects; so...

building building1 = new building();

...)

however, methodology isn't acceptable program. programme needs able instantiate new building objects on fly. imagine user has alternative click on button places new building world. click place new building world 0 times, or can click 5,000 times, consequently placing 5,000 buildings world.

i don't want have instantiate 5,000 objects, so:

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

any suggestions how might code it? in advance!

there 2 things need know appear asking do.

the first collection of (in case) building objects. create 1 in java line

arraylist<building> buildings = new arraylist<building>();

in code, if execute next 2 lines, create building , add together list:

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

after that, building remain in list, after building variable goes out of scope. have create sure buildings object referred object not go out of scope period want maintain list of buildings.

the sec thing realize don't have have 500 different instantiation statements create 500 buildings. if user clicks button, there code can execute (depending on ui framework have, etc.); code can create building , set in list. same code can execute button click; create building , set in list. if there's alternative number of buildings create, click code can @ alternative , create many buildings supposed to, in loop, , set them in list.

please clarify question if doesn't cover need.

edit: setting value on object in array

building building = buildings.get(desiredindex); building.setdesiredvalue("42");

you alternately use:

buildings.get(desiredindex).setdesiredvalue("42");

but think that's harder read.

just fyi, "infinite" numbers of objects supported on machine infinite memory; took mean "determined @ runtime".

java object constructor instantiation objectinstantiation

No comments:

Post a Comment