[squeak-dev] removing from a collection while enumerating it

Louis LaBrunda Lou at Keystone-Software.com
Wed Jul 3 21:18:06 UTC 2013


Hi Chris,

>I have a case where I need to remove certain entries from an
>OrderedCollection that will be called very frequently.  I therefore
>want to avoid copying the collection (to safely remove while
>enumerating) but it seems #reverseDo: can do what I want.

>  myCollection reverseDo: [ : each | each meetsSomeCriteria ifTrue: [
>myCollection remove: each ] ]

>Does anyone see any problem with doing this?

I don't *think* I have a problem but that code could be fragile.  Normally
I add the entry to a delete/remove list and delete them after I have
finished running the collection.  Something like:

myCollection do: [:each | each meetsSomeCriteria ifTrue: [removeList add:
each ] ].
myCollection removeAll: removeList.

or even better:

removeList := myCollection select: [:each | each meetsSomeCriteria].
myCollection removeAll: removeList.

Lou
-----------------------------------------------------------
Louis LaBrunda
Keystone Software Corp.
SkypeMe callto://PhotonDemon
mailto:Lou at Keystone-Software.com http://www.Keystone-Software.com



More information about the Squeak-dev mailing list