Collection implementations and fail-fast iterator problems.
I have a simulation where I visit every element in a Collection. While
visiting these, I may find out that I want to add a new element, or
remove some later-occurring element before I get to it. I have a few
Collections like this.
I'd like to avoid having to keep track of "to-be-deleted" and
"to-be-added" elements, but I don't see an elegant way to handle both
those cases without getting a ConcurrentModificationError.
The elements can (and do) have a flag on them to mark that they are
ready for deletion, but that still leaves a problem for the addition,
and I also have to explicitly check that flag during iteration (or after
the iteration). Not ideal IMO.
Is there a better approach? Is my design fundamentally flawed? Last time
I came across this program, I used toArray (basically, just to get a
copy), and iterated over that, and used a separate collection to hold
what needs to be added/removed. It was messy code and I'd rather avoid
that approach if possible.
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>