简体   繁体   中英

Destroying multiple references to the same object in Java

Say I have a Citizen class and a Population class. A population contains a set of citizens.

In this simulation, citizens may die. Currently, to represent the death of a citizen, I destroy all references to that citizen object, as a Population may not contain a dead citizen.

I want to be able to create multiple Population objects where citizen overlap is possible. Ex. Citizen C may belong to both Population A and Population B. However, this makes citizen deaths difficult as I would have to remove citizen C from both A and B on the event of a death. Sometimes A and B aren't even in the same scope.

Also, each citizen must belong to at least one population.

Generally speaking, how would I organize my Population and Citizen class to ensure that a citizen is completely removed from all instances of Population upon that citizen's death?

I'm thinking of making Citizen a member class of Population, but I do not know where to go from there.

Thanks.

There are a number of solutions to this problem like observer pattern etc but if having a reverse link from citizen to population is already considered too heavy, any solution in that direction is probably too heavy weight.

If you really don't want a reverse link (though probably the best option and memory probably won't suffer that badly), you can always have an isDead() on the citizen.

Any population must then either periodically or upon access prune the dead citizens.

If you think of it as a real life scenario, if a citizen belongs to few populations, then in case of death those populations need to be informed (lets say, if he is French and American, both countries need to know that to cancel his passport etc.). So the observer pattern here, as @nablex suggested, sounds like the most appropriate solution. Have a class, like 'MinistryOfDeath' or something, that will inform the relevant populations.

When compared to List<Population , an int[] with numbering all the populations would save half the memory only on machines with above something like 32 GB, where compressed OOPs don't get suffice, otherwise nothing.

Using a short[] saves half the memory when compared to int[] . Using a BitSet saves much more. You could even run your own, eg, 2 long s for a fixed set of 128 populations and use only 16 bytes per Citizen . This is much much cheaper than the forward links from Population s to Citizen s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM