Scott Nimrod
Scott Nimrod

Reputation: 11595

How can I tell if I am iterating through a collection before I attempt to modify the collection?

I want to remove an item from a collection only if I am not currently iterating through it.

Is there a way to know that it is safe to remove an item from a collection without using exception handling as part of the logic?

Upvotes: 0

Views: 51

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

Not for built-in collections.

Internally most collections have some sort of version information that allows corresponding iterators to check if collection was modified, but there is no "list of iterators over this collection" you are looking for.

You can create your own collection type that gives you such information, but be very careful to handle multithreading cases (if needed) and figure out how you want to handle corner cases like "got iterator, change collection, start iteration" or "got iterator and never use it, collection blocked from changes".

Upvotes: 3

Related Questions