Good evening,
I’ve had some experience with programming, but these last months were my first foray into OOP with Java. I was toying around with a game and have a general question about what approach/structure I should use to hold my objects. My specific case:
I have a game that has one object. Throughout the course of the game, multiple instances of this object are created, interact on-screen (via the chosen physics) and either disappear off-screen or are “destroyed” (so… also disappear). So, the collection that holds these objects is being constantly iterated over, tested for conditions, and objects are removed as these conditions are satisfied. At the same time, user interactions (button clicks) add a new object to this collection. (can think of them as bullets)
I’ve read about a couple of approaches that could work, but before I commit to one, I would like some general input on what may be the least-computationally expensive. Here’s some that I’ve seen so far:
- Use an ArrayList. Then, either use a concurrent protected version (like a synchronizedList) when using the iterators or synchronize all your access calls. I hear that synchronization can be computationally heavy; so should this be avoided? I hear CopyOnWriteArrayList can help avoid ConcurrentModificationExceptions, but that it is not good for arrays which are rapidly and dynamically modified, as it creates a copy on write.
- Use an ArrayList, but save all ‘remove’ and ‘add’ functions for AFTER the iterator has completed its operations (to avoid concurrent modifications). THEN, compute all the additions and subtractions afterwards.
- Same as (2) but use a ‘for’ loop, since there shouldn’t be any concurrent modification (thus, no worries about iterator overrun)
- Use another structure. I’ve read a forum where a structure called a ‘bag’ was made for dynamic collections. Any thoughts on this?
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/Bag.html - …
I hope my question is clear. I am looking for good approaches; recommendations for a sort of ‘best practices’ so I can start on the right foot. At the get-go, I used (1), but ran into some ConcurrentModificationException-s. Before I tore through the code and changed a lot of things, I thought I would get some experienced advice first.
Thank you for any help you can offer!