[squeak-dev] removing from a collection while enumerating it
leves at elte.hu
Thu Jul 4 18:03:41 UTC 2013
On Thu, 4 Jul 2013, Chris Muller wrote:
> Hm, I did not know about removeAllSuchThat:, but in looking at it, I
> find two things "wrong" with it. 1) the superclass implementation in
> Collection makes a copy of the collection, which is the basis of my
> reason to use reverseDo: instead of enumerating a copy myself.
Because there's no other choice. There are collections (e.g. Array) from
which you can't remove elements.
> But I'm using an OC and OC overrides it without making the copy.
> That's good, but I also need to know which elements were removed. I
> ended up doing it like:
> myCollection removeAllSuchThat: [ : each | each meetsMyCondition
> and: [ each doSomething. true ] ]
> I think it would be nice if removeAllSuchThat: could be similar to
> remove: in this respect, but at least, unlike Java, Smalltalk lets me
> put any "doSomething" expression in the block as long as it finally
> evaluates to a boolean.
As you pointed out, you can extend the behavior of the current
implementation and collect the removed elements. If it were the other way,
then you couldn't avoid the overhead of collecting and returning the
removed elements. So I think it is the better way.
> On Wed, Jul 3, 2013 at 4:19 PM, Bert Freudenberg <bert at freudenbergs.de> wrote:
>> On 03.07.2013, at 11:27, Chris Muller <asqueaker at gmail.com> wrote:
>>> 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?
>> What's wrong with removeAllSuchThat:?
>> - Bert -
More information about the Squeak-dev